2 # Copyright (c) 1998-2000, 2002, 2003, 2004, 2005, 2006 Stephen McCamant.
4 # This module is free software; you can redistribute and/or modify
5 # it under the same terms as Perl itself.
7 # This is based on the module of the same name by Malcolm Beattie,
8 # but essentially none of his code remains.
12 use B qw(class main_root main_start main_cv svref_2object opnumber perlstring
13 OPf_WANT OPf_WANT_VOID OPf_WANT_SCALAR OPf_WANT_LIST
14 OPf_KIDS OPf_REF OPf_STACKED OPf_SPECIAL OPf_MOD OPf_PARENS
15 OPpLVAL_INTRO OPpOUR_INTRO OPpENTERSUB_AMPER OPpSLICE OPpKVSLICE
17 OPpTRANS_SQUASH OPpTRANS_DELETE OPpTRANS_COMPLEMENT OPpTARGET_MY
18 OPpEXISTS_SUB OPpSORT_NUMERIC OPpSORT_INTEGER OPpREPEAT_DOLIST
19 OPpSORT_REVERSE OPpMULTIDEREF_EXISTS OPpMULTIDEREF_DELETE
20 OPpSPLIT_ASSIGN OPpSPLIT_LEX
21 OPpPADHV_ISKEYS OPpRV2HV_ISKEYS
23 OPpMULTICONCAT_APPEND OPpMULTICONCAT_STRINGIFY OPpMULTICONCAT_FAKE
24 OPpTRUEBOOL OPpINDEX_BOOLNEG
25 SVf_IOK SVf_NOK SVf_ROK SVf_POK SVpad_OUR SVf_FAKE SVs_RMG SVs_SMG
26 SVs_PADTMP SVpad_TYPED
28 PMf_KEEP PMf_GLOBAL PMf_CONTINUE PMf_EVAL PMf_ONCE
29 PMf_MULTILINE PMf_SINGLELINE PMf_FOLD PMf_EXTENDED PMf_EXTENDED_MORE
32 MDEREF_AV_pop_rv2av_aelem
33 MDEREF_AV_gvsv_vivify_rv2av_aelem
34 MDEREF_AV_padsv_vivify_rv2av_aelem
35 MDEREF_AV_vivify_rv2av_aelem
38 MDEREF_HV_pop_rv2hv_helem
39 MDEREF_HV_gvsv_vivify_rv2hv_helem
40 MDEREF_HV_padsv_vivify_rv2hv_helem
41 MDEREF_HV_vivify_rv2hv_helem
64 # List version-specific constants here.
65 # Easiest way to keep this code portable between version looks to
66 # be to fake up a dummy constant that will never actually be true.
67 foreach (qw(OPpSORT_INPLACE OPpSORT_DESCEND OPpITER_REVERSED OPpCONST_NOVER
68 OPpPAD_STATE PMf_SKIPWHITE RXf_SKIPWHITE
69 PMf_CHARSET PMf_KEEPCOPY PMf_NOCAPTURE CVf_ANONCONST
70 CVf_LOCKED OPpREVERSE_INPLACE OPpSUBSTR_REPL_FIRST
71 PMf_NONDESTRUCT OPpCONST_ARYBASE OPpEVAL_BYTES
72 OPpLVREF_TYPE OPpLVREF_SV OPpLVREF_AV OPpLVREF_HV
73 OPpLVREF_CV OPpLVREF_ELEM SVpad_STATE)) {
74 eval { B->import($_) };
76 *{$_} = sub () {0} unless *{$_}{CODE};
81 # (See also BUGS section at the end of this file)
83 # - finish tr/// changes
84 # - add option for even more parens (generalize \&foo change)
85 # - left/right context
86 # - copy comments (look at real text with $^P?)
87 # - avoid semis in one-statement blocks
88 # - associativity of &&=, ||=, ?:
89 # - ',' => '=>' (auto-unquote?)
90 # - break long lines ("\r" as discretionary break?)
91 # - configurable syntax highlighting: ANSI color, HTML, TeX, etc.
92 # - more style options: brace style, hex vs. octal, quotes, ...
93 # - print big ints as hex/octal instead of decimal (heuristic?)
94 # - handle 'my $x if 0'?
95 # - version using op_next instead of op_first/sibling?
96 # - avoid string copies (pass arrays, one big join?)
99 # Current test.deparse failures
100 # comp/hints 6 - location of BEGIN blocks wrt. block openings
101 # run/switchI 1 - missing -I switches entirely
102 # perl -Ifoo -e 'print @INC'
103 # op/caller 2 - warning mask propagates backwards before warnings::register
104 # 'use warnings; BEGIN {${^WARNING_BITS} eq "U"x12;} use warnings::register'
105 # op/getpid 2 - can't assign to shared my() declaration (threads only)
106 # 'my $x : shared = 5'
107 # op/override 7 - parens on overridden require change v-string interpretation
108 # 'BEGIN{*CORE::GLOBAL::require=sub {}} require v5.6'
109 # c.f. 'BEGIN { *f = sub {0} }; f 2'
110 # op/pat 774 - losing Unicode-ness of Latin1-only strings
111 # 'use charnames ":short"; $x="\N{latin:a with acute}"'
112 # op/recurse 12 - missing parens on recursive call makes it look like method
114 # op/subst 90 - inconsistent handling of utf8 under "use utf8"
115 # op/taint 29 - "use re 'taint'" deparsed in the wrong place wrt. block open
116 # op/tiehandle compile - "use strict" deparsed in the wrong place
118 # ext/B/t/xref 11 - line numbers when we add newlines to one-line subs
119 # ext/Data/Dumper/t/dumper compile
120 # ext/DB_file/several
122 # ext/Ernno/Errno warnings
123 # ext/IO/lib/IO/t/io_sel 23
124 # ext/PerlIO/t/encoding compile
125 # ext/POSIX/t/posix 6
126 # ext/Socket/Socket 8
127 # ext/Storable/t/croak compile
128 # lib/Attribute/Handlers/t/multi compile
129 # lib/bignum/ several
133 # lib/ExtUtils/t/bytes 4
134 # lib/File/DosGlob compile
135 # lib/Filter/Simple/t/data 1
136 # lib/Math/BigInt/t/constant 1
137 # lib/Net/t/config Deparse-warning
138 # lib/overload compile
139 # lib/Switch/ several
141 # lib/Test/Simple several
143 # lib/Tie/File/t/29_downcopy 5
149 # True when deparsing via $deparse->coderef2text; false when deparsing the
153 # (local($a), local($b)) and local($a, $b) have the same internal
154 # representation but the short form looks better. We notice we can
155 # use a large-scale local when checking the list, but need to prevent
156 # individual locals too. This hash holds the addresses of OPs that
157 # have already had their local-ness accounted for. The same thing
161 # CV for current sub (or main program) being deparsed
164 # Cached hash of lexical variables for curcv: keys are
165 # names prefixed with "m" or "o" (representing my/our), and
166 # each value is an array with two elements indicating the cop_seq
167 # of scopes in which a var of that name is valid and a third ele-
168 # ment referencing the pad name.
171 # COP for statement being deparsed
174 # name of the current package for deparsed code
177 # array of [cop_seq, CV, is_format?, name] for subs and formats we still
178 # want to deparse. The fourth element is a pad name thingy for lexical
179 # subs or a string for special blocks. For other subs, it is undef. For
180 # lexical subs, CV may be undef, indicating a stub declaration.
183 # as above, but [name, prototype] for subs that never got a GV
185 # subs_done, forms_done:
186 # keys are addresses of GVs for subs and formats we've already
187 # deparsed (or at least put into subs_todo)
190 # keys are names of subs for which we've printed declarations.
191 # That means we can omit parentheses from the arguments. It also means we
192 # need to put CORE:: on core functions of the same name.
195 # True when deparsing the replacement part of a substitution.
198 # True when deparsing the argument to \.
203 # cuddle: ' ' or '\n', depending on -sC
208 # A little explanation of how precedence contexts and associativity
211 # deparse() calls each per-op subroutine with an argument $cx (short
212 # for context, but not the same as the cx* in the perl core), which is
213 # a number describing the op's parents in terms of precedence, whether
214 # they're inside an expression or at statement level, etc. (see
215 # chart below). When ops with children call deparse on them, they pass
216 # along their precedence. Fractional values are used to implement
217 # associativity ('($x + $y) + $z' => '$x + $y + $y') and related
218 # parentheses hacks. The major disadvantage of this scheme is that
219 # it doesn't know about right sides and left sides, so say if you
220 # assign a listop to a variable, it can't tell it's allowed to leave
221 # the parens off the listop.
224 # 26 [TODO] inside interpolation context ("")
225 # 25 left terms and list operators (leftward)
229 # 21 right ! ~ \ and unary + and -
234 # 16 nonassoc named unary operators
235 # 15 nonassoc < > <= >= lt gt le ge
236 # 14 nonassoc == != <=> eq ne cmp
243 # 7 right = += -= *= etc.
245 # 5 nonassoc list operators (rightward)
249 # 1 statement modifiers
250 # 0.5 statements, but still print scopes as do { ... }
254 # Nonprinting characters with special meaning:
255 # \cS - steal parens (see maybe_parens_unop)
256 # \n - newline and indent
257 # \t - increase indent
258 # \b - decrease indent ('outdent')
259 # \f - flush left (no indent)
260 # \cK - kill following semicolon, if any
262 # Semicolon handling:
263 # - Individual statements are not deparsed with trailing semicolons.
264 # (If necessary, \cK is tacked on to the end.)
265 # - Whatever code joins statements together or emits them (lineseq,
266 # scopeop, deparse_root) is responsible for adding semicolons where
268 # - use statements are deparsed with trailing semicolons because they are
269 # immediately concatenated with the following statement.
270 # - indent() removes semicolons wherever it sees \cK.
273 BEGIN { for (qw[ const stringify rv2sv list glob pushmark null aelem
274 kvaslice kvhslice padsv
275 nextstate dbstate rv2av rv2hv helem custom ]) {
276 eval "sub OP_\U$_ () { " . opnumber($_) . "}"
279 # _pessimise_walk(): recursively walk the optree of a sub,
280 # possibly undoing optimisations along the way.
282 sub _pessimise_walk {
283 my ($self, $startop) = @_;
285 return unless $$startop;
287 for ($op = $startop; $$op; $prevop = $op, $op = $op->sibling) {
288 my $ppname = $op->name;
290 # pessimisations start here
292 if ($ppname eq "padrange") {
294 # the original optimisation either (1) changed this:
295 # pushmark -> (various pad and list and null ops) -> the_rest
296 # or (2), for the = @_ case, changed this:
297 # pushmark -> gv[_] -> rv2av -> (pad stuff) -> the_rest
299 # padrange ----------------------------------------> the_rest
300 # so we just need to convert the padrange back into a
301 # pushmark, and in case (1), set its op_next to op_sibling,
302 # which is the head of the original chain of optimised-away
303 # pad ops, or for (2), set it to sibling->first, which is
304 # the original gv[_].
306 $B::overlay->{$$op} = {
309 private => ($op->private & OPpLVAL_INTRO),
313 # pessimisations end here
315 if (class($op) eq 'PMOP') {
316 if (ref($op->pmreplroot)
317 && ${$op->pmreplroot}
318 && $op->pmreplroot->isa( 'B::OP' ))
320 $self-> _pessimise_walk($op->pmreplroot);
323 # pessimise any /(?{...})/ code blocks
325 my $code_list = $op->code_list;
327 $self->_pessimise_walk($code_list);
329 elsif (${$re = $op->pmregexp} && ${$cv = $re->qr_anoncv}) {
330 $code_list = $cv->ROOT # leavesub
333 $self->_pessimise_walk($code_list);
337 if ($op->flags & OPf_KIDS) {
338 $self-> _pessimise_walk($op->first);
345 # _pessimise_walk_exe(): recursively walk the op_next chain of a sub,
346 # possibly undoing optimisations along the way.
348 sub _pessimise_walk_exe {
349 my ($self, $startop, $visited) = @_;
351 no warnings 'recursion';
353 return unless $$startop;
354 return if $visited->{$$startop};
356 for ($op = $startop; $$op; $prevop = $op, $op = $op->next) {
357 last if $visited->{$$op};
358 $visited->{$$op} = 1;
359 my $ppname = $op->name;
361 /^((and|d?or)(assign)?|(map|grep)while|range|cond_expr|once)$/
362 # entertry is also a logop, but its op_other invariably points
363 # into the same chain as the main execution path, so we skip it
365 $self->_pessimise_walk_exe($op->other, $visited);
367 elsif ($ppname eq "subst") {
368 $self->_pessimise_walk_exe($op->pmreplstart, $visited);
370 elsif ($ppname =~ /^(enter(loop|iter))$/) {
371 # redoop and nextop will already be covered by the main block
373 $self->_pessimise_walk_exe($op->lastop, $visited);
376 # pessimisations start here
380 # Go through an optree and "remove" some optimisations by using an
381 # overlay to selectively modify or un-null some ops. Deparsing in the
382 # absence of those optimisations is then easier.
384 # Note that older optimisations are not removed, as Deparse was already
385 # written to recognise them before the pessimise/overlay system was added.
388 my ($self, $root, $start) = @_;
390 no warnings 'recursion';
391 # walk tree in root-to-branch order
392 $self->_pessimise_walk($root);
395 # walk tree in execution order
396 $self->_pessimise_walk_exe($start, \%visited);
402 return class($op) eq "NULL";
406 # Add a CV to the list of subs that still need deparsing.
410 my($cv, $is_form, $name) = @_;
411 my $cvfile = $cv->FILE//'';
412 return unless ($cvfile eq $0 || exists $self->{files}{$cvfile});
414 if ($cv->OUTSIDE_SEQ) {
415 $seq = $cv->OUTSIDE_SEQ;
416 } elsif (!null($cv->START) and is_state($cv->START)) {
417 $seq = $cv->START->cop_seq;
421 my $stash = $cv->STASH;
422 if (class($stash) eq 'HV') {
423 $self->{packs}{$stash->NAME}++;
425 push @{$self->{'subs_todo'}}, [$seq, $cv, $is_form, $name];
429 # Pop the next sub from the todo list and deparse it
433 my $ent = shift @{$self->{'subs_todo'}};
434 my ($seq, $cv, $is_form, $name) = @$ent;
436 # any 'use strict; package foo' that should come before the sub
437 # declaration to sync with the first COP of the sub
439 if ($cv and !null($cv->START) and is_state($cv->START)) {
440 $pragmata = $self->pragmata($cv->START);
443 if (ref $name) { # lexical sub
446 my $flags = $name->FLAGS;
448 !$cv || $seq <= $name->COP_SEQ_RANGE_LOW
449 ? $self->keyword($flags & SVpad_OUR
451 : $flags & SVpad_STATE
455 # XXX We would do $self->keyword("sub"), but ‘my CORE::sub’
456 # doesn’t work and ‘my sub’ ignores a &sub in scope. I.e.,
457 # we have a core bug here.
458 push @text, "sub " . substr $name->PVX, 1;
461 push @text, " " . $self->deparse_sub($cv);
462 $text[-1] =~ s/ ;$/;/;
468 return $pragmata . join "", @text;
472 $name //= $self->gv_name($gv);
474 return $pragmata . $self->keyword("format") . " $name =\n"
475 . $self->deparse_format($cv). "\n";
478 if ($name eq "BEGIN") {
479 $use_dec = $self->begin_is_use($cv);
480 if (defined ($use_dec) and $self->{'expand'} < 5) {
481 return $pragmata if 0 == length($use_dec);
483 # XXX bit of a hack: Test::More's use_ok() method
484 # builds a fake use statement which deparses as, e.g.
485 # use Net::Ping (@{$args[0];});
486 # As well as being superfluous (the use_ok() is deparsed
487 # too) and ugly, it fails under use strict and otherwise
488 # makes use of a lexical var that's not in scope.
496 \s*\#line\ \d+\ \".*"\s*
503 $use_dec =~ s/^(use|no)\b/$self->keyword($1)/e;
507 if ($self->{'linenums'}) {
508 my $line = $gv->LINE;
509 my $file = $gv->FILE;
510 $l = "\n\f#line $line \"$file\"\n";
514 if (class($cv->STASH) ne "SPECIAL") {
515 $stash = $cv->STASH->NAME;
516 if ($stash ne $self->{'curstash'}) {
517 $p = $self->keyword("package") . " $stash;\n";
518 $name = "$self->{'curstash'}::$name" unless $name =~ /::/;
519 $self->{'curstash'} = $stash;
523 return "$pragmata$p$l$use_dec";
525 if ( $name !~ /::/ and $self->lex_in_scope("&$name")
526 || $self->lex_in_scope("&$name", 1) )
528 $name = "$self->{'curstash'}::$name";
529 } elsif (defined $stash) {
530 $name =~ s/^\Q$stash\E::(?!\z|.*::)//;
532 my $ret = "$pragmata${p}${l}" . $self->keyword("sub") . " $name "
533 . $self->deparse_sub($cv);
534 $self->{'subs_declared'}{$name} = 1;
540 # Return a "use" declaration for this BEGIN block, if appropriate
542 my ($self, $cv) = @_;
543 my $root = $cv->ROOT;
544 local @$self{qw'curcv curcvlex'} = ($cv);
545 local $B::overlay = {};
546 $self->pessimise($root, $cv->START);
548 #B::walkoptree($cv->ROOT, "debug");
549 my $lineseq = $root->first;
550 return if $lineseq->name ne "lineseq";
552 my $req_op = $lineseq->first->sibling;
553 return if $req_op->name ne "require";
555 # maybe it's C<require expr> rather than C<require 'foo'>
556 return if ($req_op->first->name ne 'const');
559 if ($req_op->first->private & OPpCONST_BARE) {
560 # Actually it should always be a bareword
561 $module = $self->const_sv($req_op->first)->PV;
562 $module =~ s[/][::]g;
566 $module = $self->const($self->const_sv($req_op->first), 6);
570 my $version_op = $req_op->sibling;
571 return if class($version_op) eq "NULL";
572 if ($version_op->name eq "lineseq") {
573 # We have a version parameter; skip nextstate & pushmark
574 my $constop = $version_op->first->next->next;
576 return unless $self->const_sv($constop)->PV eq $module;
577 $constop = $constop->sibling;
578 $version = $self->const_sv($constop);
579 if (class($version) eq "IV") {
580 $version = $version->int_value;
581 } elsif (class($version) eq "NV") {
582 $version = $version->NV;
583 } elsif (class($version) ne "PVMG") {
584 # Includes PVIV and PVNV
585 $version = $version->PV;
587 # version specified as a v-string
588 $version = 'v'.join '.', map ord, split //, $version->PV;
590 $constop = $constop->sibling;
591 return if $constop->name ne "method_named";
592 return if $self->meth_sv($constop)->PV ne "VERSION";
595 $lineseq = $version_op->sibling;
596 return if $lineseq->name ne "lineseq";
597 my $entersub = $lineseq->first->sibling;
598 if ($entersub->name eq "stub") {
599 return "use $module $version ();\n" if defined $version;
600 return "use $module ();\n";
602 return if $entersub->name ne "entersub";
604 # See if there are import arguments
607 my $svop = $entersub->first->sibling; # Skip over pushmark
608 return unless $self->const_sv($svop)->PV eq $module;
610 # Pull out the arguments
611 for ($svop=$svop->sibling; index($svop->name, "method_") != 0;
612 $svop = $svop->sibling) {
613 $args .= ", " if length($args);
614 $args .= $self->deparse($svop, 6);
618 my $method_named = $svop;
619 return if $method_named->name ne "method_named";
620 my $method_name = $self->meth_sv($method_named)->PV;
622 if ($method_name eq "unimport") {
626 # Certain pragmas are dealt with using hint bits,
627 # so we ignore them here
628 if ($module eq 'strict' || $module eq 'integer'
629 || $module eq 'bytes' || $module eq 'warnings'
630 || $module eq 'feature') {
634 if (defined $version && length $args) {
635 return "$use $module $version ($args);\n";
636 } elsif (defined $version) {
637 return "$use $module $version;\n";
638 } elsif (length $args) {
639 return "$use $module ($args);\n";
641 return "$use $module;\n";
646 my ($self, $pack, $seen) = @_;
648 if (!defined $pack) {
653 $pack =~ s/(::)?$/::/;
655 $stash = \%{"main::$pack"};
659 $INC{"overload.pm"} ? overload::StrVal($stash) : $stash
661 my $stashobj = svref_2object($stash);
662 my %stash = $stashobj->ARRAY;
663 while (my ($key, $val) = each %stash) {
664 my $flags = $val->FLAGS;
665 if ($flags & SVf_ROK) {
666 # A reference. Dump this if it is a reference to a CV. If it
667 # is a constant acting as a proxy for a full subroutine, then
668 # we may or may not have to dump it. If some form of perl-
669 # space visible code must have created it, be it a use
670 # statement, or some direct symbol-table manipulation code that
671 # we will deparse, then we don’t want to dump it. If it is the
672 # result of a declaration like sub f () { 42 } then we *do*
673 # want to dump it. The only way to distinguish these seems
674 # to be the SVs_PADTMP flag on the constant, which is admit-
676 my $class = class(my $referent = $val->RV);
677 if ($class eq "CV") {
678 $self->todo($referent, 0);
680 $class !~ /^(AV|HV|CV|FM|IO|SPECIAL)\z/
681 # A more robust way to write that would be this, but B does
682 # not provide the SVt_ constants:
683 # ($referent->FLAGS & B::SVTYPEMASK) < B::SVt_PVAV
684 and $referent->FLAGS & SVs_PADTMP
686 push @{$self->{'protos_todo'}}, [$pack . $key, $val];
688 } elsif ($flags & (SVf_POK|SVf_IOK)) {
689 # Just a prototype. As an ugly but fairly effective way
690 # to find out if it belongs here is to see if the AUTOLOAD
691 # (if any) for the stash was defined in one of our files.
692 my $A = $stash{"AUTOLOAD"};
693 if (defined ($A) && class($A) eq "GV" && defined($A->CV)
694 && class($A->CV) eq "CV") {
696 next unless $AF eq $0 || exists $self->{'files'}{$AF};
698 push @{$self->{'protos_todo'}},
699 [$pack . $key, $flags & SVf_POK ? $val->PV: undef];
700 } elsif (class($val) eq "GV") {
701 if (class(my $cv = $val->CV) ne "SPECIAL") {
702 next if $self->{'subs_done'}{$$val}++;
704 # Ignore imposters (aliases etc)
705 my $name = $cv->NAME_HEK;
707 # avoid using $cv->GV here because if the $val GV is
708 # an alias, CvGV() could upgrade the real stash entry
710 next unless $name eq $key;
711 next unless $$stashobj == ${$cv->STASH};
714 next if $$val != ${$cv->GV};
719 if (class(my $cv = $val->FORM) ne "SPECIAL") {
720 next if $self->{'forms_done'}{$$val}++;
721 next if $$val != ${$cv->GV}; # Ignore imposters
724 if (class($val->HV) ne "SPECIAL" && $key =~ /::$/) {
725 $self->stash_subs($pack . $key, $seen);
735 foreach $ar (@{$self->{'protos_todo'}}) {
737 # Only print a constant if it occurs in the same package as a
738 # dumped sub. This is not perfect, but a heuristic that will
739 # hopefully work most of the time. Ideally we would use
740 # CvFILE, but a constant stub has no CvFILE.
741 my $pack = ($ar->[0] =~ /(.*)::/)[0];
742 next if $pack and !$self->{packs}{$pack}
744 my $body = defined $ar->[1]
746 ? " () {\n " . $self->const($ar->[1]->RV,0) . ";\n}"
747 : " (". $ar->[1] . ");"
749 push @ret, "sub " . $ar->[0] . "$body\n";
751 delete $self->{'protos_todo'};
759 while (length($opt = substr($opts, 0, 1))) {
761 $self->{'cuddle'} = " ";
762 $opts = substr($opts, 1);
763 } elsif ($opt eq "i") {
764 $opts =~ s/^i(\d+)//;
765 $self->{'indent_size'} = $1;
766 } elsif ($opt eq "T") {
767 $self->{'use_tabs'} = 1;
768 $opts = substr($opts, 1);
769 } elsif ($opt eq "v") {
770 $opts =~ s/^v([^.]*)(.|$)//;
771 $self->{'ex_const'} = $1;
778 my $self = bless {}, $class;
779 $self->{'cuddle'} = "\n";
780 $self->{'curcop'} = undef;
781 $self->{'curstash'} = "main";
782 $self->{'ex_const'} = "'???'";
783 $self->{'expand'} = 0;
784 $self->{'files'} = {};
785 $self->{'packs'} = {};
786 $self->{'indent_size'} = 4;
787 $self->{'linenums'} = 0;
788 $self->{'parens'} = 0;
789 $self->{'subs_todo'} = [];
790 $self->{'unquote'} = 0;
791 $self->{'use_dumper'} = 0;
792 $self->{'use_tabs'} = 0;
794 $self->{'ambient_arybase'} = 0;
795 $self->{'ambient_warnings'} = undef; # Assume no lexical warnings
796 $self->{'ambient_hints'} = 0;
797 $self->{'ambient_hinthash'} = undef;
800 while (my $arg = shift @_) {
802 $self->{'use_dumper'} = 1;
803 require Data::Dumper;
804 } elsif ($arg =~ /^-f(.*)/) {
805 $self->{'files'}{$1} = 1;
806 } elsif ($arg eq "-l") {
807 $self->{'linenums'} = 1;
808 } elsif ($arg eq "-p") {
809 $self->{'parens'} = 1;
810 } elsif ($arg eq "-P") {
811 $self->{'noproto'} = 1;
812 } elsif ($arg eq "-q") {
813 $self->{'unquote'} = 1;
814 } elsif (substr($arg, 0, 2) eq "-s") {
815 $self->style_opts(substr $arg, 2);
816 } elsif ($arg =~ /^-x(\d)$/) {
817 $self->{'expand'} = $1;
824 # Mask out the bits that L<warnings::register> uses
827 $WARN_MASK = $warnings::Bits{all} | $warnings::DeadBits{all};
834 # Initialise the contextual information, either from
835 # defaults provided with the ambient_pragmas method,
836 # or from perl's own defaults otherwise.
840 $self->{'arybase'} = $self->{'ambient_arybase'};
841 $self->{'warnings'} = defined ($self->{'ambient_warnings'})
842 ? $self->{'ambient_warnings'} & WARN_MASK
844 $self->{'hints'} = $self->{'ambient_hints'};
845 $self->{'hinthash'} = $self->{'ambient_hinthash'};
847 # also a convenient place to clear out subs_declared
848 delete $self->{'subs_declared'};
854 my $self = B::Deparse->new(@args);
855 # First deparse command-line args
856 if (defined $^I) { # deparse -i
857 print q(BEGIN { $^I = ).perlstring($^I).qq(; }\n);
859 if ($^W) { # deparse -w
860 print qq(BEGIN { \$^W = $^W; }\n);
862 if ($/ ne "\n" or defined $O::savebackslash) { # deparse -l and -0
863 my $fs = perlstring($/) || 'undef';
864 my $bs = perlstring($O::savebackslash) || 'undef';
865 print qq(BEGIN { \$/ = $fs; \$\\ = $bs; }\n);
867 my @BEGINs = B::begin_av->isa("B::AV") ? B::begin_av->ARRAY : ();
868 my @UNITCHECKs = B::unitcheck_av->isa("B::AV")
869 ? B::unitcheck_av->ARRAY
871 my @CHECKs = B::check_av->isa("B::AV") ? B::check_av->ARRAY : ();
872 my @INITs = B::init_av->isa("B::AV") ? B::init_av->ARRAY : ();
873 my @ENDs = B::end_av->isa("B::AV") ? B::end_av->ARRAY : ();
874 my @names = qw(BEGIN UNITCHECK CHECK INIT END);
875 my @blocks = \(@BEGINs, @UNITCHECKs, @CHECKs, @INITs, @ENDs);
877 my ($name, $blocks) = (shift @names, shift @blocks);
878 for my $block (@$blocks) {
879 $self->todo($block, 0, $name);
883 local($SIG{"__DIE__"}) =
885 if ($self->{'curcop'}) {
886 my $cop = $self->{'curcop'};
887 my($line, $file) = ($cop->line, $cop->file);
888 print STDERR "While deparsing $file near line $line,\n";
891 $self->{'curcv'} = main_cv;
892 $self->{'curcvlex'} = undef;
893 print $self->print_protos;
894 @{$self->{'subs_todo'}} =
895 sort {$a->[0] <=> $b->[0]} @{$self->{'subs_todo'}};
896 my $root = main_root;
897 local $B::overlay = {};
898 unless (null $root) {
899 $self->pad_subs($self->{'curcv'});
900 # Check for a stub-followed-by-ex-cop, resulting from a program
901 # consisting solely of sub declarations. For backward-compati-
902 # bility (and sane output) we don’t want to emit the stub.
906 # ex-nextstate (or ex-dbstate)
908 if ( $root->name eq 'leave'
909 and ($kid = $root->first)->name eq 'enter'
910 and !null($kid = $kid->sibling) and $kid->name eq 'stub'
911 and !null($kid = $kid->sibling) and $kid->name eq 'null'
912 and class($kid) eq 'COP' and null $kid->sibling )
916 $self->pessimise($root, main_start);
917 print $self->indent($self->deparse_root($root)), "\n";
921 while (scalar(@{$self->{'subs_todo'}})) {
922 push @text, $self->next_todo;
924 print $self->indent(join("", @text)), "\n" if @text;
926 # Print __DATA__ section, if necessary
928 my $laststash = defined $self->{'curcop'}
929 ? $self->{'curcop'}->stash->NAME : $self->{'curstash'};
930 if (defined *{$laststash."::DATA"}{IO}) {
931 print $self->keyword("package") . " $laststash;\n"
932 unless $laststash eq $self->{'curstash'};
933 print $self->keyword("__DATA__") . "\n";
934 print readline(*{$laststash."::DATA"});
942 croak "Usage: ->coderef2text(CODEREF)" unless UNIVERSAL::isa($sub, "CODE");
945 local $self->{in_coderef2text} = 1;
946 return $self->indent($self->deparse_sub(svref_2object($sub)));
949 my %strict_bits = do {
951 map +($_ => strict::bits($_)), qw/refs subs vars/
954 sub ambient_pragmas {
956 my ($arybase, $hint_bits, $warning_bits, $hinthash) = (0, 0);
962 if ($name eq 'strict') {
965 if ($val eq 'none') {
966 $hint_bits &= $strict_bits{$_} for qw/refs subs vars/;
972 @names = qw/refs subs vars/;
978 @names = split' ', $val;
980 $hint_bits |= $strict_bits{$_} for @names;
983 elsif ($name eq '$[') {
984 if (OPpCONST_ARYBASE) {
987 croak "\$[ can't be non-zero on this perl" unless $val == 0;
991 elsif ($name eq 'integer'
993 || $name eq 'utf8') {
996 $hint_bits |= ${$::{"${name}::"}{"hint_bits"}};
999 $hint_bits &= ~${$::{"${name}::"}{"hint_bits"}};
1003 elsif ($name eq 're') {
1005 if ($val eq 'none') {
1006 $hint_bits &= ~re::bits(qw/taint eval/);
1011 if ($val eq 'all') {
1012 @names = qw/taint eval/;
1018 @names = split' ',$val;
1020 $hint_bits |= re::bits(@names);
1023 elsif ($name eq 'warnings') {
1024 if ($val eq 'none') {
1025 $warning_bits = $warnings::NONE;
1034 @names = split/\s+/, $val;
1037 $warning_bits = $warnings::NONE if !defined ($warning_bits);
1038 $warning_bits |= warnings::bits(@names);
1041 elsif ($name eq 'warning_bits') {
1042 $warning_bits = $val;
1045 elsif ($name eq 'hint_bits') {
1049 elsif ($name eq '%^H') {
1054 croak "Unknown pragma type: $name";
1058 croak "The ambient_pragmas method expects an even number of args";
1061 $self->{'ambient_arybase'} = $arybase;
1062 $self->{'ambient_warnings'} = $warning_bits;
1063 $self->{'ambient_hints'} = $hint_bits;
1064 $self->{'ambient_hinthash'} = $hinthash;
1067 # This method is the inner loop, so try to keep it simple
1072 Carp::confess("Null op in deparse") if !defined($op)
1073 || class($op) eq "NULL";
1074 my $meth = "pp_" . $op->name;
1075 return $self->$meth($op, $cx);
1081 # \cK also swallows a preceding line break when followed by a
1083 $txt =~ s/\n\cK;//g;
1084 my @lines = split(/\n/, $txt);
1088 for $line (@lines) {
1089 my $cmd = substr($line, 0, 1);
1090 if ($cmd eq "\t" or $cmd eq "\b") {
1091 $level += ($cmd eq "\t" ? 1 : -1) * $self->{'indent_size'};
1092 if ($self->{'use_tabs'}) {
1093 $leader = "\t" x ($level / 8) . " " x ($level % 8);
1095 $leader = " " x $level;
1097 $line = substr($line, 1);
1099 if (index($line, "\f") > 0) {
1102 if (substr($line, 0, 1) eq "\f") {
1103 $line = substr($line, 1); # no indent
1105 $line = $leader . $line;
1107 $line =~ s/\cK;?//g;
1109 return join("\n", @lines);
1113 my ($self, $cv) = @_;
1114 my $padlist = $cv->PADLIST;
1115 my @names = $padlist->ARRAYelt(0)->ARRAY;
1116 my @values = $padlist->ARRAYelt(1)->ARRAY;
1119 for my $ix (0.. $#names) { for $_ ($names[$ix]) {
1120 next if class($_) eq "SPECIAL";
1122 if (defined $name && $name =~ /^&./) {
1123 my $low = $_->COP_SEQ_RANGE_LOW;
1124 my $flags = $_->FLAGS;
1125 my $outer = $flags & PADNAMEt_OUTER;
1126 if ($flags & SVpad_OUR) {
1127 push @todo, [$low, undef, 0, $_]
1128 # [seq, no cv, not format, padname]
1132 my $protocv = $flags & SVpad_STATE
1135 if (class ($protocv) ne 'CV') {
1139 while ($flags & PADNAMEt_OUTER && class ($protocv) ne 'CV')
1142 next PADENTRY if class($cv) eq 'SPECIAL'; # XXX freed?
1143 my $padlist = $cv->PADLIST;
1144 my $ix = $name->PARENT_PAD_INDEX;
1145 $name = $padlist->NAMES->ARRAYelt($ix);
1146 $flags = $name->FLAGS;
1147 $protocv = $flags & SVpad_STATE
1148 ? $padlist->ARRAYelt(1)->ARRAYelt($ix)
1152 my $defined_in_this_sub = ${$protocv->OUTSIDE} == $$cv || do {
1153 my $other = $protocv->PADLIST;
1154 $$other && $other->outid == $padlist->id;
1156 if ($flags & PADNAMEt_OUTER) {
1157 next unless $defined_in_this_sub;
1158 push @todo, [$protocv->OUTSIDE_SEQ, $protocv, 0, $_];
1161 my $outseq = $protocv->OUTSIDE_SEQ;
1162 if ($outseq <= $low) {
1163 # defined before its name is visible, so it’s gotta be
1164 # declared and defined at once: my sub foo { ... }
1165 push @todo, [$low, $protocv, 0, $_];
1168 # declared and defined separately: my sub f; sub f { ... }
1169 push @todo, [$low, undef, 0, $_];
1170 push @todo, [$outseq, $protocv, 0, $_]
1171 if $defined_in_this_sub;
1175 @{$self->{'subs_todo'}} =
1176 sort {$a->[0] <=> $b->[0]} @{$self->{'subs_todo'}}, @todo
1180 # deparse_argops(): deparse, if possible, a sequence of argcheck + argelem
1181 # ops into a subroutine signature. If successful, return the first op
1182 # following the signature ops plus the signature string; else return the
1185 # Normally a bunch of argelem ops will have been generated by the
1186 # signature parsing, but it's possible that ops have been added manually
1187 # or altered. In this case we "return ()" and fall back to general
1188 # deparsing of the individual sigelems as 'my $x = $_[N]' etc.
1190 # We're only called if the first two ops are nextstate and argcheck.
1192 sub deparse_argops {
1193 my ($self, $firstop, $cv) = @_;
1197 return if $o->label; #first nextstate;
1202 my ($params, $opt_params, $slurpy) = $o->aux_list($cv);
1203 my $mandatory = $params - $opt_params;
1204 my $seen_slurpy = 0;
1207 # keep looking for valid nextstate + argelem pairs
1213 last unless $o->name =~ /^(next|db)state$/;
1217 my $o2 = $o->sibling;
1220 if ($o2->name eq 'argelem') {
1221 my $ix = $o2->string($cv);
1222 while (++$last_ix < $ix) {
1223 push @sig, $last_ix < $mandatory ? '$' : '$=';
1225 my $var = $self->padname($o2->targ);
1226 if ($var =~ /^[@%]/) {
1227 return if $seen_slurpy;
1229 return if $ix != $params or !$slurpy
1230 or substr($var,0,1) ne $slurpy;
1233 return if $ix >= $params;
1235 if ($o2->flags & OPf_KIDS) {
1236 my $kid = $o2->first;
1237 return unless $$kid and $kid->name eq 'argdefelem';
1238 my $def = $self->deparse($kid->first, 7);
1239 $def = "($def)" if $kid->first->flags & OPf_PARENS;
1244 elsif ($o2->name eq 'null'
1245 and ($o2->flags & OPf_KIDS)
1246 and $o2->first->name eq 'argdefelem')
1248 # special case - a void context default expression: $ = expr
1250 my $defop = $o2->first;
1251 my $ix = $defop->targ;
1252 while (++$last_ix < $ix) {
1253 push @sig, $last_ix < $mandatory ? '$' : '$=';
1255 return if $last_ix >= $params
1256 or $last_ix < $mandatory;
1257 my $def = $self->deparse($defop->first, 7);
1258 $def = "($def)" if $defop->first->flags & OPf_PARENS;
1259 push @sig, '$ = ' . $def;
1268 while (++$last_ix < $params) {
1269 push @sig, $last_ix < $mandatory ? '$' : '$=';
1271 push @sig, $slurpy if $slurpy and !$seen_slurpy;
1273 return ($o, join(', ', @sig));
1276 # Deparse a sub. Returns everything except the 'sub foo',
1277 # e.g. ($$) : method { ...; }
1278 # or ($a, $b) : prototype($$) lvalue;
1284 my $protosig; # prototype or signature (what goes in the (....))
1286 Carp::confess("NULL in deparse_sub") if !defined($cv) || $cv->isa("B::NULL");
1287 Carp::confess("SPECIAL in deparse_sub") if $cv->isa("B::SPECIAL");
1288 local $self->{'curcop'} = $self->{'curcop'};
1290 my $has_sig = $self->{hinthash}{feature_signatures};
1291 if ($cv->FLAGS & SVf_POK) {
1292 my $proto = $cv->PV;
1294 push @attrs, "prototype($proto)";
1300 if ($cv->CvFLAGS & (CVf_METHOD|CVf_LOCKED|CVf_LVALUE|CVf_ANONCONST)) {
1301 push @attrs, "lvalue" if $cv->CvFLAGS & CVf_LVALUE;
1302 push @attrs, "method" if $cv->CvFLAGS & CVf_METHOD;
1303 push @attrs, "const" if $cv->CvFLAGS & CVf_ANONCONST;
1306 local($self->{'curcv'}) = $cv;
1307 local($self->{'curcvlex'});
1308 local(@$self{qw'curstash warnings hints hinthash'})
1309 = @$self{qw'curstash warnings hints hinthash'};
1311 my $root = $cv->ROOT;
1312 local $B::overlay = {};
1313 if (not null $root) {
1314 $self->pad_subs($cv);
1315 $self->pessimise($root, $cv->START);
1316 my $lineseq = $root->first;
1317 if ($lineseq->name eq "lineseq") {
1318 my $firstop = $lineseq->first;
1322 # try to deparse first few ops as a signature if possible
1324 and $firstop->name =~ /^(next|db)state$/
1325 and (($o2 = $firstop->sibling))
1328 if ($o2->name eq 'argcheck') {
1329 my ($nexto, $sig) = $self->deparse_argops($firstop, $cv);
1330 if (defined $nexto) {
1339 for (my $o = $firstop; $$o; $o=$o->sibling) {
1342 $body = $self->lineseq(undef, 0, @ops).";";
1343 if (!$has_sig and $ops[-1]->name =~ /^(next|db)state$/) {
1344 # this handles void context in
1345 # use feature signatures; sub ($=1) {}
1348 my $scope_en = $self->find_scope_en($lineseq);
1349 if (defined $scope_en) {
1350 my $subs = join"", $self->seq_subs($scope_en);
1351 $body .= ";\n$subs" if length($subs);
1355 $body = $self->deparse($root->first, 0);
1357 $body = "{\n\t$body\n\b}";
1360 my $sv = $cv->const_sv;
1362 # uh-oh. inlinable sub... format it differently
1363 $body = "{ " . $self->const($sv, 0) . " }\n";
1364 } else { # XSUB? (or just a declaration)
1368 $protosig = defined $protosig ? "($protosig) " : "";
1370 $attrs = ': ' . join('', map "$_ ", @attrs) if @attrs;
1371 return "$protosig$attrs$body\n";
1374 sub deparse_format {
1378 local($self->{'curcv'}) = $form;
1379 local($self->{'curcvlex'});
1380 local($self->{'in_format'}) = 1;
1381 local(@$self{qw'curstash warnings hints hinthash'})
1382 = @$self{qw'curstash warnings hints hinthash'};
1383 my $op = $form->ROOT;
1384 local $B::overlay = {};
1385 $self->pessimise($op, $form->START);
1387 return "\f." if $op->first->name eq 'stub'
1388 || $op->first->name eq 'nextstate';
1389 $op = $op->first->first; # skip leavewrite, lineseq
1390 while (not null $op) {
1391 $op = $op->sibling; # skip nextstate
1393 $kid = $op->first->sibling; # skip pushmark
1394 push @text, "\f".$self->const_sv($kid)->PV;
1395 $kid = $kid->sibling;
1396 for (; not null $kid; $kid = $kid->sibling) {
1397 push @exprs, $self->deparse($kid, -1);
1398 $exprs[-1] =~ s/;\z//;
1400 push @text, "\f".join(", ", @exprs)."\n" if @exprs;
1403 return join("", @text) . "\f.";
1408 return $op->name eq "leave" || $op->name eq "scope"
1409 || $op->name eq "lineseq"
1410 || ($op->name eq "null" && class($op) eq "UNOP"
1411 && (is_scope($op->first) || $op->first->name eq "enter"));
1415 my $name = $_[0]->name;
1416 return $name eq "nextstate" || $name eq "dbstate" || $name eq "setstate";
1419 sub is_miniwhile { # check for one-line loop ('foo() while $y--')
1421 return (!null($op) and null($op->sibling)
1422 and $op->name eq "null" and class($op) eq "UNOP"
1423 and (($op->first->name =~ /^(and|or)$/
1424 and $op->first->first->sibling->name eq "lineseq")
1425 or ($op->first->name eq "lineseq"
1426 and not null $op->first->first->sibling
1427 and $op->first->first->sibling->name eq "unstack")
1431 # Check if the op and its sibling are the initialization and the rest of a
1432 # for (..;..;..) { ... } loop
1435 # This OP might be almost anything, though it won't be a
1436 # nextstate. (It's the initialization, so in the canonical case it
1437 # will be an sassign.) The sibling is (old style) a lineseq whose
1438 # first child is a nextstate and whose second is a leaveloop, or
1439 # (new style) an unstack whose sibling is a leaveloop.
1440 my $lseq = $op->sibling;
1441 return 0 unless !is_state($op) and !null($lseq);
1442 if ($lseq->name eq "lineseq") {
1443 if ($lseq->first && !null($lseq->first) && is_state($lseq->first)
1444 && (my $sib = $lseq->first->sibling)) {
1445 return (!null($sib) && $sib->name eq "leaveloop");
1447 } elsif ($lseq->name eq "unstack" && ($lseq->flags & OPf_SPECIAL)) {
1448 my $sib = $lseq->sibling;
1449 return $sib && !null($sib) && $sib->name eq "leaveloop";
1456 return ($op->name eq "rv2sv" or
1457 $op->name eq "padsv" or
1458 $op->name eq "gv" or # only in array/hash constructs
1459 $op->flags & OPf_KIDS && !null($op->first)
1460 && $op->first->name eq "gvsv");
1465 my($text, $cx, $prec) = @_;
1466 if ($prec < $cx # unary ops nest just fine
1467 or $prec == $cx and $cx != 4 and $cx != 16 and $cx != 21
1468 or $self->{'parens'})
1471 # In a unop, let parent reuse our parens; see maybe_parens_unop
1472 $text = "\cS" . $text if $cx == 16;
1479 # same as above, but get around the 'if it looks like a function' rule
1480 sub maybe_parens_unop {
1482 my($name, $kid, $cx) = @_;
1483 if ($cx > 16 or $self->{'parens'}) {
1484 $kid = $self->deparse($kid, 1);
1485 if ($name eq "umask" && $kid =~ /^\d+$/) {
1486 $kid = sprintf("%#o", $kid);
1488 return $self->keyword($name) . "($kid)";
1490 $kid = $self->deparse($kid, 16);
1491 if ($name eq "umask" && $kid =~ /^\d+$/) {
1492 $kid = sprintf("%#o", $kid);
1494 $name = $self->keyword($name);
1495 if (substr($kid, 0, 1) eq "\cS") {
1497 return $name . substr($kid, 1);
1498 } elsif (substr($kid, 0, 1) eq "(") {
1499 # avoid looks-like-a-function trap with extra parens
1500 # ('+' can lead to ambiguities)
1501 return "$name(" . $kid . ")";
1503 return "$name $kid";
1508 sub maybe_parens_func {
1510 my($func, $text, $cx, $prec) = @_;
1511 if ($prec <= $cx or substr($text, 0, 1) eq "(" or $self->{'parens'}) {
1512 return "$func($text)";
1514 return "$func $text";
1519 my ($self, $name) = @_;
1520 $self->populate_curcvlex() if !defined $self->{'curcvlex'};
1521 my $seq = $self->{'curcop'} ? $self->{'curcop'}->cop_seq : 0;
1522 for my $a (@{$self->{'curcvlex'}{"o$name"}}) {
1523 my ($st, undef, $padname) = @$a;
1524 if ($st >= $seq && $padname->FLAGS & SVpad_TYPED) {
1525 return $padname->SvSTASH->NAME;
1533 my($op, $cx, $text) = @_;
1534 my $name = $op->name;
1535 my $our_intro = ($name =~ /^(?:(?:gv|rv2)[ash]v|split|refassign
1539 my $lval_intro = $name eq 'split' ? 0 : OPpLVAL_INTRO;
1540 # The @a in \(@a) isn't in ref context, but only when the
1542 my $need_parens = $self->{'in_refgen'} && $name =~ /[ah]v\z/
1543 && ($op->flags & (OPf_PARENS|OPf_REF)) == OPf_PARENS;
1544 if ((my $priv = $op->private) & ($lval_intro|$our_intro)) {
1546 push @our_local, "local" if $priv & $lval_intro;
1547 push @our_local, "our" if $priv & $our_intro;
1548 my $our_local = join " ", map $self->keyword($_), @our_local;
1549 if( $our_local[-1] eq 'our' ) {
1550 if ( $text !~ /^\W(\w+::)*\w+\z/
1551 and !utf8::decode($text) || $text !~ /^\W(\w+::)*\w+\z/
1553 die "Unexpected our($text)\n";
1555 $text =~ s/(\w+::)+//;
1557 if (my $type = $self->find_our_type($text)) {
1558 $our_local .= ' ' . $type;
1561 return $need_parens ? "($text)" : $text
1562 if $self->{'avoid_local'}{$$op};
1564 return "$our_local($text)";
1565 } elsif (want_scalar($op)) {
1566 return "$our_local $text";
1568 return $self->maybe_parens_func("$our_local", $text, $cx, 16);
1571 return $need_parens ? "($text)" : $text;
1577 my($op, $cx, $func, @args) = @_;
1578 if ($op->private & OPpTARGET_MY) {
1579 my $var = $self->padname($op->targ);
1580 my $val = $func->($self, $op, 7, @args);
1581 return $self->maybe_parens("$var = $val", $cx, 7);
1583 return $func->($self, $op, $cx, @args);
1590 return $self->{'curcv'}->PADLIST->ARRAYelt(0)->ARRAYelt($targ);
1595 my($op, $cx, $text, $padname, $forbid_parens) = @_;
1596 # The @a in \(@a) isn't in ref context, but only when the
1598 my $need_parens = !$forbid_parens && $self->{'in_refgen'}
1599 && $op->name =~ /[ah]v\z/
1600 && ($op->flags & (OPf_PARENS|OPf_REF)) == OPf_PARENS;
1601 # The @a in \my @a must not have parens.
1602 if (!$need_parens && $self->{'in_refgen'}) {
1605 if ($op->private & OPpLVAL_INTRO and not $self->{'avoid_local'}{$$op}) {
1606 # Check $padname->FLAGS for statehood, rather than $op->private,
1607 # because enteriter ops do not carry the flag.
1609 $self->keyword($padname->FLAGS & SVpad_STATE ? "state" : "my");
1610 if ($padname->FLAGS & SVpad_TYPED) {
1611 $my .= ' ' . $padname->SvSTASH->NAME;
1614 return "$my($text)";
1615 } elsif ($forbid_parens || want_scalar($op)) {
1618 return $self->maybe_parens_func($my, $text, $cx, 16);
1621 return $need_parens ? "($text)" : $text;
1625 # The following OPs don't have functions:
1627 # pp_padany -- does not exist after parsing
1630 if ($AUTOLOAD =~ s/^.*::pp_//) {
1631 warn "unexpected OP_".
1632 ($_[1]->type == OP_CUSTOM ? "CUSTOM ($AUTOLOAD)" : uc $AUTOLOAD);
1635 die "Undefined subroutine $AUTOLOAD called";
1639 sub DESTROY {} # Do not AUTOLOAD
1641 # $root should be the op which represents the root of whatever
1642 # we're sequencing here. If it's undefined, then we don't append
1643 # any subroutine declarations to the deparsed ops, otherwise we
1644 # append appropriate declarations.
1646 my($self, $root, $cx, @ops) = @_;
1649 my $out_cop = $self->{'curcop'};
1650 my $out_seq = defined($out_cop) ? $out_cop->cop_seq : undef;
1652 if (defined $root) {
1653 $limit_seq = $out_seq;
1655 $nseq = $self->find_scope_st($root->sibling) if ${$root->sibling};
1656 $limit_seq = $nseq if !defined($limit_seq)
1657 or defined($nseq) && $nseq < $limit_seq;
1659 $limit_seq = $self->{'limit_seq'}
1660 if defined($self->{'limit_seq'})
1661 && (!defined($limit_seq) || $self->{'limit_seq'} < $limit_seq);
1662 local $self->{'limit_seq'} = $limit_seq;
1664 $self->walk_lineseq($root, \@ops,
1665 sub { push @exprs, $_[0]} );
1667 my $sep = $cx ? '; ' : ";\n";
1668 my $body = join($sep, grep {length} @exprs);
1670 if (defined $root && defined $limit_seq && !$self->{'in_format'}) {
1671 $subs = join "\n", $self->seq_subs($limit_seq);
1673 return join($sep, grep {length} $body, $subs);
1677 my($real_block, $self, $op, $cx) = @_;
1681 local(@$self{qw'curstash warnings hints hinthash'})
1682 = @$self{qw'curstash warnings hints hinthash'} if $real_block;
1684 $kid = $op->first->sibling; # skip enter
1685 if (is_miniwhile($kid)) {
1686 my $top = $kid->first;
1687 my $name = $top->name;
1688 if ($name eq "and") {
1689 $name = $self->keyword("while");
1690 } elsif ($name eq "or") {
1691 $name = $self->keyword("until");
1692 } else { # no conditional -> while 1 or until 0
1693 return $self->deparse($top->first, 1) . " "
1694 . $self->keyword("while") . " 1";
1696 my $cond = $top->first;
1697 my $body = $cond->sibling->first; # skip lineseq
1698 $cond = $self->deparse($cond, 1);
1699 $body = $self->deparse($body, 1);
1700 return "$body $name $cond";
1705 for (; !null($kid); $kid = $kid->sibling) {
1708 if ($cx > 0) { # inside an expression, (a do {} while for lineseq)
1709 my $body = $self->lineseq($op, 0, @kids);
1710 return is_lexical_subs(@kids)
1712 : ($self->lex_in_scope("&do") ? "CORE::do" : "do")
1713 . " {\n\t$body\n\b}";
1715 my $lineseq = $self->lineseq($op, $cx, @kids);
1716 return (length ($lineseq) ? "$lineseq;" : "");
1720 sub pp_scope { scopeop(0, @_); }
1721 sub pp_lineseq { scopeop(0, @_); }
1722 sub pp_leave { scopeop(1, @_); }
1724 # This is a special case of scopeop and lineseq, for the case of the
1725 # main_root. The difference is that we print the output statements as
1726 # soon as we get them, for the sake of impatient users.
1730 local(@$self{qw'curstash warnings hints hinthash'})
1731 = @$self{qw'curstash warnings hints hinthash'};
1733 return if null $op->first; # Can happen, e.g., for Bytecode without -k
1734 for (my $kid = $op->first->sibling; !null($kid); $kid = $kid->sibling) {
1737 $self->walk_lineseq($op, \@kids,
1738 sub { return unless length $_[0];
1739 print $self->indent($_[0].';');
1741 unless $_[1] == $#kids;
1746 my ($self, $op, $kids, $callback) = @_;
1748 for (my $i = 0; $i < @kids; $i++) {
1750 if (is_state $kids[$i]) {
1751 $expr = $self->deparse($kids[$i++], 0);
1753 $callback->($expr, $i);
1757 if (is_for_loop($kids[$i])) {
1758 $callback->($expr . $self->for_loop($kids[$i], 0),
1759 $i += $kids[$i]->sibling->name eq "unstack" ? 2 : 1);
1762 my $expr2 = $self->deparse($kids[$i], (@kids != 1)/2);
1763 $expr2 =~ s/^sub :(?!:)/+sub :/; # statement label otherwise
1765 $callback->($expr, $i);
1769 # The BEGIN {} is used here because otherwise this code isn't executed
1770 # when you run B::Deparse on itself.
1772 BEGIN { map($globalnames{$_}++, "SIG", "STDIN", "STDOUT", "STDERR", "INC",
1773 "ENV", "ARGV", "ARGVOUT", "_"); }
1779 #Carp::confess() unless ref($gv) eq "B::GV";
1780 my $cv = $gv->FLAGS & SVf_ROK ? $gv->RV : 0;
1781 my $stash = ($cv || $gv)->STASH->NAME;
1783 ? $cv ? $cv->NAME_HEK || $cv->GV->NAME : $gv->NAME
1785 ? B::safename($cv->NAME_HEK || $cv->GV->NAME)
1787 if ($stash eq 'main' && $name =~ /^::/) {
1790 elsif (($stash eq 'main'
1791 && ($globalnames{$name} || $name =~ /^[^A-Za-z_:]/))
1792 or ($stash eq $self->{'curstash'} && !$globalnames{$name}
1793 && ($stash eq 'main' || $name !~ /::/))
1798 $stash = $stash . "::";
1800 if (!$raw and $name =~ /^(\^..|{)/) {
1801 $name = "{$name}"; # ${^WARNING_BITS}, etc and ${
1803 return $stash . $name;
1806 # Return the name to use for a stash variable.
1807 # If a lexical with the same name is in scope, or
1808 # if strictures are enabled, it may need to be
1810 sub stash_variable {
1811 my ($self, $prefix, $name, $cx) = @_;
1813 return $prefix.$self->maybe_qualify($prefix, $name) if $name =~ /::/;
1815 unless ($prefix eq '$' || $prefix eq '@' || $prefix eq '&' || #'
1816 $prefix eq '%' || $prefix eq '$#') {
1817 return "$prefix$name";
1820 if ($name =~ /^[^[:alpha:]_+-]$/) {
1821 if (defined $cx && $cx == 26) {
1822 if ($prefix eq '@') {
1823 return "$prefix\{$name}";
1825 elsif ($name eq '#') { return '${#}' } # "${#}a" vs "$#a"
1827 if ($prefix eq '$#') {
1828 return "\$#{$name}";
1832 return $prefix . $self->maybe_qualify($prefix, $name);
1835 my %unctrl = # portable to EBCDIC
1837 "\c@" => '@', # unused
1864 "\c[" => '[', # unused
1865 "\c\\" => '\\', # unused
1866 "\c]" => ']', # unused
1867 "\c_" => '_', # unused
1870 # Return just the name, without the prefix. It may be returned as a quoted
1871 # string. The second return value is a boolean indicating that.
1872 sub stash_variable_name {
1873 my($self, $prefix, $gv) = @_;
1874 my $name = $self->gv_name($gv, 1);
1875 $name = $self->maybe_qualify($prefix,$name);
1876 if ($name =~ /^(?:\S|(?!\d)[\ca-\cz]?(?:\w|::)*|\d+)\z/) {
1877 $name =~ s/^([\ca-\cz])/'^' . $unctrl{$1}/e;
1878 $name =~ /^(\^..|{)/ and $name = "{$name}";
1879 return $name, 0; # not quoted
1882 single_delim("q", "'", $name, $self), 1;
1887 my ($self,$prefix,$name) = @_;
1888 my $v = ($prefix eq '$#' ? '@' : $prefix) . $name;
1889 if ($prefix eq "") {
1890 $name .= "::" if $name =~ /(?:\ACORE::[^:]*|::)\z/;
1893 return $name if $name =~ /::/;
1894 return $self->{'curstash'}.'::'. $name
1896 $name =~ /^(?!\d)\w/ # alphabetic
1897 && $v !~ /^\$[ab]\z/ # not $a or $b
1898 && $v =~ /\A[\$\@\%\&]/ # scalar, array, hash, or sub
1899 && !$globalnames{$name} # not a global name
1900 && $self->{hints} & $strict_bits{vars} # strict vars
1901 && !$self->lex_in_scope($v,1) # no "our"
1902 or $self->lex_in_scope($v); # conflicts with "my" variable
1907 my ($self, $name, $our) = @_;
1908 substr $name, 0, 0, = $our ? 'o' : 'm'; # our/my
1909 $self->populate_curcvlex() if !defined $self->{'curcvlex'};
1911 return 0 if !defined($self->{'curcop'});
1912 my $seq = $self->{'curcop'}->cop_seq;
1913 return 0 if !exists $self->{'curcvlex'}{$name};
1914 for my $a (@{$self->{'curcvlex'}{$name}}) {
1915 my ($st, $en) = @$a;
1916 return 1 if $seq > $st && $seq <= $en;
1921 sub populate_curcvlex {
1923 for (my $cv = $self->{'curcv'}; class($cv) eq "CV"; $cv = $cv->OUTSIDE) {
1924 my $padlist = $cv->PADLIST;
1925 # an undef CV still in lexical chain
1926 next if class($padlist) eq "SPECIAL";
1927 my @padlist = $padlist->ARRAY;
1928 my @ns = $padlist[0]->ARRAY;
1930 for (my $i=0; $i<@ns; ++$i) {
1931 next if class($ns[$i]) eq "SPECIAL";
1932 if (class($ns[$i]) eq "PV") {
1933 # Probably that pesky lexical @_
1936 my $name = $ns[$i]->PVX;
1937 next unless defined $name;
1938 my ($seq_st, $seq_en) =
1939 ($ns[$i]->FLAGS & SVf_FAKE)
1941 : ($ns[$i]->COP_SEQ_RANGE_LOW, $ns[$i]->COP_SEQ_RANGE_HIGH);
1943 push @{$self->{'curcvlex'}{
1944 ($ns[$i]->FLAGS & SVpad_OUR ? 'o' : 'm') . $name
1945 }}, [$seq_st, $seq_en, $ns[$i]];
1950 sub find_scope_st { ((find_scope(@_))[0]); }
1951 sub find_scope_en { ((find_scope(@_))[1]); }
1953 # Recurses down the tree, looking for pad variable introductions and COPs
1955 my ($self, $op, $scope_st, $scope_en) = @_;
1956 carp("Undefined op in find_scope") if !defined $op;
1957 return ($scope_st, $scope_en) unless $op->flags & OPf_KIDS;
1960 while(my $op = shift @queue ) {
1961 for (my $o=$op->first; $$o; $o=$o->sibling) {
1962 if ($o->name =~ /^pad.v$/ && $o->private & OPpLVAL_INTRO) {
1963 my $s = int($self->padname_sv($o->targ)->COP_SEQ_RANGE_LOW);
1964 my $e = $self->padname_sv($o->targ)->COP_SEQ_RANGE_HIGH;
1965 $scope_st = $s if !defined($scope_st) || $s < $scope_st;
1966 $scope_en = $e if !defined($scope_en) || $e > $scope_en;
1967 return ($scope_st, $scope_en);
1969 elsif (is_state($o)) {
1970 my $c = $o->cop_seq;
1971 $scope_st = $c if !defined($scope_st) || $c < $scope_st;
1972 $scope_en = $c if !defined($scope_en) || $c > $scope_en;
1973 return ($scope_st, $scope_en);
1975 elsif ($o->flags & OPf_KIDS) {
1976 unshift (@queue, $o);
1981 return ($scope_st, $scope_en);
1984 # Returns a list of subs which should be inserted before the COP
1986 my ($self, $op, $out_seq) = @_;
1987 my $seq = $op->cop_seq;
1988 $seq = $out_seq if defined($out_seq) && $out_seq < $seq;
1989 return $self->seq_subs($seq);
1993 my ($self, $seq) = @_;
1995 #push @text, "# ($seq)\n";
1997 return "" if !defined $seq;
1999 while (scalar(@{$self->{'subs_todo'}})
2000 and $seq > $self->{'subs_todo'}[0][0]) {
2001 my $cv = $self->{'subs_todo'}[0][1];
2002 # Skip the OUTSIDE check for lexical subs. We may be deparsing a
2003 # cloned anon sub with lexical subs declared in it, in which case
2004 # the OUTSIDE pointer points to the anon protosub.
2005 my $lexical = ref $self->{'subs_todo'}[0][3];
2006 my $outside = !$lexical && $cv && $cv->OUTSIDE;
2007 if (!$lexical and $cv
2008 and ${$cv->OUTSIDE || \0} != ${$self->{'curcv'}})
2010 push @pending, shift @{$self->{'subs_todo'}};
2013 push @text, $self->next_todo;
2015 unshift @{$self->{'subs_todo'}}, @pending;
2019 sub _features_from_bundle {
2020 my ($hints, $hh) = @_;
2021 foreach (@{$feature::feature_bundle{@feature::hint_bundles[$hints >> $feature::hint_shift]}}) {
2022 $hh->{$feature::feature{$_}} = 1;
2027 # generate any pragmas, 'package foo' etc needed to synchronise
2028 # with the given cop
2036 my $stash = $op->stashpv;
2037 if ($stash ne $self->{'curstash'}) {
2038 push @text, $self->keyword("package") . " $stash;\n";
2039 $self->{'curstash'} = $stash;
2042 if (OPpCONST_ARYBASE && $self->{'arybase'} != $op->arybase) {
2043 push @text, '$[ = '. $op->arybase .";\n";
2044 $self->{'arybase'} = $op->arybase;
2047 my $warnings = $op->warnings;
2049 if ($warnings->isa("B::SPECIAL") && $$warnings == 4) {
2050 $warning_bits = $warnings::Bits{"all"} & WARN_MASK;
2052 elsif ($warnings->isa("B::SPECIAL") && $$warnings == 5) {
2053 $warning_bits = $warnings::NONE;
2055 elsif ($warnings->isa("B::SPECIAL")) {
2056 $warning_bits = undef;
2059 $warning_bits = $warnings->PV & WARN_MASK;
2062 if (defined ($warning_bits) and
2063 !defined($self->{warnings}) || $self->{'warnings'} ne $warning_bits) {
2065 $self->declare_warnings($self->{'warnings'}, $warning_bits);
2066 $self->{'warnings'} = $warning_bits;
2069 my $hints = $op->hints;
2070 my $old_hints = $self->{'hints'};
2071 if ($self->{'hints'} != $hints) {
2072 push @text, $self->declare_hints($self->{'hints'}, $hints);
2073 $self->{'hints'} = $hints;
2077 $newhh = $op->hints_hash->HASH;
2080 # feature bundle hints
2081 my $from = $old_hints & $feature::hint_mask;
2082 my $to = $ hints & $feature::hint_mask;
2084 if ($to == $feature::hint_mask) {
2085 if ($self->{'hinthash'}) {
2086 delete $self->{'hinthash'}{$_}
2087 for grep /^feature_/, keys %{$self->{'hinthash'}};
2089 else { $self->{'hinthash'} = {} }
2091 = _features_from_bundle($from, $self->{'hinthash'});
2095 $feature::hint_bundles[$to >> $feature::hint_shift];
2096 $bundle =~ s/(\d[13579])\z/$1+1/e; # 5.11 => 5.12
2098 $self->keyword("no") . " feature ':all';\n",
2099 $self->keyword("use") . " feature ':$bundle';\n";
2105 push @text, $self->declare_hinthash(
2106 $self->{'hinthash'}, $newhh,
2107 $self->{indent_size}, $self->{hints},
2109 $self->{'hinthash'} = $newhh;
2112 return join("", @text);
2116 # Notice how subs and formats are inserted between statements here;
2117 # also $[ assignments and pragmas.
2121 $self->{'curcop'} = $op;
2125 my @subs = $self->cop_subs($op);
2127 # Special marker to swallow up the semicolon
2132 push @text, $self->pragmata($op);
2135 # This should go after of any branches that add statements, to
2136 # increase the chances that it refers to the same line it did in
2137 # the original program.
2138 if ($self->{'linenums'} && $cx != .5) { # $cx == .5 means in a format
2139 push @text, "\f#line " . $op->line .
2140 ' "' . $op->file, qq'"\n';
2143 push @text, $op->label . ": " if $op->label;
2145 return join("", @text);
2148 sub declare_warnings {
2149 my ($self, $from, $to) = @_;
2151 my $all = (warnings::bits("all") & WARN_MASK);
2152 unless ((($from & WARN_MASK) & ~$all) =~ /[^\0]/) {
2153 # no FATAL bits need turning off
2154 if ( ($to & WARN_MASK) eq $all) {
2155 return $self->keyword("use") . " warnings;\n";
2157 elsif (($to & WARN_MASK) eq ("\0"x length($to) & WARN_MASK)) {
2158 return $self->keyword("no") . " warnings;\n";
2162 return "BEGIN {\${^WARNING_BITS} = \""
2163 . join("", map { sprintf("\\x%02x", ord $_) } split "", $to)
2168 my ($self, $from, $to) = @_;
2169 my $use = $to & ~$from;
2170 my $no = $from & ~$to;
2172 for my $pragma (hint_pragmas($use)) {
2173 $decls .= $self->keyword("use") . " $pragma;\n";
2175 for my $pragma (hint_pragmas($no)) {
2176 $decls .= $self->keyword("no") . " $pragma;\n";
2181 # Internal implementation hints that the core sets automatically, so don't need
2182 # (or want) to be passed back to the user
2183 my %ignored_hints = (
2194 sub declare_hinthash {
2195 my ($self, $from, $to, $indent, $hints) = @_;
2196 my $doing_features =
2197 ($hints & $feature::hint_mask) == $feature::hint_mask;
2200 my @unfeatures; # bugs?
2201 for my $key (sort keys %$to) {
2202 next if $ignored_hints{$key};
2203 my $is_feature = $key =~ /^feature_/;
2204 next if $is_feature and not $doing_features;
2205 if (!exists $from->{$key} or $from->{$key} ne $to->{$key}) {
2206 push(@features, $key), next if $is_feature;
2208 qq(\$^H{) . single_delim("q", "'", $key, $self) . qq(} = )
2211 ? single_delim("q", "'", $to->{$key}, $self)
2217 for my $key (sort keys %$from) {
2218 next if $ignored_hints{$key};
2219 my $is_feature = $key =~ /^feature_/;
2220 next if $is_feature and not $doing_features;
2221 if (!exists $to->{$key}) {
2222 push(@unfeatures, $key), next if $is_feature;
2223 push @decls, qq(delete \$^H{'$key'};);
2227 if (@features || @unfeatures) {
2228 if (!%rev_feature) { %rev_feature = reverse %feature::feature }
2231 push @ret, $self->keyword("use") . " feature "
2232 . join(", ", map "'$rev_feature{$_}'", @features) . ";\n";
2235 push @ret, $self->keyword("no") . " feature "
2236 . join(", ", map "'$rev_feature{$_}'", @unfeatures)
2241 join("\n" . (" " x $indent), "BEGIN {", @decls) . "\n}\n\cK";
2247 my (@pragmas, @strict);
2248 push @pragmas, "integer" if $bits & 0x1;
2249 for (sort keys %strict_bits) {
2250 push @strict, "'$_'" if $bits & $strict_bits{$_};
2252 if (@strict == keys %strict_bits) {
2253 push @pragmas, "strict";
2256 push @pragmas, "strict " . join ', ', @strict;
2258 push @pragmas, "bytes" if $bits & 0x8;
2262 sub pp_dbstate { pp_nextstate(@_) }
2263 sub pp_setstate { pp_nextstate(@_) }
2265 sub pp_unstack { return "" } # see also leaveloop
2267 my %feature_keywords = (
2268 # keyword => 'feature',
2273 default => 'switch',
2275 evalbytes=>'evalbytes',
2276 __SUB__ => '__SUB__',
2280 # keywords that are strong and also have a prototype
2282 my %strong_proto_keywords = map { $_ => 1 } qw(
2290 sub feature_enabled {
2291 my($self,$name) = @_;
2293 my $hints = $self->{hints} & $feature::hint_mask;
2294 if ($hints && $hints != $feature::hint_mask) {
2295 $hh = _features_from_bundle($hints);
2297 elsif ($hints) { $hh = $self->{'hinthash'} }
2298 return $hh && $hh->{"feature_$feature_keywords{$name}"}
2304 return $name if $name =~ /^CORE::/; # just in case
2305 if (exists $feature_keywords{$name}) {
2306 return "CORE::$name" if not $self->feature_enabled($name);
2308 # This sub may be called for a program that has no nextstate ops. In
2309 # that case we may have a lexical sub named no/use/sub in scope but
2310 # but $self->lex_in_scope will return false because it depends on the
2311 # current nextstate op. So we need this alternate method if there is
2313 if (!$self->{'curcop'}) {
2314 $self->populate_curcvlex() if !defined $self->{'curcvlex'};
2315 return "CORE::$name" if exists $self->{'curcvlex'}{"m&$name"}
2316 || exists $self->{'curcvlex'}{"o&$name"};
2317 } elsif ($self->lex_in_scope("&$name")
2318 || $self->lex_in_scope("&$name", 1)) {
2319 return "CORE::$name";
2321 if ($strong_proto_keywords{$name}
2322 || ($name !~ /^(?:chom?p|do|exec|glob|s(?:elect|ystem))\z/
2323 && !defined eval{prototype "CORE::$name"})
2326 exists $self->{subs_declared}{$name}
2328 exists &{"$self->{curstash}::$name"}
2330 return "CORE::$name"
2337 my($op, $cx, $name) = @_;
2338 return $self->keyword($name);
2341 sub pp_stub { "()" }
2342 sub pp_wantarray { baseop(@_, "wantarray") }
2343 sub pp_fork { baseop(@_, "fork") }
2344 sub pp_wait { maybe_targmy(@_, \&baseop, "wait") }
2345 sub pp_getppid { maybe_targmy(@_, \&baseop, "getppid") }
2346 sub pp_time { maybe_targmy(@_, \&baseop, "time") }
2347 sub pp_tms { baseop(@_, "times") }
2348 sub pp_ghostent { baseop(@_, "gethostent") }
2349 sub pp_gnetent { baseop(@_, "getnetent") }
2350 sub pp_gprotoent { baseop(@_, "getprotoent") }
2351 sub pp_gservent { baseop(@_, "getservent") }
2352 sub pp_ehostent { baseop(@_, "endhostent") }
2353 sub pp_enetent { baseop(@_, "endnetent") }
2354 sub pp_eprotoent { baseop(@_, "endprotoent") }
2355 sub pp_eservent { baseop(@_, "endservent") }
2356 sub pp_gpwent { baseop(@_, "getpwent") }
2357 sub pp_spwent { baseop(@_, "setpwent") }
2358 sub pp_epwent { baseop(@_, "endpwent") }
2359 sub pp_ggrent { baseop(@_, "getgrent") }
2360 sub pp_sgrent { baseop(@_, "setgrent") }
2361 sub pp_egrent { baseop(@_, "endgrent") }
2362 sub pp_getlogin { baseop(@_, "getlogin") }
2364 sub POSTFIX () { 1 }
2366 # I couldn't think of a good short name, but this is the category of
2367 # symbolic unary operators with interesting precedence
2371 my($op, $cx, $name, $prec, $flags) = (@_, 0);
2372 my $kid = $op->first;
2373 $kid = $self->deparse($kid, $prec);
2374 return $self->maybe_parens(($flags & POSTFIX)
2376 # avoid confusion with filetests
2378 && $kid =~ /^[a-zA-Z](?!\w)/
2384 sub pp_preinc { pfixop(@_, "++", 23) }
2385 sub pp_predec { pfixop(@_, "--", 23) }
2386 sub pp_postinc { maybe_targmy(@_, \&pfixop, "++", 23, POSTFIX) }
2387 sub pp_postdec { maybe_targmy(@_, \&pfixop, "--", 23, POSTFIX) }
2388 sub pp_i_preinc { pfixop(@_, "++", 23) }
2389 sub pp_i_predec { pfixop(@_, "--", 23) }
2390 sub pp_i_postinc { maybe_targmy(@_, \&pfixop, "++", 23, POSTFIX) }
2391 sub pp_i_postdec { maybe_targmy(@_, \&pfixop, "--", 23, POSTFIX) }
2392 sub pp_complement { maybe_targmy(@_, \&pfixop, "~", 21) }
2393 *pp_ncomplement = *pp_complement;
2394 sub pp_scomplement { maybe_targmy(@_, \&pfixop, "~.", 21) }
2396 sub pp_negate { maybe_targmy(@_, \&real_negate) }
2400 if ($op->first->name =~ /^(i_)?negate$/) {
2402 $self->pfixop($op, $cx, "-", 21.5);
2404 $self->pfixop($op, $cx, "-", 21);
2407 sub pp_i_negate { pp_negate(@_) }
2413 $self->listop($op, $cx, "not", $op->first);
2415 $self->pfixop($op, $cx, "!", 21);
2421 my($op, $cx, $name, $nollafr) = @_;
2423 if ($op->flags & OPf_KIDS) {
2426 # this deals with 'boolkeys' right now
2427 return $self->deparse($kid,$cx);
2429 my $builtinname = $name;
2430 $builtinname =~ /^CORE::/ or $builtinname = "CORE::$name";
2431 if (defined prototype($builtinname)
2432 && $builtinname ne 'CORE::readline'
2433 && prototype($builtinname) =~ /^;?\*/
2434 && $kid->name eq "rv2gv") {
2439 if (($kid = $self->deparse($kid, 16)) !~ s/^\cS//) {
2440 # require foo() is a syntax error.
2441 $kid =~ /^(?!\d)\w/ and $kid = "($kid)";
2443 return $self->maybe_parens(
2444 $self->keyword($name) . " $kid", $cx, 16
2447 return $self->maybe_parens_unop($name, $kid, $cx);
2449 return $self->maybe_parens(
2450 $self->keyword($name) . ($op->flags & OPf_SPECIAL ? "()" : ""),
2456 sub pp_chop { maybe_targmy(@_, \&unop, "chop") }
2457 sub pp_chomp { maybe_targmy(@_, \&unop, "chomp") }
2458 sub pp_schop { maybe_targmy(@_, \&unop, "chop") }
2459 sub pp_schomp { maybe_targmy(@_, \&unop, "chomp") }
2460 sub pp_defined { unop(@_, "defined") }
2461 sub pp_undef { unop(@_, "undef") }
2462 sub pp_study { unop(@_, "study") }
2463 sub pp_ref { unop(@_, "ref") }
2464 sub pp_pos { maybe_local(@_, unop(@_, "pos")) }
2466 sub pp_sin { maybe_targmy(@_, \&unop, "sin") }
2467 sub pp_cos { maybe_targmy(@_, \&unop, "cos") }
2468 sub pp_rand { maybe_targmy(@_, \&unop, "rand") }
2469 sub pp_srand { unop(@_, "srand") }
2470 sub pp_exp { maybe_targmy(@_, \&unop, "exp") }
2471 sub pp_log { maybe_targmy(@_, \&unop, "log") }
2472 sub pp_sqrt { maybe_targmy(@_, \&unop, "sqrt") }
2473 sub pp_int { maybe_targmy(@_, \&unop, "int") }
2474 sub pp_hex { maybe_targmy(@_, \&unop, "hex") }
2475 sub pp_oct { maybe_targmy(@_, \&unop, "oct") }
2476 sub pp_abs { maybe_targmy(@_, \&unop, "abs") }
2478 sub pp_length { maybe_targmy(@_, \&unop, "length") }
2479 sub pp_ord { maybe_targmy(@_, \&unop, "ord") }
2480 sub pp_chr { maybe_targmy(@_, \&unop, "chr") }
2482 sub pp_each { unop(@_, "each") }
2483 sub pp_values { unop(@_, "values") }
2484 sub pp_keys { unop(@_, "keys") }
2485 { no strict 'refs'; *{"pp_r$_"} = *{"pp_$_"} for qw< keys each values >; }
2487 # no name because its an optimisation op that has no keyword
2490 sub pp_aeach { unop(@_, "each") }
2491 sub pp_avalues { unop(@_, "values") }
2492 sub pp_akeys { unop(@_, "keys") }
2493 sub pp_pop { unop(@_, "pop") }
2494 sub pp_shift { unop(@_, "shift") }
2496 sub pp_caller { unop(@_, "caller") }
2497 sub pp_reset { unop(@_, "reset") }
2498 sub pp_exit { unop(@_, "exit") }
2499 sub pp_prototype { unop(@_, "prototype") }
2501 sub pp_close { unop(@_, "close") }
2502 sub pp_fileno { unop(@_, "fileno") }
2503 sub pp_umask { unop(@_, "umask") }
2504 sub pp_untie { unop(@_, "untie") }
2505 sub pp_tied { unop(@_, "tied") }
2506 sub pp_dbmclose { unop(@_, "dbmclose") }
2507 sub pp_getc { unop(@_, "getc") }
2508 sub pp_eof { unop(@_, "eof") }
2509 sub pp_tell { unop(@_, "tell") }
2510 sub pp_getsockname { unop(@_, "getsockname") }
2511 sub pp_getpeername { unop(@_, "getpeername") }
2514 my ($self, $op, $cx) = @_;
2515 if (($op->flags & (OPf_SPECIAL|OPf_KIDS)) == (OPf_SPECIAL|OPf_KIDS)) {
2516 my $kw = $self->keyword("chdir");
2517 my $kid = $self->const_sv($op->first)->PV;
2519 . ($cx >= 16 || $self->{'parens'} ? "($kid)" : " $kid");
2520 maybe_targmy(@_, sub { $_[3] }, $code);
2522 maybe_targmy(@_, \&unop, "chdir")
2526 sub pp_chroot { maybe_targmy(@_, \&unop, "chroot") }
2527 sub pp_readlink { unop(@_, "readlink") }
2528 sub pp_rmdir { maybe_targmy(@_, \&unop, "rmdir") }
2529 sub pp_readdir { unop(@_, "readdir") }
2530 sub pp_telldir { unop(@_, "telldir") }
2531 sub pp_rewinddir { unop(@_, "rewinddir") }
2532 sub pp_closedir { unop(@_, "closedir") }
2533 sub pp_getpgrp { maybe_targmy(@_, \&unop, "getpgrp") }
2534 sub pp_localtime { unop(@_, "localtime") }
2535 sub pp_gmtime { unop(@_, "gmtime") }
2536 sub pp_alarm { unop(@_, "alarm") }
2537 sub pp_sleep { maybe_targmy(@_, \&unop, "sleep") }
2540 my $code = unop(@_, "do", 1); # llafr does not apply
2541 if ($code =~ s/^((?:CORE::)?do) \{/$1({/) { $code .= ')' }
2547 $_[1]->private & OPpEVAL_BYTES ? 'evalbytes' : "eval"
2551 sub pp_ghbyname { unop(@_, "gethostbyname") }
2552 sub pp_gnbyname { unop(@_, "getnetbyname") }
2553 sub pp_gpbyname { unop(@_, "getprotobyname") }
2554 sub pp_shostent { unop(@_, "sethostent") }
2555 sub pp_snetent { unop(@_, "setnetent") }
2556 sub pp_sprotoent { unop(@_, "setprotoent") }
2557 sub pp_sservent { unop(@_, "setservent") }
2558 sub pp_gpwnam { unop(@_, "getpwnam") }
2559 sub pp_gpwuid { unop(@_, "getpwuid") }
2560 sub pp_ggrnam { unop(@_, "getgrnam") }
2561 sub pp_ggrgid { unop(@_, "getgrgid") }
2563 sub pp_lock { unop(@_, "lock") }
2565 sub pp_continue { unop(@_, "continue"); }
2566 sub pp_break { unop(@_, "break"); }
2570 my($op, $cx, $givwhen) = @_;
2572 my $enterop = $op->first;
2574 if ($enterop->flags & OPf_SPECIAL) {
2575 $head = $self->keyword("default");
2576 $block = $self->deparse($enterop->first, 0);
2579 my $cond = $enterop->first;
2580 my $cond_str = $self->deparse($cond, 1);
2581 $head = "$givwhen ($cond_str)";
2582 $block = $self->deparse($cond->sibling, 0);
2590 sub pp_leavegiven { givwhen(@_, $_[0]->keyword("given")); }
2591 sub pp_leavewhen { givwhen(@_, $_[0]->keyword("when")); }
2597 my $name = $self->keyword("exists");
2598 if ($op->private & OPpEXISTS_SUB) {
2599 # Checking for the existence of a subroutine
2600 return $self->maybe_parens_func($name,
2601 $self->pp_rv2cv($op->first, 16), $cx, 16);
2603 if ($op->flags & OPf_SPECIAL) {
2604 # Array element, not hash element
2605 return $self->maybe_parens_func($name,
2606 $self->pp_aelem($op->first, 16), $cx, 16);
2608 return $self->maybe_parens_func($name, $self->pp_helem($op->first, 16),
2616 my $name = $self->keyword("delete");
2617 if ($op->private & (OPpSLICE|OPpKVSLICE)) {
2618 if ($op->flags & OPf_SPECIAL) {
2619 # Deleting from an array, not a hash
2620 return $self->maybe_parens_func($name,
2621 $self->pp_aslice($op->first, 16),
2624 return $self->maybe_parens_func($name,
2625 $self->pp_hslice($op->first, 16),
2628 if ($op->flags & OPf_SPECIAL) {
2629 # Deleting from an array, not a hash
2630 return $self->maybe_parens_func($name,
2631 $self->pp_aelem($op->first, 16),
2634 return $self->maybe_parens_func($name,
2635 $self->pp_helem($op->first, 16),
2643 my $opname = $op->flags & OPf_SPECIAL ? 'CORE::require' : 'require';
2644 my $kid = $op->first;
2645 if ($kid->name eq 'const') {
2646 my $priv = $kid->private;
2647 my $sv = $self->const_sv($kid);
2649 if ($priv & OPpCONST_BARE) {
2653 } elsif ($priv & OPpCONST_NOVER) {
2654 $opname = $self->keyword('no');
2655 $arg = $self->const($sv, 16);
2656 } elsif ((my $tmp = $self->const($sv, 16)) =~ /^v/) {
2660 return $self->maybe_parens("$opname $arg", $cx, 16);
2666 1, # llafr does not apply
2673 my $kid = $op->first;
2674 if (not null $kid->sibling) {
2675 # XXX Was a here-doc
2676 return $self->dquote($op);
2678 $self->unop(@_, "scalar");
2685 return $self->{'curcv'}->PADLIST->ARRAYelt(1)->ARRAYelt($targ);
2688 sub anon_hash_or_list {
2692 my($pre, $post) = @{{"anonlist" => ["[","]"],
2693 "anonhash" => ["{","}"]}->{$op->name}};
2695 $op = $op->first->sibling; # skip pushmark
2696 for (; !null($op); $op = $op->sibling) {
2697 $expr = $self->deparse($op, 6);
2700 if ($pre eq "{" and $cx < 1) {
2701 # Disambiguate that it's not a block
2704 return $pre . join(", ", @exprs) . $post;
2710 if ($op->flags & OPf_SPECIAL) {
2711 return $self->anon_hash_or_list($op, $cx);
2713 warn "Unexpected op pp_" . $op->name() . " without OPf_SPECIAL";
2717 *pp_anonhash = \&pp_anonlist;
2722 my $kid = $op->first;
2723 if ($kid->name eq "null") {
2724 my $anoncode = $kid = $kid->first;
2725 if ($anoncode->name eq "anonconst") {
2726 $anoncode = $anoncode->first->first->sibling;
2728 if ($anoncode->name eq "anoncode"
2729 or !null($anoncode = $kid->sibling) and
2730 $anoncode->name eq "anoncode") {
2731 return $self->e_anoncode({ code => $self->padval($anoncode->targ) });
2732 } elsif ($kid->name eq "pushmark") {
2733 my $sib_name = $kid->sibling->name;
2734 if ($sib_name eq 'entersub') {
2735 my $text = $self->deparse($kid->sibling, 1);
2736 # Always show parens for \(&func()), but only with -p otherwise
2737 $text = "($text)" if $self->{'parens'}
2738 or $kid->sibling->private & OPpENTERSUB_AMPER;
2743 local $self->{'in_refgen'} = 1;
2744 $self->pfixop($op, $cx, "\\", 20);
2748 my ($self, $info) = @_;
2749 my $text = $self->deparse_sub($info->{code});
2750 return $self->keyword("sub") . " $text";
2753 sub pp_srefgen { pp_refgen(@_) }
2758 my $kid = $op->first;
2760 and $op->flags & OPf_SPECIAL
2761 and $self->deparse($kid, 1) eq 'ARGV')
2765 return $self->unop($op, $cx, "readline");
2771 return "<" . $self->gv_name($self->gv_or_padgv($op)) . ">";
2774 # Unary operators that can occur as pseudo-listops inside double quotes
2777 my($op, $cx, $name, $prec, $flags) = (@_, 0, 0);
2779 if ($op->flags & OPf_KIDS) {
2781 # If there's more than one kid, the first is an ex-pushmark.
2782 $kid = $kid->sibling if not null $kid->sibling;
2783 return $self->maybe_parens_unop($name, $kid, $cx);
2785 return $name . ($op->flags & OPf_SPECIAL ? "()" : "");
2789 sub pp_ucfirst { dq_unop(@_, "ucfirst") }
2790 sub pp_lcfirst { dq_unop(@_, "lcfirst") }
2791 sub pp_uc { dq_unop(@_, "uc") }
2792 sub pp_lc { dq_unop(@_, "lc") }
2793 sub pp_quotemeta { maybe_targmy(@_, \&dq_unop, "quotemeta") }
2794 sub pp_fc { dq_unop(@_, "fc") }
2798 my ($op, $cx, $name) = @_;
2799 if (class($op) eq "PVOP") {
2800 $name .= " " . $op->pv;
2801 } elsif (class($op) eq "OP") {
2803 } elsif (class($op) eq "UNOP") {
2804 (my $kid = $self->deparse($op->first, 7)) =~ s/^\cS//;
2805 # last foo() is a syntax error.
2806 $kid =~ /^(?!\d)\w/ and $kid = "($kid)";
2809 return $self->maybe_parens($name, $cx, 7);
2812 sub pp_last { loopex(@_, "last") }
2813 sub pp_next { loopex(@_, "next") }
2814 sub pp_redo { loopex(@_, "redo") }
2815 sub pp_goto { loopex(@_, "goto") }
2816 sub pp_dump { loopex(@_, "CORE::dump") }
2820 my($op, $cx, $name) = @_;
2821 if (class($op) eq "UNOP") {
2822 # Genuine '-X' filetests are exempt from the LLAFR, but not
2824 if ($name =~ /^-/) {
2825 (my $kid = $self->deparse($op->first, 16)) =~ s/^\cS//;
2826 return $self->maybe_parens("$name $kid", $cx, 16);
2828 return $self->maybe_parens_unop($name, $op->first, $cx);
2829 } elsif (class($op) =~ /^(SV|PAD)OP$/) {
2830 return $self->maybe_parens_func($name, $self->pp_gv($op, 1), $cx, 16);
2831 } else { # I don't think baseop filetests ever survive ck_ftst, but...
2836 sub pp_lstat { ftst(@_, "lstat") }
2837 sub pp_stat { ftst(@_, "stat") }
2838 sub pp_ftrread { ftst(@_, "-R") }
2839 sub pp_ftrwrite { ftst(@_, "-W") }
2840 sub pp_ftrexec { ftst(@_, "-X") }
2841 sub pp_fteread { ftst(@_, "-r") }
2842 sub pp_ftewrite { ftst(@_, "-w") }
2843 sub pp_fteexec { ftst(@_, "-x") }
2844 sub pp_ftis { ftst(@_, "-e") }
2845 sub pp_fteowned { ftst(@_, "-O") }
2846 sub pp_ftrowned { ftst(@_, "-o") }
2847 sub pp_ftzero { ftst(@_, "-z") }
2848 sub pp_ftsize { ftst(@_, "-s") }
2849 sub pp_ftmtime { ftst(@_, "-M") }
2850 sub pp_ftatime { ftst(@_, "-A") }
2851 sub pp_ftctime { ftst(@_, "-C") }
2852 sub pp_ftsock { ftst(@_, "-S") }
2853 sub pp_ftchr { ftst(@_, "-c") }
2854 sub pp_ftblk { ftst(@_, "-b") }
2855 sub pp_ftfile { ftst(@_, "-f") }
2856 sub pp_ftdir { ftst(@_, "-d") }
2857 sub pp_ftpipe { ftst(@_, "-p") }
2858 sub pp_ftlink { ftst(@_, "-l") }
2859 sub pp_ftsuid { ftst(@_, "-u") }
2860 sub pp_ftsgid { ftst(@_, "-g") }
2861 sub pp_ftsvtx { ftst(@_, "-k") }
2862 sub pp_fttty { ftst(@_, "-t") }
2863 sub pp_fttext { ftst(@_, "-T") }
2864 sub pp_ftbinary { ftst(@_, "-B") }
2866 sub SWAP_CHILDREN () { 1 }
2867 sub ASSIGN () { 2 } # has OP= variant
2868 sub LIST_CONTEXT () { 4 } # Assignment is in list context
2874 my $name = $op->name;
2875 if ($name eq "concat" and $op->first->name eq "concat") {
2876 # avoid spurious '=' -- see comment in pp_concat
2879 if ($name eq "null" and class($op) eq "UNOP"
2880 and $op->first->name =~ /^(and|x?or)$/
2881 and null $op->first->sibling)
2883 # Like all conditional constructs, OP_ANDs and OP_ORs are topped
2884 # with a null that's used as the common end point of the two
2885 # flows of control. For precedence purposes, ignore it.
2886 # (COND_EXPRs have these too, but we don't bother with
2887 # their associativity).
2888 return assoc_class($op->first);
2890 return $name . ($op->flags & OPf_STACKED ? "=" : "");
2893 # Left associative operators, like '+', for which
2894 # $a + $b + $c is equivalent to ($a + $b) + $c
2897 %left = ('multiply' => 19, 'i_multiply' => 19,
2898 'divide' => 19, 'i_divide' => 19,
2899 'modulo' => 19, 'i_modulo' => 19,
2901 'add' => 18, 'i_add' => 18,
2902 'subtract' => 18, 'i_subtract' => 18,
2904 'left_shift' => 17, 'right_shift' => 17,
2905 'bit_and' => 13, 'nbit_and' => 13, 'sbit_and' => 13,
2906 'bit_or' => 12, 'bit_xor' => 12,
2907 'sbit_or' => 12, 'sbit_xor' => 12,
2908 'nbit_or' => 12, 'nbit_xor' => 12,
2910 'or' => 2, 'xor' => 2,
2914 sub deparse_binop_left {
2916 my($op, $left, $prec) = @_;
2917 if ($left{assoc_class($op)} && $left{assoc_class($left)}
2918 and $left{assoc_class($op)} == $left{assoc_class($left)})
2920 return $self->deparse($left, $prec - .00001);
2922 return $self->deparse($left, $prec);
2926 # Right associative operators, like '=', for which
2927 # $a = $b = $c is equivalent to $a = ($b = $c)
2930 %right = ('pow' => 22,
2931 'sassign=' => 7, 'aassign=' => 7,
2932 'multiply=' => 7, 'i_multiply=' => 7,
2933 'divide=' => 7, 'i_divide=' => 7,
2934 'modulo=' => 7, 'i_modulo=' => 7,
2935 'repeat=' => 7, 'refassign' => 7, 'refassign=' => 7,
2936 'add=' => 7, 'i_add=' => 7,
2937 'subtract=' => 7, 'i_subtract=' => 7,
2939 'left_shift=' => 7, 'right_shift=' => 7,
2940 'bit_and=' => 7, 'sbit_and=' => 7, 'nbit_and=' => 7,
2941 'nbit_or=' => 7, 'nbit_xor=' => 7,
2942 'sbit_or=' => 7, 'sbit_xor=' => 7,
2948 sub deparse_binop_right {
2950 my($op, $right, $prec) = @_;
2951 if ($right{assoc_class($op)} && $right{assoc_class($right)}
2952 and $right{assoc_class($op)} == $right{assoc_class($right)})
2954 return $self->deparse($right, $prec - .00001);
2956 return $self->deparse($right, $prec);
2962 my ($op, $cx, $opname, $prec, $flags) = (@_, 0);
2963 my $left = $op->first;
2964 my $right = $op->last;
2966 if ($op->flags & OPf_STACKED && $flags & ASSIGN) {
2970 if ($flags & SWAP_CHILDREN) {
2971 ($left, $right) = ($right, $left);
2974 $left = $self->deparse_binop_left($op, $left, $prec);
2975 $left = "($left)" if $flags & LIST_CONTEXT
2976 and $left !~ /^(my|our|local|state|)\s*[\@%\(]/
2978 # Parenthesize if the left argument is a
2980 my $left = $leftop->first->sibling;
2981 $left->name eq 'repeat'
2982 && null($left->sibling);
2984 $right = $self->deparse_binop_right($op, $right, $prec);
2985 return $self->maybe_parens("$left $opname$eq $right", $cx, $prec);
2988 sub pp_add { maybe_targmy(@_, \&binop, "+", 18, ASSIGN) }
2989 sub pp_multiply { maybe_targmy(@_, \&binop, "*", 19, ASSIGN) }
2990 sub pp_subtract { maybe_targmy(@_, \&binop, "-",18, ASSIGN) }
2991 sub pp_divide { maybe_targmy(@_, \&binop, "/", 19, ASSIGN) }
2992 sub pp_modulo { maybe_targmy(@_, \&binop, "%", 19, ASSIGN) }
2993 sub pp_i_add { maybe_targmy(@_, \&binop, "+", 18, ASSIGN) }
2994 sub pp_i_multiply { maybe_targmy(@_, \&binop, "*", 19, ASSIGN) }
2995 sub pp_i_subtract { maybe_targmy(@_, \&binop, "-", 18, ASSIGN) }
2996 sub pp_i_divide { maybe_targmy(@_, \&binop, "/", 19, ASSIGN) }
2997 sub pp_i_modulo { maybe_targmy(@_, \&binop, "%", 19, ASSIGN) }
2998 sub pp_pow { maybe_targmy(@_, \&binop, "**", 22, ASSIGN) }
3000 sub pp_left_shift { maybe_targmy(@_, \&binop, "<<", 17, ASSIGN) }
3001 sub pp_right_shift { maybe_targmy(@_, \&binop, ">>", 17, ASSIGN) }
3002 sub pp_bit_and { maybe_targmy(@_, \&binop, "&", 13, ASSIGN) }
3003 sub pp_bit_or { maybe_targmy(@_, \&binop, "|", 12, ASSIGN) }
3004 sub pp_bit_xor { maybe_targmy(@_, \&binop, "^", 12, ASSIGN) }
3005 *pp_nbit_and = *pp_bit_and;
3006 *pp_nbit_or = *pp_bit_or;
3007 *pp_nbit_xor = *pp_bit_xor;
3008 sub pp_sbit_and { maybe_targmy(@_, \&binop, "&.", 13, ASSIGN) }
3009 sub pp_sbit_or { maybe_targmy(@_, \&binop, "|.", 12, ASSIGN) }
3010 sub pp_sbit_xor { maybe_targmy(@_, \&binop, "^.", 12, ASSIGN) }
3012 sub pp_eq { binop(@_, "==", 14) }
3013 sub pp_ne { binop(@_, "!=", 14) }
3014 sub pp_lt { binop(@_, "<", 15) }
3015 sub pp_gt { binop(@_, ">", 15) }
3016 sub pp_ge { binop(@_, ">=", 15) }
3017 sub pp_le { binop(@_, "<=", 15) }
3018 sub pp_ncmp { binop(@_, "<=>", 14) }
3019 sub pp_i_eq { binop(@_, "==", 14) }
3020 sub pp_i_ne { binop(@_, "!=", 14) }
3021 sub pp_i_lt { binop(@_, "<", 15) }
3022 sub pp_i_gt { binop(@_, ">", 15) }
3023 sub pp_i_ge { binop(@_, ">=", 15) }
3024 sub pp_i_le { binop(@_, "<=", 15) }
3025 sub pp_i_ncmp { maybe_targmy(@_, \&binop, "<=>", 14) }
3027 sub pp_seq { binop(@_, "eq", 14) }
3028 sub pp_sne { binop(@_, "ne", 14) }
3029 sub pp_slt { binop(@_, "lt", 15) }
3030 sub pp_sgt { binop(@_, "gt", 15) }
3031 sub pp_sge { binop(@_, "ge", 15) }
3032 sub pp_sle { binop(@_, "le", 15) }
3033 sub pp_scmp { maybe_targmy(@_, \&binop, "cmp", 14) }
3035 sub pp_sassign { binop(@_, "=", 7, SWAP_CHILDREN) }
3036 sub pp_aassign { binop(@_, "=", 7, SWAP_CHILDREN | LIST_CONTEXT) }
3039 my ($self, $op, $cx) = @_;
3040 if (($op->flags & OPf_SPECIAL) && $self->{expand} < 2) {
3041 return $self->deparse($op->last, $cx);
3044 binop(@_, "~~", 14);
3048 # '.' is special because concats-of-concats are optimized to save copying
3049 # by making all but the first concat stacked. The effect is as if the
3050 # programmer had written '($a . $b) .= $c', except legal.
3051 sub pp_concat { maybe_targmy(@_, \&real_concat) }
3055 my $left = $op->first;
3056 my $right = $op->last;
3059 if (($op->flags & OPf_STACKED) and !($op->private & OPpCONCAT_NESTED)) {
3060 # '.=' rather than optimised '.'
3064 $left = $self->deparse_binop_left($op, $left, $prec);
3065 $right = $self->deparse_binop_right($op, $right, $prec);
3066 return $self->maybe_parens("$left .$eq $right", $cx, $prec);
3069 sub pp_repeat { maybe_targmy(@_, \&repeat) }
3071 # 'x' is weird when the left arg is a list
3075 my $left = $op->first;
3076 my $right = $op->last;
3079 if ($op->flags & OPf_STACKED) {
3083 if (null($right)) { # list repeat; count is inside left-side ex-list
3084 # in 5.21.5 and earlier
3085 my $kid = $left->first->sibling; # skip pushmark
3087 for (; !null($kid->sibling); $kid = $kid->sibling) {
3088 push @exprs, $self->deparse($kid, 6);
3091 $left = "(" . join(", ", @exprs). ")";
3093 my $dolist = $op->private & OPpREPEAT_DOLIST;
3094 $left = $self->deparse_binop_left($op, $left, $dolist ? 1 : $prec);
3099 $right = $self->deparse_binop_right($op, $right, $prec);
3100 return $self->maybe_parens("$left x$eq $right", $cx, $prec);
3105 my ($op, $cx, $type) = @_;
3106 my $left = $op->first;
3107 my $right = $left->sibling;
3108 $left = $self->deparse($left, 9);
3109 $right = $self->deparse($right, 9);
3110 return $self->maybe_parens("$left $type $right", $cx, 9);
3116 my $flip = $op->first;
3117 my $type = ($flip->flags & OPf_SPECIAL) ? "..." : "..";
3118 return $self->range($flip->first, $cx, $type);
3121 # one-line while/until is handled in pp_leave
3125 my ($op, $cx, $lowop, $lowprec, $highop, $highprec, $blockname) = @_;
3126 my $left = $op->first;
3127 my $right = $op->first->sibling;
3128 $blockname &&= $self->keyword($blockname);
3129 if ($cx < 1 and is_scope($right) and $blockname
3130 and $self->{'expand'} < 7)
3132 $left = $self->deparse($left, 1);
3133 $right = $self->deparse($right, 0);
3134 return "$blockname ($left) {\n\t$right\n\b}\cK";
3135 } elsif ($cx < 1 and $blockname and not $self->{'parens'}
3136 and $self->{'expand'} < 7) { # $b if $a
3137 $right = $self->deparse($right, 1);
3138 $left = $self->deparse($left, 1);
3139 return "$right $blockname $left";
3140 } elsif ($cx > $lowprec and $highop) { # $a && $b
3141 $left = $self->deparse_binop_left($op, $left, $highprec);
3142 $right = $self->deparse_binop_right($op, $right, $highprec);
3143 return $self->maybe_parens("$left $highop $right", $cx, $highprec);
3144 } else { # $a and $b
3145 $left = $self->deparse_binop_left($op, $left, $lowprec);
3146 $right = $self->deparse_binop_right($op, $right, $lowprec);
3147 return $self->maybe_parens("$left $lowop $right", $cx, $lowprec);
3151 sub pp_and { logop(@_, "and", 3, "&&", 11, "if") }
3152 sub pp_or { logop(@_, "or", 2, "||", 10, "unless") }
3153 sub pp_dor { logop(@_, "//", 10) }
3155 # xor is syntactically a logop, but it's really a binop (contrary to
3156 # old versions of opcode.pl). Syntax is what matters here.
3157 sub pp_xor { logop(@_, "xor", 2, "", 0, "") }
3161 my ($op, $cx, $opname) = @_;
3162 my $left = $op->first;
3163 my $right = $op->first->sibling->first; # skip sassign
3164 $left = $self->deparse($left, 7);
3165 $right = $self->deparse($right, 7);
3166 return $self->maybe_parens("$left $opname $right", $cx, 7);
3169 sub pp_andassign { logassignop(@_, "&&=") }
3170 sub pp_orassign { logassignop(@_, "||=") }
3171 sub pp_dorassign { logassignop(@_, "//=") }
3173 sub rv2gv_or_string {
3175 if ($op->name eq "gv") { # could be open("open") or open("###")
3177 $self->stash_variable_name("", $self->gv_or_padgv($op));
3178 $quoted ? $name : "*$name";
3181 $self->deparse($op, 6);
3187 my($op, $cx, $name, $kid, $nollafr) = @_;
3189 my $parens = ($cx >= 5) || $self->{'parens'};
3190 $kid ||= $op->first->sibling;
3191 # If there are no arguments, add final parentheses (or parenthesize the
3192 # whole thing if the llafr does not apply) to account for cases like
3193 # (return)+1 or setpgrp()+1. When the llafr does not apply, we use a
3194 # precedence of 6 (< comma), as "return, 1" does not need parentheses.
3197 ? $self->maybe_parens($self->keyword($name), $cx, 7)
3198 : $self->keyword($name) . '()' x (7 < $cx);
3201 my $fullname = $self->keyword($name);
3202 my $proto = prototype("CORE::$name");
3204 ( (defined $proto && $proto =~ /^;?\*/)
3205 || $name eq 'select' # select(F) doesn't have a proto
3207 && $kid->name eq "rv2gv"
3208 && !($kid->private & OPpLVAL_INTRO)
3210 $first = $self->rv2gv_or_string($kid->first);
3213 $first = $self->deparse($kid, 6);
3215 if ($name eq "chmod" && $first =~ /^\d+$/) {
3216 $first = sprintf("%#o", $first);
3219 if not $parens and not $nollafr and substr($first, 0, 1) eq "(";
3220 push @exprs, $first;
3221 $kid = $kid->sibling;
3222 if (defined $proto && $proto =~ /^\*\*/ && $kid->name eq "rv2gv"
3223 && !($kid->private & OPpLVAL_INTRO)) {
3224 push @exprs, $first = $self->rv2gv_or_string($kid->first);
3225 $kid = $kid->sibling;
3227 for (; !null($kid); $kid = $kid->sibling) {
3228 push @exprs, $self->deparse($kid, 6);
3230 if ($name eq "reverse" && ($op->private & OPpREVERSE_INPLACE)) {
3231 return "$exprs[0] = $fullname"
3232 . ($parens ? "($exprs[0])" : " $exprs[0]");
3235 if ($parens && $nollafr) {
3236 return "($fullname " . join(", ", @exprs) . ")";
3238 return "$fullname(" . join(", ", @exprs) . ")";
3240 return "$fullname " . join(", ", @exprs);
3244 sub pp_bless { listop(@_, "bless") }
3245 sub pp_atan2 { maybe_targmy(@_, \&listop, "atan2") }
3247 my ($self,$op,$cx) = @_;
3248 if ($op->private & OPpSUBSTR_REPL_FIRST) {
3250 listop($self, $op, 7, "substr", $op->first->sibling->sibling)
3252 . $self->deparse($op->first->sibling, 7);
3254 maybe_local(@_, listop(@_, "substr"))
3258 # Also handles pp_rindex.
3260 # The body of this function includes an unrolled maybe_targmy(),
3261 # since the two parts of that sub's actions need to have have the
3262 # '== -1' bit in between
3264 my($self, $op, $cx) = @_;
3266 my $lex = ($op->private & OPpTARGET_MY);
3267 my $bool = ($op->private & OPpTRUEBOOL);
3269 my $val = $self->listop($op, ($bool ? 14 : $lex ? 7 : $cx), $op->name);
3271 # (index() == -1) has op_eq and op_const optimised away
3273 $val .= ($op->private & OPpINDEX_BOOLNEG) ? " == -1" : " != -1";
3274 $val = "($val)" if ($op->flags & OPf_PARENS);
3277 my $var = $self->padname($op->targ);
3278 $val = $self->maybe_parens("$var = $val", $cx, 7);
3283 sub pp_rindex { pp_index(@_); }
3284 sub pp_vec { maybe_targmy(@_, \&maybe_local, listop(@_, "vec")) }
3285 sub pp_sprintf { maybe_targmy(@_, \&listop, "sprintf") }
3286 sub pp_formline { listop(@_, "formline") } # see also deparse_format
3287 sub pp_crypt { maybe_targmy(@_, \&listop, "crypt") }
3288 sub pp_unpack { listop(@_, "unpack") }
3289 sub pp_pack { listop(@_, "pack") }
3290 sub pp_join { maybe_targmy(@_, \&listop, "join") }
3291 sub pp_splice { listop(@_, "splice") }
3292 sub pp_push { maybe_targmy(@_, \&listop, "push") }
3293 sub pp_unshift { maybe_targmy(@_, \&listop, "unshift") }
3294 sub pp_reverse { listop(@_, "reverse") }
3295 sub pp_warn { listop(@_, "warn") }
3296 sub pp_die { listop(@_, "die") }
3297 sub pp_return { listop(@_, "return", undef, 1) } # llafr does not apply
3298 sub pp_open { listop(@_, "open") }
3299 sub pp_pipe_op { listop(@_, "pipe") }
3300 sub pp_tie { listop(@_, "tie") }
3301 sub pp_binmode { listop(@_, "binmode") }
3302 sub pp_dbmopen { listop(@_, "dbmopen") }
3303 sub pp_sselect { listop(@_, "select") }
3304 sub pp_select { listop(@_, "select") }
3305 sub pp_read { listop(@_, "read") }
3306 sub pp_sysopen { listop(@_, "sysopen") }
3307 sub pp_sysseek { listop(@_, "sysseek") }
3308 sub pp_sysread { listop(@_, "sysread") }
3309 sub pp_syswrite { listop(@_, "syswrite") }
3310 sub pp_send { listop(@_, "send") }
3311 sub pp_recv { listop(@_, "recv") }
3312 sub pp_seek { listop(@_, "seek") }
3313 sub pp_fcntl { listop(@_, "fcntl") }
3314 sub pp_ioctl { listop(@_, "ioctl") }
3315 sub pp_flock { maybe_targmy(@_, \&listop, "flock") }
3316 sub pp_socket { listop(@_, "socket") }
3317 sub pp_sockpair { listop(@_, "socketpair") }
3318 sub pp_bind { listop(@_, "bind") }
3319 sub pp_connect { listop(@_, "connect") }
3320 sub pp_listen { listop(@_, "listen") }
3321 sub pp_accept { listop(@_, "accept") }
3322 sub pp_shutdown { listop(@_, "shutdown") }
3323 sub pp_gsockopt { listop(@_, "getsockopt") }
3324 sub pp_ssockopt { listop(@_, "setsockopt") }
3325 sub pp_chown { maybe_targmy(@_, \&listop, "chown") }
3326 sub pp_unlink { maybe_targmy(@_, \&listop, "unlink") }
3327 sub pp_chmod { maybe_targmy(@_, \&listop, "chmod") }
3328 sub pp_utime { maybe_targmy(@_, \&listop, "utime") }
3329 sub pp_rename { maybe_targmy(@_, \&listop, "rename") }
3330 sub pp_link { maybe_targmy(@_, \&listop, "link") }
3331 sub pp_symlink { maybe_targmy(@_, \&listop, "symlink") }
3332 sub pp_mkdir { maybe_targmy(@_, \&listop, "mkdir") }
3333 sub pp_open_dir { listop(@_, "opendir") }
3334 sub pp_seekdir { listop(@_, "seekdir") }
3335 sub pp_waitpid { maybe_targmy(@_, \&listop, "waitpid") }
3336 sub pp_system { maybe_targmy(@_, \&indirop, "system") }
3337 sub pp_exec { maybe_targmy(@_, \&indirop, "exec") }
3338 sub pp_kill { maybe_targmy(@_, \&listop, "kill") }
3339 sub pp_setpgrp { maybe_targmy(@_, \&listop, "setpgrp") }
3340 sub pp_getpriority { maybe_targmy(@_, \&listop, "getpriority") }
3341 sub pp_setpriority { maybe_targmy(@_, \&listop, "setpriority") }
3342 sub pp_shmget { listop(@_, "shmget") }
3343 sub pp_shmctl { listop(@_, "shmctl") }
3344 sub pp_shmread { listop(@_, "shmread") }
3345 sub pp_shmwrite { listop(@_, "shmwrite") }
3346 sub pp_msgget { listop(@_, "msgget") }
3347 sub pp_msgctl { listop(@_, "msgctl") }
3348 sub pp_msgsnd { listop(@_, "msgsnd") }
3349 sub pp_msgrcv { listop(@_, "msgrcv") }
3350 sub pp_semget { listop(@_, "semget") }
3351 sub pp_semctl { listop(@_, "semctl") }
3352 sub pp_semop { listop(@_, "semop") }
3353 sub pp_ghbyaddr { listop(@_, "gethostbyaddr") }
3354 sub pp_gnbyaddr { listop(@_, "getnetbyaddr") }
3355 sub pp_gpbynumber { listop(@_, "getprotobynumber") }
3356 sub pp_gsbyname { listop(@_, "getservbyname") }
3357 sub pp_gsbyport { listop(@_, "getservbyport") }
3358 sub pp_syscall { listop(@_, "syscall") }
3363 my $kid = $op->first->sibling; # skip pushmark
3365 $op->flags & OPf_SPECIAL ? 'glob' : $self->keyword('glob');
3366 my $text = $self->deparse($kid);
3367 return $cx >= 5 || $self->{'parens'}
3372 # Truncate is special because OPf_SPECIAL makes a bareword first arg
3373 # be a filehandle. This could probably be better fixed in the core
3374 # by moving the GV lookup into ck_truc.
3380 my $parens = ($cx >= 5) || $self->{'parens'};
3381 my $kid = $op->first->sibling;
3383 if ($op->flags & OPf_SPECIAL) {
3384 # $kid is an OP_CONST
3385 $fh = $self->const_sv($kid)->PV;
3387 $fh = $self->deparse($kid, 6);
3388 $fh = "+$fh" if not $parens and substr($fh, 0, 1) eq "(";
3390 my $len = $self->deparse($kid->sibling, 6);
3391 my $name = $self->keyword('truncate');
3393 return "$name($fh, $len)";
3395 return "$name $fh, $len";
3401 my($op, $cx, $name) = @_;
3403 my $firstkid = my $kid = $op->first->sibling;
3405 if ($op->flags & OPf_STACKED) {
3407 $indir = $indir->first; # skip rv2gv
3408 if (is_scope($indir)) {
3409 $indir = "{" . $self->deparse($indir, 0) . "}";
3410 $indir = "{;}" if $indir eq "{}";
3411 } elsif ($indir->name eq "const" && $indir->private & OPpCONST_BARE) {
3412 $indir = $self->const_sv($indir)->PV;
3414 $indir = $self->deparse($indir, 24);
3416 $indir = $indir . " ";
3417 $kid = $kid->sibling;
3419 if ($name eq "sort" && $op->private & (OPpSORT_NUMERIC | OPpSORT_INTEGER)) {
3420 $indir = ($op->private & OPpSORT_DESCEND) ? '{$b <=> $a} '
3423 elsif ($name eq "sort" && $op->private & OPpSORT_DESCEND) {
3424 $indir = '{$b cmp $a} ';
3426 for (; !null($kid); $kid = $kid->sibling) {
3427 $expr = $self->deparse($kid, !$indir && $kid == $firstkid && $name eq "sort" && $firstkid->name eq "entersub" ? 16 : 6);
3431 if ($name eq "sort" && $op->private & OPpSORT_REVERSE) {
3432 $name2 = $self->keyword('reverse') . ' ' . $self->keyword('sort');
3434 else { $name2 = $self->keyword($name) }
3435 if ($name eq "sort" && ($op->private & OPpSORT_INPLACE)) {
3436 return "$exprs[0] = $name2 $indir $exprs[0]";
3439 my $args = $indir . join(", ", @exprs);
3440 if ($indir ne "" && $name eq "sort") {
3441 # We don't want to say "sort(f 1, 2, 3)", since perl -w will
3442 # give bareword warnings in that case. Therefore if context
3443 # requires, we'll put parens around the outside "(sort f 1, 2,
3444 # 3)". Unfortunately, we'll currently think the parens are
3445 # necessary more often that they really are, because we don't
3446 # distinguish which side of an assignment we're on.
3448 return "($name2 $args)";
3450 return "$name2 $args";
3453 !$indir && $name eq "sort"
3454 && !null($op->first->sibling)
3455 && $op->first->sibling->name eq 'entersub'
3457 # We cannot say sort foo(bar), as foo will be interpreted as a
3458 # comparison routine. We have to say sort(...) in that case.
3459 return "$name2($args)";
3462 ? $self->maybe_parens_func($name2, $args, $cx, 5)
3463 : $name2 . '()' x (7 < $cx);
3468 sub pp_prtf { indirop(@_, "printf") }
3469 sub pp_print { indirop(@_, "print") }
3470 sub pp_say { indirop(@_, "say") }
3471 sub pp_sort { indirop(@_, "sort") }
3475 my($op, $cx, $name) = @_;
3477 my $kid = $op->first; # this is the (map|grep)start
3478 $kid = $kid->first->sibling; # skip a pushmark
3479 my $code = $kid->first; # skip a null
3480 if (is_scope $code) {
3481 $code = "{" . $self->deparse($code, 0) . "} ";
3483 $code = $self->deparse($code, 24);
3484 $code .= ", " if !null($kid->sibling);
3486 $kid = $kid->sibling;
3487 for (; !null($kid); $kid = $kid->sibling) {
3488 $expr = $self->deparse($kid, 6);
3489 push @exprs, $expr if defined $expr;
3491 return $self->maybe_parens_func($self->keyword($name),
3492 $code . join(", ", @exprs), $cx, 5);
3495 sub pp_mapwhile { mapop(@_, "map") }
3496 sub pp_grepwhile { mapop(@_, "grep") }
3497 sub pp_mapstart { baseop(@_, "map") }
3498 sub pp_grepstart { baseop(@_, "grep") }
3503 eval { require B::Op_private }
3504 ? @{$B::Op_private::ops_using{OPpLVAL_INTRO}}
3505 : qw(gvsv rv2sv rv2hv rv2gv rv2av aelem helem aslice
3506 hslice delete padsv padav padhv enteriter entersub padrange
3507 pushmark cond_expr refassign list)
3509 delete @uses_intro{qw( lvref lvrefslice lvavref entersub )};
3513 # Look for a my/state attribute declaration in a list or ex-list.
3514 # Returns undef if not found, 'my($x, @a) :Foo(bar)' etc otherwise.
3516 # There are three basic tree structs that are expected:
3519 # <1> ex-list vK/LVINTRO ->c
3520 # <0> ex-pushmark v ->3
3521 # <1> entersub[t2] vKRS*/TARG ->b
3523 # <0> padsv[$x:64,65] vM/LVINTRO ->c
3528 # <1> ex-list vK ->c
3529 # <0> ex-pushmark v ->3
3530 # <0> padav[@a:64,65] vM/LVINTRO ->4
3531 # <1> entersub[t2] vKRS*/TARG ->c
3534 # my ($x,@a,%h) :foo;
3536 # <;> nextstate(main 64 -e:1) v:{ ->3
3538 # <0> pushmark vM/LVINTRO ->4
3539 # <0> padsv[$x:64,65] vM/LVINTRO ->5
3540 # <0> padav[@a:64,65] vM/LVINTRO ->6
3541 # <0> padhv[%h:64,65] vM/LVINTRO ->7
3542 # <1> entersub[t4] vKRS*/TARG ->f
3544 # <1> entersub[t5] vKRS*/TARG ->n
3546 # <1> entersub[t6] vKRS*/TARG ->v
3548 # where the entersub in all cases looks like
3549 # <1> entersub[t2] vKRS*/TARG ->c
3550 # <0> pushmark s ->5
3551 # <$> const[PV "attributes"] sM ->6
3552 # <$> const[PV "main"] sM ->7
3553 # <1> srefgen sKM/1 ->9
3554 # <1> ex-list lKRM ->8
3555 # <0> padsv[@a:64,65] sRM ->8
3556 # <$> const[PV "foo"] sM ->a
3557 # <.> method_named[PV "import"] ->b
3559 sub maybe_var_attr {
3560 my ($self, $op, $cx) = @_;
3562 my $kid = $op->first->sibling; # skip pushmark
3563 return if class($kid) eq 'NULL';
3568 # Extract out all the pad ops and entersub ops into
3569 # @padops and @entersubops. Return if anything else seen.
3570 # Also determine what class (if any) all the pad vars belong to
3572 my $decl; # 'my' or 'state'
3573 my (@padops, @entersubops);
3574 for ($lop = $kid; !null($lop); $lop = $lop->sibling) {
3575 my $lopname = $lop->name;
3576 my $loppriv = $lop->private;
3577 if ($lopname =~ /^pad[sah]v$/) {
3578 return unless $loppriv & OPpLVAL_INTRO;
3580 my $padname = $self->padname_sv($lop->targ);
3581 my $thisclass = ($padname->FLAGS & SVpad_TYPED)
3582 ? $padname->SvSTASH->NAME : 'main';
3584 # all pad vars must be in the same class
3585 $class //= $thisclass;
3586 return unless $thisclass eq $class;
3588 # all pad vars must be the same sort of declaration
3589 # (all my, all state, etc)
3590 my $this = ($loppriv & OPpPAD_STATE) ? 'state' : 'my';
3591 if (defined $decl) {
3592 return unless $this eq $decl;
3598 elsif ($lopname eq 'entersub') {
3599 push @entersubops, $lop;
3606 return unless @padops && @padops == @entersubops;
3608 # there should be a balance: each padop has a corresponding
3609 # 'attributes'->import() method call, in the same order.
3614 for my $i (0..$#padops) {
3615 my $padop = $padops[$i];
3616 my $esop = $entersubops[$i];
3618 push @varnames, $self->padname($padop->targ);
3620 return unless ($esop->flags & OPf_KIDS);
3622 my $kid = $esop->first;
3623 return unless $kid->type == OP_PUSHMARK;
3625 $kid = $kid->sibling;
3626 return unless $$kid && $kid->type == OP_CONST;
3627 return unless $self->const_sv($kid)->PV eq 'attributes';
3629 $kid = $kid->sibling;
3630 return unless $$kid && $kid->type == OP_CONST; # __PACKAGE__
3632 $kid = $kid->sibling;
3634 && $kid->name eq "srefgen"
3635 && ($kid->flags & OPf_KIDS)
3636 && ($kid->first->flags & OPf_KIDS)
3637 && $kid->first->first->name =~ /^pad[sah]v$/
3638 && $kid->first->first->targ == $padop->targ;
3640 $kid = $kid->sibling;
3643 last if ($kid->type != OP_CONST);
3644 push @attr, $self->const_sv($kid)->PV;
3645 $kid = $kid->sibling;
3647 return unless @attr;
3648 my $thisattr = ":" . join(' ', @attr);
3649 $attr_text //= $thisattr;
3650 # all import calls must have the same list of attributes
3651 return unless $attr_text eq $thisattr;
3653 return unless $kid->name eq 'method_named';
3654 return unless $self->meth_sv($kid)->PV eq 'import';
3656 $kid = $kid->sibling;
3661 $res .= " $class " if $class ne 'main';
3664 ? "(" . join(', ', @varnames) . ')'
3667 return "$res $attr_text";
3676 # might be my ($s,@a,%h) :Foo(bar);
3677 my $my_attr = maybe_var_attr($self, $op, $cx);
3678 return $my_attr if defined $my_attr;
3682 my $kid = $op->first->sibling; # skip pushmark
3683 return '' if class($kid) eq 'NULL';
3685 my $local = "either"; # could be local(...), my(...), state(...) or our(...)
3687 for ($lop = $kid; !null($lop); $lop = $lop->sibling) {
3688 my $lopname = $lop->name;
3689 my $loppriv = $lop->private;
3691 if ($lopname =~ /^pad[ash]v$/ && $loppriv & OPpLVAL_INTRO) {
3692 if ($loppriv & OPpPAD_STATE) { # state()
3693 ($local = "", last) if $local !~ /^(?:either|state)$/;
3696 ($local = "", last) if $local !~ /^(?:either|my)$/;
3699 my $padname = $self->padname_sv($lop->targ);
3700 if ($padname->FLAGS & SVpad_TYPED) {
3701 $newtype = $padname->SvSTASH->NAME;
3703 } elsif ($lopname =~ /^(?:gv|rv2)([ash])v$/
3704 && $loppriv & OPpOUR_INTRO
3705 or $lopname eq "null" && class($lop) eq 'UNOP'
3706 && $lop->first->name eq "gvsv"
3707 && $lop->first->private & OPpOUR_INTRO) { # our()
3708 my $newlocal = "local " x !!($loppriv & OPpLVAL_INTRO) . "our";
3710 if $local ne 'either' && $local ne $newlocal;
3712 my $funny = !$1 || $1 eq 's' ? '$' : $1 eq 'a' ? '@' : '%';
3713 if (my $t = $self->find_our_type(
3714 $funny . $self->gv_or_padgv($lop->first)->NAME
3718 } elsif ($lopname ne 'undef'
3719 and !($loppriv & OPpLVAL_INTRO)
3720 || !exists $uses_intro{$lopname eq 'null'
3721 ? substr B::ppname($lop->targ), 3
3724 $local = ""; # or not
3726 } elsif ($lopname ne "undef")
3729 ($local = "", last) if $local !~ /^(?:either|local)$/;
3732 if (defined $type && defined $newtype && $newtype ne $type) {
3738 $local = "" if $local eq "either"; # no point if it's all undefs
3739 $local &&= join ' ', map $self->keyword($_), split / /, $local;
3740 $local .= " $type " if $local && length $type;
3741 return $self->deparse($kid, $cx) if null $kid->sibling and not $local;
3742 for (; !null($kid); $kid = $kid->sibling) {
3744 if (class($kid) eq "UNOP" and $kid->first->name eq "gvsv") {
3749 $self->{'avoid_local'}{$$lop}++;
3750 $expr = $self->deparse($kid, 6);
3751 delete $self->{'avoid_local'}{$$lop};
3753 $expr = $self->deparse($kid, 6);
3758 if (@exprs == 1 && ($local eq 'state' || $local eq 'CORE::state')) {
3759 # 'state @a = ...' is legal, while 'state(@a) = ...' currently isn't
3760 return "$local $exprs[0]";
3762 return "$local(" . join(", ", @exprs) . ")";
3764 return $self->maybe_parens( join(", ", @exprs), $cx, 6);
3768 sub is_ifelse_cont {
3770 return ($op->name eq "null" and class($op) eq "UNOP"
3771 and $op->first->name =~ /^(and|cond_expr)$/
3772 and is_scope($op->first->first->sibling));
3778 my $cond = $op->first;
3779 my $true = $cond->sibling;
3780 my $false = $true->sibling;
3781 my $cuddle = $self->{'cuddle'};
3782 unless ($cx < 1 and (is_scope($true) and $true->name ne "null") and
3783 (is_scope($false) || is_ifelse_cont($false))
3784 and $self->{'expand'} < 7) {
3785 $cond = $self->deparse($cond, 8);
3786 $true = $self->deparse($true, 6);
3787 $false = $self->deparse($false, 8);
3788 return $self->maybe_parens("$cond ? $true : $false", $cx, 8);
3791 $cond = $self->deparse($cond, 1);
3792 $true = $self->deparse($true, 0);
3793 my $head = $self->keyword("if") . " ($cond) {\n\t$true\n\b}";
3796 while (!null($false) and is_ifelse_cont($false)) {
3797 my $newop = $false->first;
3798 my $newcond = $newop->first;
3799 my $newtrue = $newcond->sibling;
3800 $false = $newtrue->sibling; # last in chain is OP_AND => no else
3801 if ($newcond->name eq "lineseq")
3803 # lineseq to ensure correct line numbers in elsif()
3804 # Bug #37302 fixed by change #33710.
3805 $newcond = $newcond->first->sibling;
3807 $newcond = $self->deparse($newcond, 1);
3808 $newtrue = $self->deparse($newtrue, 0);
3809 $elsif ||= $self->keyword("elsif");
3810 push @elsifs, "$elsif ($newcond) {\n\t$newtrue\n\b}";
3812 if (!null($false)) {
3813 $false = $cuddle . $self->keyword("else") . " {\n\t" .
3814 $self->deparse($false, 0) . "\n\b}\cK";
3818 return $head . join($cuddle, "", @elsifs) . $false;
3822 my ($self, $op, $cx) = @_;
3823 my $cond = $op->first;
3824 my $true = $cond->sibling;
3826 my $ret = $self->deparse($true, $cx);
3827 $ret =~ s/^(\(?)\$/$1 . $self->keyword("state") . ' $'/e;
3833 my($op, $cx, $init) = @_;
3834 my $enter = $op->first;
3835 my $kid = $enter->sibling;
3836 local(@$self{qw'curstash warnings hints hinthash'})
3837 = @$self{qw'curstash warnings hints hinthash'};
3843 if ($kid->name eq "lineseq") { # bare or infinite loop
3844 if ($kid->last->name eq "unstack") { # infinite
3845 $head = "while (1) "; # Can't use for(;;) if there's a continue
3851 } elsif ($enter->name eq "enteriter") { # foreach
3852 my $ary = $enter->first->sibling; # first was pushmark
3853 my $var = $ary->sibling;
3854 if ($ary->name eq 'null' and $enter->private & OPpITER_REVERSED) {
3855 # "reverse" was optimised away
3856 $ary = listop($self, $ary->first->sibling, 1, 'reverse');
3857 } elsif ($enter->flags & OPf_STACKED
3858 and not null $ary->first->sibling->sibling)
3860 $ary = $self->deparse($ary->first->sibling, 9) . " .. " .
3861 $self->deparse($ary->first->sibling->sibling, 9);
3863 $ary = $self->deparse($ary, 1);
3866 $var = $self->pp_padsv($enter, 1, 1);
3867 } elsif ($var->name eq "rv2gv") {
3868 $var = $self->pp_rv2sv($var, 1);
3869 if ($enter->private & OPpOUR_INTRO) {
3870 # our declarations don't have package names
3871 $var =~ s/^(.).*::/$1/;
3874 } elsif ($var->name eq "gv") {
3875 $var = "\$" . $self->deparse($var, 1);
3877 $var = $self->deparse($var, 1);
3879 $body = $kid->first->first->sibling; # skip OP_AND and OP_ITER
3880 if (!is_state $body->first and $body->first->name !~ /^(?:stub|leave|scope)$/) {
3881 confess unless $var eq '$_';
3882 $body = $body->first;
3883 return $self->deparse($body, 2) . " "
3884 . $self->keyword("foreach") . " ($ary)";
3886 $head = "foreach $var ($ary) ";
3887 } elsif ($kid->name eq "null") { # while/until
3889 $name = {"and" => "while", "or" => "until"}->{$kid->name};
3890 $cond = $kid->first;
3891 $body = $kid->first->sibling;
3892 } elsif ($kid->name eq "stub") { # bare and empty
3893 return "{;}"; # {} could be a hashref
3895 # If there isn't a continue block, then the next pointer for the loop
3896 # will point to the unstack, which is kid's last child, except
3897 # in a bare loop, when it will point to the leaveloop. When neither of
3898 # these conditions hold, then the second-to-last child is the continue
3899 # block (or the last in a bare loop).
3900 my $cont_start = $enter->nextop;
3904 if ($$cont_start != $$op && ${$cont_start} != ${$body->last}) {
3906 $cont = $body->last;
3908 $cont = $body->first;
3909 while (!null($cont->sibling->sibling)) {
3910 $cont = $cont->sibling;
3913 my $state = $body->first;
3914 my $cuddle = $self->{'cuddle'};
3916 for (; $$state != $$cont; $state = $state->sibling) {
3917 push @states, $state;
3919 $body = $self->lineseq(undef, 0, @states);
3920 if (defined $cond and not is_scope $cont and $self->{'expand'} < 3) {
3921 $precond = "for ($init; ";
3922 $postcond = "; " . $self->deparse($cont, 1) .") ";
3925 $cont = $cuddle . "continue {\n\t" .
3926 $self->deparse($cont, 0) . "\n\b}\cK";
3929 return "" if !defined $body;
3931 $precond = "for ($init; ";
3935 $body = $self->deparse($body, 0);
3937 if ($precond) { # for(;;)
3938 $cond &&= $name eq 'until'
3939 ? listop($self, undef, 1, "not", $cond->first)
3940 : $self->deparse($cond, 1);
3941 $head = "$precond$cond$postcond";
3943 if ($name && !$head) {
3944 ref $cond and $cond = $self->deparse($cond, 1);
3945 $head = "$name ($cond) ";
3947 $head =~ s/^(for(?:each)?|while|until)/$self->keyword($1)/e;
3948 $body =~ s/;?$/;\n/;
3950 return $head . "{\n\t" . $body . "\b}" . $cont;
3953 sub pp_leaveloop { shift->loop_common(@_, "") }
3958 my $init = $self->deparse($op, 1);
3959 my $s = $op->sibling;
3960 my $ll = $s->name eq "unstack" ? $s->sibling : $s->first->sibling;
3961 return $self->loop_common($ll, $cx, $init);
3966 return "eval {\n\t" . $self->pp_leave(@_) . "\n\b}";
3970 my ($op, $expect_type) = @_;
3971 my $type = $op->type;
3972 return($type == $expect_type
3973 || ($type == OP_NULL && $op->targ == $expect_type));
3977 my($self, $op, $cx) = @_;
3979 # might be 'my $s :Foo(bar);'
3980 if ($op->targ == OP_LIST) {
3981 my $my_attr = maybe_var_attr($self, $op, $cx);
3982 return $my_attr if defined $my_attr;
3985 if (class($op) eq "OP") {
3987 return $self->{'ex_const'} if $op->targ == OP_CONST;
3988 } elsif (class ($op) eq "COP") {
3989 return &pp_nextstate;
3990 } elsif ($op->first->name eq 'pushmark'
3991 or $op->first->name eq 'null'
3992 && $op->first->targ == OP_PUSHMARK
3993 && _op_is_or_was($op, OP_LIST)) {
3994 return $self->pp_list($op, $cx);
3995 } elsif ($op->first->name eq "enter") {
3996 return $self->pp_leave($op, $cx);
3997 } elsif ($op->first->name eq "leave") {
3998 return $self->pp_leave($op->first, $cx);
3999 } elsif ($op->first->name eq "scope") {
4000 return $self->pp_scope($op->first, $cx);
4001 } elsif ($op->targ == OP_STRINGIFY) {
4002 return $self->dquote($op, $cx);
4003 } elsif ($op->targ == OP_GLOB) {
4004 return $self->pp_glob(
4005 $op->first # entersub
4011 } elsif (!null($op->first->sibling) and
4012 $op->first->sibling->name eq "readline" and
4013 $op->first->sibling->flags & OPf_STACKED) {
4014 return $self->maybe_parens($self->deparse($op->first, 7) . " = "
4015 . $self->deparse($op->first->sibling, 7),
4017 } elsif (!null($op->first->sibling) and
4018 $op->first->sibling->name =~ /^transr?\z/ and
4019 $op->first->sibling->flags & OPf_STACKED) {
4020 return $self->maybe_parens($self->deparse($op->first, 20) . " =~ "
4021 . $self->deparse($op->first->sibling, 20),
4023 } elsif ($op->flags & OPf_SPECIAL && $cx < 1 && !$op->targ) {
4024 return ($self->lex_in_scope("&do") ? "CORE::do" : "do")
4025 . " {\n\t". $self->deparse($op->first, $cx) ."\n\b};";
4026 } elsif (!null($op->first->sibling) and
4027 $op->first->sibling->name eq "null" and
4028 class($op->first->sibling) eq "UNOP" and
4029 $op->first->sibling->first->flags & OPf_STACKED and
4030 $op->first->sibling->first->name eq "rcatline") {
4031 return $self->maybe_parens($self->deparse($op->first, 18) . " .= "
4032 . $self->deparse($op->first->sibling, 18),
4035 return $self->deparse($op->first, $cx);
4042 return $self->padname_sv($targ)->PVX;
4048 return substr($self->padname($op->targ), 1); # skip $/@/%
4053 my($op, $cx, $forbid_parens) = @_;
4054 my $targ = $op->targ;
4055 return $self->maybe_my($op, $cx, $self->padname($targ),
4056 $self->padname_sv($targ),
4060 sub pp_padav { pp_padsv(@_) }
4062 # prepend 'keys' where its been optimised away, with suitable handling
4063 # of CORE:: and parens
4065 sub add_keys_keyword {
4066 my ($self, $str, $cx) = @_;
4067 $str = $self->maybe_parens($str, $cx, 16);
4068 # 'keys %h' versus 'keys(%h)'
4069 $str = " $str" unless $str =~ /^\(/;
4070 return $self->keyword("keys") . $str;
4074 my ($self, $op, $cx) = @_;
4075 my $str = pp_padsv(@_);
4076 # with OPpPADHV_ISKEYS the keys op is optimised away, except
4077 # in scalar context the old op is kept (but not executed) so its targ
4079 if ( ($op->private & OPpPADHV_ISKEYS)
4080 && !(($op->flags & OPf_WANT) == OPf_WANT_SCALAR))
4082 $str = $self->add_keys_keyword($str, $cx);
4090 if (class($op) eq "PADOP") {
4091 return $self->padval($op->padix);
4092 } else { # class($op) eq "SVOP"
4100 my $gv = $self->gv_or_padgv($op);
4101 return $self->maybe_local($op, $cx, $self->stash_variable("\$",
4102 $self->gv_name($gv), $cx));
4108 my $gv = $self->gv_or_padgv($op);
4109 return $self->maybe_qualify("", $self->gv_name($gv));
4112 sub pp_aelemfast_lex {
4115 my $name = $self->padname($op->targ);
4117 my $i = $op->private;
4118 $i -= 256 if $i > 127;
4119 return $name . "[" . ($i + $self->{'arybase'}) . "]";
4125 # optimised PADAV, pre 5.15
4126 return $self->pp_aelemfast_lex(@_) if ($op->flags & OPf_SPECIAL);
4128 my $gv = $self->gv_or_padgv($op);
4129 my($name,$quoted) = $self->stash_variable_name('@',$gv);
4130 $name = $quoted ? "$name->" : '$' . $name;
4131 my $i = $op->private;
4132 $i -= 256 if $i > 127;
4133 return $name . "[" . ($i + $self->{'arybase'}) . "]";
4138 my($op, $cx, $type) = @_;
4140 if (class($op) eq 'NULL' || !$op->can("first")) {
4141 carp("Unexpected op in pp_rv2x");
4144 my $kid = $op->first;
4145 if ($kid->name eq "gv") {
4146 return $self->stash_variable($type,
4147 $self->gv_name($self->gv_or_padgv($kid)), $cx);
4148 } elsif (is_scalar $kid) {
4149 my $str = $self->deparse($kid, 0);
4150 if ($str =~ /^\$([^\w\d])\z/) {
4151 # "$$+" isn't a legal way to write the scalar dereference
4152 # of $+, since the lexer can't tell you aren't trying to
4153 # do something like "$$ + 1" to get one more than your
4154 # PID. Either "${$+}" or "$${+}" are workable
4155 # disambiguations, but if the programmer did the former,
4156 # they'd be in the "else" clause below rather than here.
4157 # It's not clear if this should somehow be unified with
4158 # the code in dq and re_dq that also adds lexer
4159 # disambiguation braces.
4160 $str = '$' . "{$1}"; #'
4162 return $type . $str;
4164 return $type . "{" . $self->deparse($kid, 0) . "}";
4168 sub pp_rv2sv { maybe_local(@_, rv2x(@_, "\$")) }
4169 sub pp_rv2gv { maybe_local(@_, rv2x(@_, "*")) }
4172 my ($self, $op, $cx) = @_;
4173 my $str = rv2x(@_, "%");
4174 if ($op->private & OPpRV2HV_ISKEYS) {
4175 $str = $self->add_keys_keyword($str, $cx);
4177 return maybe_local(@_, $str);
4184 if ($op->first->name eq "padav") {
4185 return $self->maybe_local($op, $cx, '$#' . $self->padany($op->first));
4187 return $self->maybe_local($op, $cx,
4188 $self->rv2x($op->first, $cx, '$#'));
4192 # skip down to the old, ex-rv2cv
4194 my ($self, $op, $cx) = @_;
4195 if (!null($op->first) && $op->first->name eq 'null' &&
4196 $op->first->targ == OP_LIST)
4198 return $self->rv2x($op->first->first->sibling, $cx, "&")
4201 return $self->rv2x($op, $cx, "")
4207 my($cx, @list) = @_;
4208 my @a = map $self->const($_, 6), @list;
4213 } elsif ( @a > 2 and !grep(!/^-?\d+$/, @a)) {
4214 # collapse (-1,0,1,2) into (-1..2)
4215 my ($s, $e) = @a[0,-1];
4217 return $self->maybe_parens("$s..$e", $cx, 9)
4218 unless grep $i++ != $_, @a;
4220 return $self->maybe_parens(join(", ", @a), $cx, 6);
4226 my $kid = $op->first;
4227 if ($kid->name eq "const") { # constant list
4228 my $av = $self->const_sv($kid);
4229 return $self->list_const($cx, $av->ARRAY);
4231 return $self->maybe_local($op, $cx, $self->rv2x($op, $cx, "\@"));
4235 sub is_subscriptable {
4237 if ($op->name =~ /^([ahg]elem|multideref$)/) {
4239 } elsif ($op->name eq "entersub") {
4240 my $kid = $op->first;
4241 return 0 unless null $kid->sibling;
4243 $kid = $kid->sibling until null $kid->sibling;
4244 return 0 if is_scope($kid);
4246 return 0 if $kid->name eq "gv" || $kid->name eq "padcv";
4247 return 0 if is_scalar($kid);
4248 return is_subscriptable($kid);
4254 sub elem_or_slice_array_name
4257 my ($array, $left, $padname, $allow_arrow) = @_;
4259 if ($array->name eq $padname) {
4260 return $self->padany($array);
4261 } elsif (is_scope($array)) { # ${expr}[0]
4262 return "{" . $self->deparse($array, 0) . "}";
4263 } elsif ($array->name eq "gv") {
4264 ($array, my $quoted) =
4265 $self->stash_variable_name(
4266 $left eq '[' ? '@' : '%', $self->gv_or_padgv($array)
4268 if (!$allow_arrow && $quoted) {
4269 # This cannot happen.
4270 die "Invalid variable name $array for slice";
4272 return $quoted ? "$array->" : $array;
4273 } elsif (!$allow_arrow || is_scalar $array) { # $x[0], $$x[0], ...
4274 return $self->deparse($array, 24);
4280 sub elem_or_slice_single_index
4285 $idx = $self->deparse($idx, 1);
4287 # Outer parens in an array index will confuse perl
4288 # if we're interpolating in a regular expression, i.e.
4289 # /$x$foo[(-1)]/ is *not* the same as /$x$foo[-1]/
4291 # If $self->{parens}, then an initial '(' will
4292 # definitely be paired with a final ')'. If
4293 # !$self->{parens}, the misleading parens won't
4294 # have been added in the first place.
4296 # [You might think that we could get "(...)...(...)"
4297 # where the initial and final parens do not match
4298 # each other. But we can't, because the above would
4299 # only happen if there's an infix binop between the
4300 # two pairs of parens, and *that* means that the whole
4301 # expression would be parenthesized as well.]
4303 $idx =~ s/^\((.*)\)$/$1/ if $self->{'parens'};
4305 # Hash-element braces will autoquote a bareword inside themselves.
4306 # We need to make sure that C<$hash{warn()}> doesn't come out as
4307 # C<$hash{warn}>, which has a quite different meaning. Currently
4308 # B::Deparse will always quote strings, even if the string was a
4309 # bareword in the original (i.e. the OPpCONST_BARE flag is ignored
4310 # for constant strings.) So we can cheat slightly here - if we see
4311 # a bareword, we know that it is supposed to be a function call.
4313 $idx =~ s/^([A-Za-z_]\w*)$/$1()/;
4320 my ($op, $cx, $left, $right, $padname) = @_;
4321 my($array, $idx) = ($op->first, $op->first->sibling);
4323 $idx = $self->elem_or_slice_single_index($idx);
4325 unless ($array->name eq $padname) { # Maybe this has been fixed
4326 $array = $array->first; # skip rv2av (or ex-rv2av in _53+)
4328 if (my $array_name=$self->elem_or_slice_array_name
4329 ($array, $left, $padname, 1)) {
4330 return ($array_name =~ /->\z/
4332 : $array_name eq '#' ? '${#}' : "\$" . $array_name)
4333 . $left . $idx . $right;
4335 # $x[20][3]{hi} or expr->[20]
4336 my $arrow = is_subscriptable($array) ? "" : "->";
4337 return $self->deparse($array, 24) . $arrow . $left . $idx . $right;
4342 # a simplified version of elem_or_slice_array_name()
4343 # for the use of pp_multideref
4345 sub multideref_var_name {
4347 my ($gv, $is_hash) = @_;
4349 my ($name, $quoted) =
4350 $self->stash_variable_name( $is_hash ? '%' : '@', $gv);
4351 return $quoted ? "$name->"
4353 ? '${#}' # avoid ${#}[1] => $#[1]
4358 # deparse an OP_MULTICONCAT. If $in_dq is 1, we're within
4359 # a double-quoted string, so for example.
4361 # might get compiled as
4362 # multiconcat("abc", metaquote(multiconcat("def", $x)), "bar")
4363 # and the inner multiconcat should be deparsed as C<def$x> rather than
4364 # the normal C<def . $x>
4365 # Ditto if $in_dq is 2, handle qr/...\Qdef$x\E.../.
4367 sub do_multiconcat {
4369 my($op, $cx, $in_dq) = @_;
4377 for ($kid = $op->first; !null $kid; $kid = $kid->sibling) {
4378 # skip the consts and/or padsv we've optimised away
4380 unless $kid->type == OP_NULL
4381 && ( $kid->targ == OP_PADSV
4382 || $kid->targ == OP_CONST
4383 || $kid->targ == OP_PUSHMARK);
4386 $append = ($op->private & OPpMULTICONCAT_APPEND);
4388 if ($op->private & OPpTARGET_MY) {
4389 # '$lex = ...' or '$lex .= ....' or 'my $lex = '
4390 $lhs = $self->padname($op->targ);
4391 $lhs = "my $lhs" if ($op->private & OPpLVAL_INTRO);
4394 elsif ($op->flags & OPf_STACKED) {
4395 # 'expr = ...' or 'expr .= ....'
4396 my $expr = $append ? shift(@kids) : pop(@kids);
4397 $lhs = $self->deparse($expr, 7);
4402 $lhs .= $append ? ' .= ' : ' = ';
4405 my ($nargs, $const_str, @const_lens) = $op->aux_list($self->{curcv});
4411 push @consts, undef;
4414 push @consts, substr($const_str, $i, $_);
4423 || (($op->private & OPpMULTICONCAT_STRINGIFY) && !$self->{'unquote'}))
4425 # "foo=$foo bar=$bar "
4429 my $s = $self->dq(shift(@kids), 18);
4430 # don't deparse "a${$}b" as "a$$b"
4431 $s = '${$}' if $s eq '$$';
4432 $rhs = dq_disambiguate($rhs, $s);
4435 my $c = shift @consts;
4438 # in pattern: don't convert newline to '\n' etc etc
4439 my $s = re_uninterp(escape_re(re_unback($c)));
4440 $rhs = re_dq_disambiguate($rhs, $s)
4443 my $s = uninterp(escape_str(unback($c)));
4444 $rhs = dq_disambiguate($rhs, $s)
4448 return $rhs if $in_dq;
4449 $rhs = single_delim("qq", '"', $rhs, $self);
4451 elsif ($op->private & OPpMULTICONCAT_FAKE) {
4452 # sprintf("foo=%s bar=%s ", $foo, $bar)
4455 @consts = map { $_ //= ''; s/%/%%/g; $_ } @consts;
4456 my $fmt = join '%s', @consts;
4457 push @all, $self->quoted_const_str($fmt);
4459 # the following is a stripped down copy of sub listop {}
4460 my $parens = $assign || ($cx >= 5) || $self->{'parens'};
4461 my $fullname = $self->keyword('sprintf');
4462 push @all, map $self->deparse($_, 6), @kids;
4465 ? "$fullname(" . join(", ", @all) . ")"
4466 : "$fullname " . join(", ", @all);
4469 # "foo=" . $foo . " bar=" . $bar
4473 push @all, $self->deparse(shift(@kids), 18) if $not_first;
4475 my $c = shift @consts;
4477 push @all, $self->quoted_const_str($c);