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 : prototype($$) lvalue ($a, $b) { ...; };
1287 Carp::confess("NULL in deparse_sub") if !defined($cv) || $cv->isa("B::NULL");
1288 Carp::confess("SPECIAL in deparse_sub") if $cv->isa("B::SPECIAL");
1289 local $self->{'curcop'} = $self->{'curcop'};
1291 my $has_sig = $self->{hinthash}{feature_signatures};
1292 if ($cv->FLAGS & SVf_POK) {
1293 my $myproto = $cv->PV;
1295 push @attrs, "prototype($myproto)";
1301 if ($cv->CvFLAGS & (CVf_METHOD|CVf_LOCKED|CVf_LVALUE|CVf_ANONCONST)) {
1302 push @attrs, "lvalue" if $cv->CvFLAGS & CVf_LVALUE;
1303 push @attrs, "method" if $cv->CvFLAGS & CVf_METHOD;
1304 push @attrs, "const" if $cv->CvFLAGS & CVf_ANONCONST;
1307 local($self->{'curcv'}) = $cv;
1308 local($self->{'curcvlex'});
1309 local(@$self{qw'curstash warnings hints hinthash'})
1310 = @$self{qw'curstash warnings hints hinthash'};
1312 my $root = $cv->ROOT;
1313 local $B::overlay = {};
1314 if (not null $root) {
1315 $self->pad_subs($cv);
1316 $self->pessimise($root, $cv->START);
1317 my $lineseq = $root->first;
1318 if ($lineseq->name eq "lineseq") {
1319 my $firstop = $lineseq->first;
1323 # try to deparse first few ops as a signature if possible
1325 and $firstop->name =~ /^(next|db)state$/
1326 and (($o2 = $firstop->sibling))
1329 if ($o2->name eq 'argcheck') {
1330 my ($nexto, $mysig) = $self->deparse_argops($firstop, $cv);
1331 if (defined $nexto) {
1340 for (my $o = $firstop; $$o; $o=$o->sibling) {
1343 $body = $self->lineseq(undef, 0, @ops).";";
1344 if (!$has_sig and $ops[-1]->name =~ /^(next|db)state$/) {
1345 # this handles void context in
1346 # use feature signatures; sub ($=1) {}
1349 my $scope_en = $self->find_scope_en($lineseq);
1350 if (defined $scope_en) {
1351 my $subs = join"", $self->seq_subs($scope_en);
1352 $body .= ";\n$subs" if length($subs);
1356 $body = $self->deparse($root->first, 0);
1358 $body = "{\n\t$body\n\b}";
1361 my $sv = $cv->const_sv;
1363 # uh-oh. inlinable sub... format it differently
1364 $body = "{ " . $self->const($sv, 0) . " }\n";
1365 } else { # XSUB? (or just a declaration)
1369 $proto = defined $proto ? "($proto) " : "";
1370 $sig = defined $sig ? "($sig) " : "";
1372 $attrs = ': ' . join('', map "$_ ", @attrs) if @attrs;
1373 return "$proto$attrs$sig$body\n";
1376 sub deparse_format {
1380 local($self->{'curcv'}) = $form;
1381 local($self->{'curcvlex'});
1382 local($self->{'in_format'}) = 1;
1383 local(@$self{qw'curstash warnings hints hinthash'})
1384 = @$self{qw'curstash warnings hints hinthash'};
1385 my $op = $form->ROOT;
1386 local $B::overlay = {};
1387 $self->pessimise($op, $form->START);
1389 return "\f." if $op->first->name eq 'stub'
1390 || $op->first->name eq 'nextstate';
1391 $op = $op->first->first; # skip leavewrite, lineseq
1392 while (not null $op) {
1393 $op = $op->sibling; # skip nextstate
1395 $kid = $op->first->sibling; # skip pushmark
1396 push @text, "\f".$self->const_sv($kid)->PV;
1397 $kid = $kid->sibling;
1398 for (; not null $kid; $kid = $kid->sibling) {
1399 push @exprs, $self->deparse($kid, -1);
1400 $exprs[-1] =~ s/;\z//;
1402 push @text, "\f".join(", ", @exprs)."\n" if @exprs;
1405 return join("", @text) . "\f.";
1410 return $op->name eq "leave" || $op->name eq "scope"
1411 || $op->name eq "lineseq"
1412 || ($op->name eq "null" && class($op) eq "UNOP"
1413 && (is_scope($op->first) || $op->first->name eq "enter"));
1417 my $name = $_[0]->name;
1418 return $name eq "nextstate" || $name eq "dbstate" || $name eq "setstate";
1421 sub is_miniwhile { # check for one-line loop ('foo() while $y--')
1423 return (!null($op) and null($op->sibling)
1424 and $op->name eq "null" and class($op) eq "UNOP"
1425 and (($op->first->name =~ /^(and|or)$/
1426 and $op->first->first->sibling->name eq "lineseq")
1427 or ($op->first->name eq "lineseq"
1428 and not null $op->first->first->sibling
1429 and $op->first->first->sibling->name eq "unstack")
1433 # Check if the op and its sibling are the initialization and the rest of a
1434 # for (..;..;..) { ... } loop
1437 # This OP might be almost anything, though it won't be a
1438 # nextstate. (It's the initialization, so in the canonical case it
1439 # will be an sassign.) The sibling is (old style) a lineseq whose
1440 # first child is a nextstate and whose second is a leaveloop, or
1441 # (new style) an unstack whose sibling is a leaveloop.
1442 my $lseq = $op->sibling;
1443 return 0 unless !is_state($op) and !null($lseq);
1444 if ($lseq->name eq "lineseq") {
1445 if ($lseq->first && !null($lseq->first) && is_state($lseq->first)
1446 && (my $sib = $lseq->first->sibling)) {
1447 return (!null($sib) && $sib->name eq "leaveloop");
1449 } elsif ($lseq->name eq "unstack" && ($lseq->flags & OPf_SPECIAL)) {
1450 my $sib = $lseq->sibling;
1451 return $sib && !null($sib) && $sib->name eq "leaveloop";
1458 return ($op->name eq "rv2sv" or
1459 $op->name eq "padsv" or
1460 $op->name eq "gv" or # only in array/hash constructs
1461 $op->flags & OPf_KIDS && !null($op->first)
1462 && $op->first->name eq "gvsv");
1467 my($text, $cx, $prec) = @_;
1468 if ($prec < $cx # unary ops nest just fine
1469 or $prec == $cx and $cx != 4 and $cx != 16 and $cx != 21
1470 or $self->{'parens'})
1473 # In a unop, let parent reuse our parens; see maybe_parens_unop
1474 $text = "\cS" . $text if $cx == 16;
1481 # same as above, but get around the 'if it looks like a function' rule
1482 sub maybe_parens_unop {
1484 my($name, $kid, $cx) = @_;
1485 if ($cx > 16 or $self->{'parens'}) {
1486 $kid = $self->deparse($kid, 1);
1487 if ($name eq "umask" && $kid =~ /^\d+$/) {
1488 $kid = sprintf("%#o", $kid);
1490 return $self->keyword($name) . "($kid)";
1492 $kid = $self->deparse($kid, 16);
1493 if ($name eq "umask" && $kid =~ /^\d+$/) {
1494 $kid = sprintf("%#o", $kid);
1496 $name = $self->keyword($name);
1497 if (substr($kid, 0, 1) eq "\cS") {
1499 return $name . substr($kid, 1);
1500 } elsif (substr($kid, 0, 1) eq "(") {
1501 # avoid looks-like-a-function trap with extra parens
1502 # ('+' can lead to ambiguities)
1503 return "$name(" . $kid . ")";
1505 return "$name $kid";
1510 sub maybe_parens_func {
1512 my($func, $text, $cx, $prec) = @_;
1513 if ($prec <= $cx or substr($text, 0, 1) eq "(" or $self->{'parens'}) {
1514 return "$func($text)";
1516 return "$func $text";
1521 my ($self, $name) = @_;
1522 $self->populate_curcvlex() if !defined $self->{'curcvlex'};
1523 my $seq = $self->{'curcop'} ? $self->{'curcop'}->cop_seq : 0;
1524 for my $a (@{$self->{'curcvlex'}{"o$name"}}) {
1525 my ($st, undef, $padname) = @$a;
1526 if ($st >= $seq && $padname->FLAGS & SVpad_TYPED) {
1527 return $padname->SvSTASH->NAME;
1535 my($op, $cx, $text) = @_;
1536 my $name = $op->name;
1537 my $our_intro = ($name =~ /^(?:(?:gv|rv2)[ash]v|split|refassign
1541 my $lval_intro = $name eq 'split' ? 0 : OPpLVAL_INTRO;
1542 # The @a in \(@a) isn't in ref context, but only when the
1544 my $need_parens = $self->{'in_refgen'} && $name =~ /[ah]v\z/
1545 && ($op->flags & (OPf_PARENS|OPf_REF)) == OPf_PARENS;
1546 if ((my $priv = $op->private) & ($lval_intro|$our_intro)) {
1548 push @our_local, "local" if $priv & $lval_intro;
1549 push @our_local, "our" if $priv & $our_intro;
1550 my $our_local = join " ", map $self->keyword($_), @our_local;
1551 if( $our_local[-1] eq 'our' ) {
1552 if ( $text !~ /^\W(\w+::)*\w+\z/
1553 and !utf8::decode($text) || $text !~ /^\W(\w+::)*\w+\z/
1555 die "Unexpected our($text)\n";
1557 $text =~ s/(\w+::)+//;
1559 if (my $type = $self->find_our_type($text)) {
1560 $our_local .= ' ' . $type;
1563 return $need_parens ? "($text)" : $text
1564 if $self->{'avoid_local'}{$$op};
1566 return "$our_local($text)";
1567 } elsif (want_scalar($op)) {
1568 return "$our_local $text";
1570 return $self->maybe_parens_func("$our_local", $text, $cx, 16);
1573 return $need_parens ? "($text)" : $text;
1579 my($op, $cx, $func, @args) = @_;
1580 if ($op->private & OPpTARGET_MY) {
1581 my $var = $self->padname($op->targ);
1582 my $val = $func->($self, $op, 7, @args);
1583 return $self->maybe_parens("$var = $val", $cx, 7);
1585 return $func->($self, $op, $cx, @args);
1592 return $self->{'curcv'}->PADLIST->ARRAYelt(0)->ARRAYelt($targ);
1597 my($op, $cx, $text, $padname, $forbid_parens) = @_;
1598 # The @a in \(@a) isn't in ref context, but only when the
1600 my $need_parens = !$forbid_parens && $self->{'in_refgen'}
1601 && $op->name =~ /[ah]v\z/
1602 && ($op->flags & (OPf_PARENS|OPf_REF)) == OPf_PARENS;
1603 # The @a in \my @a must not have parens.
1604 if (!$need_parens && $self->{'in_refgen'}) {
1607 if ($op->private & OPpLVAL_INTRO and not $self->{'avoid_local'}{$$op}) {
1608 # Check $padname->FLAGS for statehood, rather than $op->private,
1609 # because enteriter ops do not carry the flag.
1611 $self->keyword($padname->FLAGS & SVpad_STATE ? "state" : "my");
1612 if ($padname->FLAGS & SVpad_TYPED) {
1613 $my .= ' ' . $padname->SvSTASH->NAME;
1616 return "$my($text)";
1617 } elsif ($forbid_parens || want_scalar($op)) {
1620 return $self->maybe_parens_func($my, $text, $cx, 16);
1623 return $need_parens ? "($text)" : $text;
1627 # The following OPs don't have functions:
1629 # pp_padany -- does not exist after parsing
1632 if ($AUTOLOAD =~ s/^.*::pp_//) {
1633 warn "unexpected OP_".
1634 ($_[1]->type == OP_CUSTOM ? "CUSTOM ($AUTOLOAD)" : uc $AUTOLOAD);
1637 die "Undefined subroutine $AUTOLOAD called";
1641 sub DESTROY {} # Do not AUTOLOAD
1643 # $root should be the op which represents the root of whatever
1644 # we're sequencing here. If it's undefined, then we don't append
1645 # any subroutine declarations to the deparsed ops, otherwise we
1646 # append appropriate declarations.
1648 my($self, $root, $cx, @ops) = @_;
1651 my $out_cop = $self->{'curcop'};
1652 my $out_seq = defined($out_cop) ? $out_cop->cop_seq : undef;
1654 if (defined $root) {
1655 $limit_seq = $out_seq;
1657 $nseq = $self->find_scope_st($root->sibling) if ${$root->sibling};
1658 $limit_seq = $nseq if !defined($limit_seq)
1659 or defined($nseq) && $nseq < $limit_seq;
1661 $limit_seq = $self->{'limit_seq'}
1662 if defined($self->{'limit_seq'})
1663 && (!defined($limit_seq) || $self->{'limit_seq'} < $limit_seq);
1664 local $self->{'limit_seq'} = $limit_seq;
1666 $self->walk_lineseq($root, \@ops,
1667 sub { push @exprs, $_[0]} );
1669 my $sep = $cx ? '; ' : ";\n";
1670 my $body = join($sep, grep {length} @exprs);
1672 if (defined $root && defined $limit_seq && !$self->{'in_format'}) {
1673 $subs = join "\n", $self->seq_subs($limit_seq);
1675 return join($sep, grep {length} $body, $subs);
1679 my($real_block, $self, $op, $cx) = @_;
1683 local(@$self{qw'curstash warnings hints hinthash'})
1684 = @$self{qw'curstash warnings hints hinthash'} if $real_block;
1686 $kid = $op->first->sibling; # skip enter
1687 if (is_miniwhile($kid)) {
1688 my $top = $kid->first;
1689 my $name = $top->name;
1690 if ($name eq "and") {
1691 $name = $self->keyword("while");
1692 } elsif ($name eq "or") {
1693 $name = $self->keyword("until");
1694 } else { # no conditional -> while 1 or until 0
1695 return $self->deparse($top->first, 1) . " "
1696 . $self->keyword("while") . " 1";
1698 my $cond = $top->first;
1699 my $body = $cond->sibling->first; # skip lineseq
1700 $cond = $self->deparse($cond, 1);
1701 $body = $self->deparse($body, 1);
1702 return "$body $name $cond";
1707 for (; !null($kid); $kid = $kid->sibling) {
1710 if ($cx > 0) { # inside an expression, (a do {} while for lineseq)
1711 my $body = $self->lineseq($op, 0, @kids);
1712 return is_lexical_subs(@kids)
1714 : ($self->lex_in_scope("&do") ? "CORE::do" : "do")
1715 . " {\n\t$body\n\b}";
1717 my $lineseq = $self->lineseq($op, $cx, @kids);
1718 return (length ($lineseq) ? "$lineseq;" : "");
1722 sub pp_scope { scopeop(0, @_); }
1723 sub pp_lineseq { scopeop(0, @_); }
1724 sub pp_leave { scopeop(1, @_); }
1726 # This is a special case of scopeop and lineseq, for the case of the
1727 # main_root. The difference is that we print the output statements as
1728 # soon as we get them, for the sake of impatient users.
1732 local(@$self{qw'curstash warnings hints hinthash'})
1733 = @$self{qw'curstash warnings hints hinthash'};
1735 return if null $op->first; # Can happen, e.g., for Bytecode without -k
1736 for (my $kid = $op->first->sibling; !null($kid); $kid = $kid->sibling) {
1739 $self->walk_lineseq($op, \@kids,
1740 sub { return unless length $_[0];
1741 print $self->indent($_[0].';');
1743 unless $_[1] == $#kids;
1748 my ($self, $op, $kids, $callback) = @_;
1750 for (my $i = 0; $i < @kids; $i++) {
1752 if (is_state $kids[$i]) {
1753 $expr = $self->deparse($kids[$i++], 0);
1755 $callback->($expr, $i);
1759 if (is_for_loop($kids[$i])) {
1760 $callback->($expr . $self->for_loop($kids[$i], 0),
1761 $i += $kids[$i]->sibling->name eq "unstack" ? 2 : 1);
1764 my $expr2 = $self->deparse($kids[$i], (@kids != 1)/2);
1765 $expr2 =~ s/^sub :(?!:)/+sub :/; # statement label otherwise
1767 $callback->($expr, $i);
1771 # The BEGIN {} is used here because otherwise this code isn't executed
1772 # when you run B::Deparse on itself.
1774 BEGIN { map($globalnames{$_}++, "SIG", "STDIN", "STDOUT", "STDERR", "INC",
1775 "ENV", "ARGV", "ARGVOUT", "_"); }
1781 #Carp::confess() unless ref($gv) eq "B::GV";
1782 my $cv = $gv->FLAGS & SVf_ROK ? $gv->RV : 0;
1783 my $stash = ($cv || $gv)->STASH->NAME;
1785 ? $cv ? $cv->NAME_HEK || $cv->GV->NAME : $gv->NAME
1787 ? B::safename($cv->NAME_HEK || $cv->GV->NAME)
1789 if ($stash eq 'main' && $name =~ /^::/) {
1792 elsif (($stash eq 'main'
1793 && ($globalnames{$name} || $name =~ /^[^A-Za-z_:]/))
1794 or ($stash eq $self->{'curstash'} && !$globalnames{$name}
1795 && ($stash eq 'main' || $name !~ /::/))
1800 $stash = $stash . "::";
1802 if (!$raw and $name =~ /^(\^..|{)/) {
1803 $name = "{$name}"; # ${^WARNING_BITS}, etc and ${
1805 return $stash . $name;
1808 # Return the name to use for a stash variable.
1809 # If a lexical with the same name is in scope, or
1810 # if strictures are enabled, it may need to be
1812 sub stash_variable {
1813 my ($self, $prefix, $name, $cx) = @_;
1815 return $prefix.$self->maybe_qualify($prefix, $name) if $name =~ /::/;
1817 unless ($prefix eq '$' || $prefix eq '@' || $prefix eq '&' || #'
1818 $prefix eq '%' || $prefix eq '$#') {
1819 return "$prefix$name";
1822 if ($name =~ /^[^[:alpha:]_+-]$/) {
1823 if (defined $cx && $cx == 26) {
1824 if ($prefix eq '@') {
1825 return "$prefix\{$name}";
1827 elsif ($name eq '#') { return '${#}' } # "${#}a" vs "$#a"
1829 if ($prefix eq '$#') {
1830 return "\$#{$name}";
1834 return $prefix . $self->maybe_qualify($prefix, $name);
1837 my %unctrl = # portable to EBCDIC
1839 "\c@" => '@', # unused
1866 "\c[" => '[', # unused
1867 "\c\\" => '\\', # unused
1868 "\c]" => ']', # unused
1869 "\c_" => '_', # unused
1872 # Return just the name, without the prefix. It may be returned as a quoted
1873 # string. The second return value is a boolean indicating that.
1874 sub stash_variable_name {
1875 my($self, $prefix, $gv) = @_;
1876 my $name = $self->gv_name($gv, 1);
1877 $name = $self->maybe_qualify($prefix,$name);
1878 if ($name =~ /^(?:\S|(?!\d)[\ca-\cz]?(?:\w|::)*|\d+)\z/) {
1879 $name =~ s/^([\ca-\cz])/'^' . $unctrl{$1}/e;
1880 $name =~ /^(\^..|{)/ and $name = "{$name}";
1881 return $name, 0; # not quoted
1884 single_delim("q", "'", $name, $self), 1;
1889 my ($self,$prefix,$name) = @_;
1890 my $v = ($prefix eq '$#' ? '@' : $prefix) . $name;
1891 if ($prefix eq "") {
1892 $name .= "::" if $name =~ /(?:\ACORE::[^:]*|::)\z/;
1895 return $name if $name =~ /::/;
1896 return $self->{'curstash'}.'::'. $name
1898 $name =~ /^(?!\d)\w/ # alphabetic
1899 && $v !~ /^\$[ab]\z/ # not $a or $b
1900 && $v =~ /\A[\$\@\%\&]/ # scalar, array, hash, or sub
1901 && !$globalnames{$name} # not a global name
1902 && $self->{hints} & $strict_bits{vars} # strict vars
1903 && !$self->lex_in_scope($v,1) # no "our"
1904 or $self->lex_in_scope($v); # conflicts with "my" variable
1909 my ($self, $name, $our) = @_;
1910 substr $name, 0, 0, = $our ? 'o' : 'm'; # our/my
1911 $self->populate_curcvlex() if !defined $self->{'curcvlex'};
1913 return 0 if !defined($self->{'curcop'});
1914 my $seq = $self->{'curcop'}->cop_seq;
1915 return 0 if !exists $self->{'curcvlex'}{$name};
1916 for my $a (@{$self->{'curcvlex'}{$name}}) {
1917 my ($st, $en) = @$a;
1918 return 1 if $seq > $st && $seq <= $en;
1923 sub populate_curcvlex {
1925 for (my $cv = $self->{'curcv'}; class($cv) eq "CV"; $cv = $cv->OUTSIDE) {
1926 my $padlist = $cv->PADLIST;
1927 # an undef CV still in lexical chain
1928 next if class($padlist) eq "SPECIAL";
1929 my @padlist = $padlist->ARRAY;
1930 my @ns = $padlist[0]->ARRAY;
1932 for (my $i=0; $i<@ns; ++$i) {
1933 next if class($ns[$i]) eq "SPECIAL";
1934 if (class($ns[$i]) eq "PV") {
1935 # Probably that pesky lexical @_
1938 my $name = $ns[$i]->PVX;
1939 next unless defined $name;
1940 my ($seq_st, $seq_en) =
1941 ($ns[$i]->FLAGS & SVf_FAKE)
1943 : ($ns[$i]->COP_SEQ_RANGE_LOW, $ns[$i]->COP_SEQ_RANGE_HIGH);
1945 push @{$self->{'curcvlex'}{
1946 ($ns[$i]->FLAGS & SVpad_OUR ? 'o' : 'm') . $name
1947 }}, [$seq_st, $seq_en, $ns[$i]];
1952 sub find_scope_st { ((find_scope(@_))[0]); }
1953 sub find_scope_en { ((find_scope(@_))[1]); }
1955 # Recurses down the tree, looking for pad variable introductions and COPs
1957 my ($self, $op, $scope_st, $scope_en) = @_;
1958 carp("Undefined op in find_scope") if !defined $op;
1959 return ($scope_st, $scope_en) unless $op->flags & OPf_KIDS;
1962 while(my $op = shift @queue ) {
1963 for (my $o=$op->first; $$o; $o=$o->sibling) {
1964 if ($o->name =~ /^pad.v$/ && $o->private & OPpLVAL_INTRO) {
1965 my $s = int($self->padname_sv($o->targ)->COP_SEQ_RANGE_LOW);
1966 my $e = $self->padname_sv($o->targ)->COP_SEQ_RANGE_HIGH;
1967 $scope_st = $s if !defined($scope_st) || $s < $scope_st;
1968 $scope_en = $e if !defined($scope_en) || $e > $scope_en;
1969 return ($scope_st, $scope_en);
1971 elsif (is_state($o)) {
1972 my $c = $o->cop_seq;
1973 $scope_st = $c if !defined($scope_st) || $c < $scope_st;
1974 $scope_en = $c if !defined($scope_en) || $c > $scope_en;
1975 return ($scope_st, $scope_en);
1977 elsif ($o->flags & OPf_KIDS) {
1978 unshift (@queue, $o);
1983 return ($scope_st, $scope_en);
1986 # Returns a list of subs which should be inserted before the COP
1988 my ($self, $op, $out_seq) = @_;
1989 my $seq = $op->cop_seq;
1990 $seq = $out_seq if defined($out_seq) && $out_seq < $seq;
1991 return $self->seq_subs($seq);
1995 my ($self, $seq) = @_;
1997 #push @text, "# ($seq)\n";
1999 return "" if !defined $seq;
2001 while (scalar(@{$self->{'subs_todo'}})
2002 and $seq > $self->{'subs_todo'}[0][0]) {
2003 my $cv = $self->{'subs_todo'}[0][1];
2004 # Skip the OUTSIDE check for lexical subs. We may be deparsing a
2005 # cloned anon sub with lexical subs declared in it, in which case
2006 # the OUTSIDE pointer points to the anon protosub.
2007 my $lexical = ref $self->{'subs_todo'}[0][3];
2008 my $outside = !$lexical && $cv && $cv->OUTSIDE;
2009 if (!$lexical and $cv
2010 and ${$cv->OUTSIDE || \0} != ${$self->{'curcv'}})
2012 push @pending, shift @{$self->{'subs_todo'}};
2015 push @text, $self->next_todo;
2017 unshift @{$self->{'subs_todo'}}, @pending;
2021 sub _features_from_bundle {
2022 my ($hints, $hh) = @_;
2023 foreach (@{$feature::feature_bundle{@feature::hint_bundles[$hints >> $feature::hint_shift]}}) {
2024 $hh->{$feature::feature{$_}} = 1;
2029 # generate any pragmas, 'package foo' etc needed to synchronise
2030 # with the given cop
2038 my $stash = $op->stashpv;
2039 if ($stash ne $self->{'curstash'}) {
2040 push @text, $self->keyword("package") . " $stash;\n";
2041 $self->{'curstash'} = $stash;
2044 if (OPpCONST_ARYBASE && $self->{'arybase'} != $op->arybase) {
2045 push @text, '$[ = '. $op->arybase .";\n";
2046 $self->{'arybase'} = $op->arybase;
2049 my $warnings = $op->warnings;
2051 if ($warnings->isa("B::SPECIAL") && $$warnings == 4) {
2052 $warning_bits = $warnings::Bits{"all"} & WARN_MASK;
2054 elsif ($warnings->isa("B::SPECIAL") && $$warnings == 5) {
2055 $warning_bits = $warnings::NONE;
2057 elsif ($warnings->isa("B::SPECIAL")) {
2058 $warning_bits = undef;
2061 $warning_bits = $warnings->PV & WARN_MASK;
2064 if (defined ($warning_bits) and
2065 !defined($self->{warnings}) || $self->{'warnings'} ne $warning_bits) {
2067 $self->declare_warnings($self->{'warnings'}, $warning_bits);
2068 $self->{'warnings'} = $warning_bits;
2071 my $hints = $op->hints;
2072 my $old_hints = $self->{'hints'};
2073 if ($self->{'hints'} != $hints) {
2074 push @text, $self->declare_hints($self->{'hints'}, $hints);
2075 $self->{'hints'} = $hints;
2079 $newhh = $op->hints_hash->HASH;
2082 # feature bundle hints
2083 my $from = $old_hints & $feature::hint_mask;
2084 my $to = $ hints & $feature::hint_mask;
2086 if ($to == $feature::hint_mask) {
2087 if ($self->{'hinthash'}) {
2088 delete $self->{'hinthash'}{$_}
2089 for grep /^feature_/, keys %{$self->{'hinthash'}};
2091 else { $self->{'hinthash'} = {} }
2093 = _features_from_bundle($from, $self->{'hinthash'});
2097 $feature::hint_bundles[$to >> $feature::hint_shift];
2098 $bundle =~ s/(\d[13579])\z/$1+1/e; # 5.11 => 5.12
2100 $self->keyword("no") . " feature ':all';\n",
2101 $self->keyword("use") . " feature ':$bundle';\n";
2107 push @text, $self->declare_hinthash(
2108 $self->{'hinthash'}, $newhh,
2109 $self->{indent_size}, $self->{hints},
2111 $self->{'hinthash'} = $newhh;
2114 return join("", @text);
2118 # Notice how subs and formats are inserted between statements here;
2119 # also $[ assignments and pragmas.
2123 $self->{'curcop'} = $op;
2127 my @subs = $self->cop_subs($op);
2129 # Special marker to swallow up the semicolon
2134 push @text, $self->pragmata($op);
2137 # This should go after of any branches that add statements, to
2138 # increase the chances that it refers to the same line it did in
2139 # the original program.
2140 if ($self->{'linenums'} && $cx != .5) { # $cx == .5 means in a format
2141 push @text, "\f#line " . $op->line .
2142 ' "' . $op->file, qq'"\n';
2145 push @text, $op->label . ": " if $op->label;
2147 return join("", @text);
2150 sub declare_warnings {
2151 my ($self, $from, $to) = @_;
2153 my $all = (warnings::bits("all") & WARN_MASK);
2154 unless ((($from & WARN_MASK) & ~$all) =~ /[^\0]/) {
2155 # no FATAL bits need turning off
2156 if ( ($to & WARN_MASK) eq $all) {
2157 return $self->keyword("use") . " warnings;\n";
2159 elsif (($to & WARN_MASK) eq ("\0"x length($to) & WARN_MASK)) {
2160 return $self->keyword("no") . " warnings;\n";
2164 return "BEGIN {\${^WARNING_BITS} = \""
2165 . join("", map { sprintf("\\x%02x", ord $_) } split "", $to)
2170 my ($self, $from, $to) = @_;
2171 my $use = $to & ~$from;
2172 my $no = $from & ~$to;
2174 for my $pragma (hint_pragmas($use)) {
2175 $decls .= $self->keyword("use") . " $pragma;\n";
2177 for my $pragma (hint_pragmas($no)) {
2178 $decls .= $self->keyword("no") . " $pragma;\n";
2183 # Internal implementation hints that the core sets automatically, so don't need
2184 # (or want) to be passed back to the user
2185 my %ignored_hints = (
2196 sub declare_hinthash {
2197 my ($self, $from, $to, $indent, $hints) = @_;
2198 my $doing_features =
2199 ($hints & $feature::hint_mask) == $feature::hint_mask;
2202 my @unfeatures; # bugs?
2203 for my $key (sort keys %$to) {
2204 next if $ignored_hints{$key};
2205 my $is_feature = $key =~ /^feature_/;
2206 next if $is_feature and not $doing_features;
2207 if (!exists $from->{$key} or $from->{$key} ne $to->{$key}) {
2208 push(@features, $key), next if $is_feature;
2210 qq(\$^H{) . single_delim("q", "'", $key, $self) . qq(} = )
2213 ? single_delim("q", "'", $to->{$key}, $self)
2219 for my $key (sort keys %$from) {
2220 next if $ignored_hints{$key};
2221 my $is_feature = $key =~ /^feature_/;
2222 next if $is_feature and not $doing_features;
2223 if (!exists $to->{$key}) {
2224 push(@unfeatures, $key), next if $is_feature;
2225 push @decls, qq(delete \$^H{'$key'};);
2229 if (@features || @unfeatures) {
2230 if (!%rev_feature) { %rev_feature = reverse %feature::feature }
2233 push @ret, $self->keyword("use") . " feature "
2234 . join(", ", map "'$rev_feature{$_}'", @features) . ";\n";
2237 push @ret, $self->keyword("no") . " feature "
2238 . join(", ", map "'$rev_feature{$_}'", @unfeatures)
2243 join("\n" . (" " x $indent), "BEGIN {", @decls) . "\n}\n\cK";
2249 my (@pragmas, @strict);
2250 push @pragmas, "integer" if $bits & 0x1;
2251 for (sort keys %strict_bits) {
2252 push @strict, "'$_'" if $bits & $strict_bits{$_};
2254 if (@strict == keys %strict_bits) {
2255 push @pragmas, "strict";
2258 push @pragmas, "strict " . join ', ', @strict;
2260 push @pragmas, "bytes" if $bits & 0x8;
2264 sub pp_dbstate { pp_nextstate(@_) }
2265 sub pp_setstate { pp_nextstate(@_) }
2267 sub pp_unstack { return "" } # see also leaveloop
2269 my %feature_keywords = (
2270 # keyword => 'feature',
2275 default => 'switch',
2277 evalbytes=>'evalbytes',
2278 __SUB__ => '__SUB__',
2282 # keywords that are strong and also have a prototype
2284 my %strong_proto_keywords = map { $_ => 1 } qw(
2292 sub feature_enabled {
2293 my($self,$name) = @_;
2295 my $hints = $self->{hints} & $feature::hint_mask;
2296 if ($hints && $hints != $feature::hint_mask) {
2297 $hh = _features_from_bundle($hints);
2299 elsif ($hints) { $hh = $self->{'hinthash'} }
2300 return $hh && $hh->{"feature_$feature_keywords{$name}"}
2306 return $name if $name =~ /^CORE::/; # just in case
2307 if (exists $feature_keywords{$name}) {
2308 return "CORE::$name" if not $self->feature_enabled($name);
2310 # This sub may be called for a program that has no nextstate ops. In
2311 # that case we may have a lexical sub named no/use/sub in scope but
2312 # but $self->lex_in_scope will return false because it depends on the
2313 # current nextstate op. So we need this alternate method if there is
2315 if (!$self->{'curcop'}) {
2316 $self->populate_curcvlex() if !defined $self->{'curcvlex'};
2317 return "CORE::$name" if exists $self->{'curcvlex'}{"m&$name"}
2318 || exists $self->{'curcvlex'}{"o&$name"};
2319 } elsif ($self->lex_in_scope("&$name")
2320 || $self->lex_in_scope("&$name", 1)) {
2321 return "CORE::$name";
2323 if ($strong_proto_keywords{$name}
2324 || ($name !~ /^(?:chom?p|do|exec|glob|s(?:elect|ystem))\z/
2325 && !defined eval{prototype "CORE::$name"})
2328 exists $self->{subs_declared}{$name}
2330 exists &{"$self->{curstash}::$name"}
2332 return "CORE::$name"
2339 my($op, $cx, $name) = @_;
2340 return $self->keyword($name);
2343 sub pp_stub { "()" }
2344 sub pp_wantarray { baseop(@_, "wantarray") }
2345 sub pp_fork { baseop(@_, "fork") }
2346 sub pp_wait { maybe_targmy(@_, \&baseop, "wait") }
2347 sub pp_getppid { maybe_targmy(@_, \&baseop, "getppid") }
2348 sub pp_time { maybe_targmy(@_, \&baseop, "time") }
2349 sub pp_tms { baseop(@_, "times") }
2350 sub pp_ghostent { baseop(@_, "gethostent") }
2351 sub pp_gnetent { baseop(@_, "getnetent") }
2352 sub pp_gprotoent { baseop(@_, "getprotoent") }
2353 sub pp_gservent { baseop(@_, "getservent") }
2354 sub pp_ehostent { baseop(@_, "endhostent") }
2355 sub pp_enetent { baseop(@_, "endnetent") }
2356 sub pp_eprotoent { baseop(@_, "endprotoent") }
2357 sub pp_eservent { baseop(@_, "endservent") }
2358 sub pp_gpwent { baseop(@_, "getpwent") }
2359 sub pp_spwent { baseop(@_, "setpwent") }
2360 sub pp_epwent { baseop(@_, "endpwent") }
2361 sub pp_ggrent { baseop(@_, "getgrent") }
2362 sub pp_sgrent { baseop(@_, "setgrent") }
2363 sub pp_egrent { baseop(@_, "endgrent") }
2364 sub pp_getlogin { baseop(@_, "getlogin") }
2366 sub POSTFIX () { 1 }
2368 # I couldn't think of a good short name, but this is the category of
2369 # symbolic unary operators with interesting precedence
2373 my($op, $cx, $name, $prec, $flags) = (@_, 0);
2374 my $kid = $op->first;
2375 $kid = $self->deparse($kid, $prec);
2376 return $self->maybe_parens(($flags & POSTFIX)
2378 # avoid confusion with filetests
2380 && $kid =~ /^[a-zA-Z](?!\w)/
2386 sub pp_preinc { pfixop(@_, "++", 23) }
2387 sub pp_predec { pfixop(@_, "--", 23) }
2388 sub pp_postinc { maybe_targmy(@_, \&pfixop, "++", 23, POSTFIX) }
2389 sub pp_postdec { maybe_targmy(@_, \&pfixop, "--", 23, POSTFIX) }
2390 sub pp_i_preinc { pfixop(@_, "++", 23) }
2391 sub pp_i_predec { pfixop(@_, "--", 23) }
2392 sub pp_i_postinc { maybe_targmy(@_, \&pfixop, "++", 23, POSTFIX) }
2393 sub pp_i_postdec { maybe_targmy(@_, \&pfixop, "--", 23, POSTFIX) }
2394 sub pp_complement { maybe_targmy(@_, \&pfixop, "~", 21) }
2395 *pp_ncomplement = *pp_complement;
2396 sub pp_scomplement { maybe_targmy(@_, \&pfixop, "~.", 21) }
2398 sub pp_negate { maybe_targmy(@_, \&real_negate) }
2402 if ($op->first->name =~ /^(i_)?negate$/) {
2404 $self->pfixop($op, $cx, "-", 21.5);
2406 $self->pfixop($op, $cx, "-", 21);
2409 sub pp_i_negate { pp_negate(@_) }
2415 $self->listop($op, $cx, "not", $op->first);
2417 $self->pfixop($op, $cx, "!", 21);
2423 my($op, $cx, $name, $nollafr) = @_;
2425 if ($op->flags & OPf_KIDS) {
2428 # this deals with 'boolkeys' right now
2429 return $self->deparse($kid,$cx);
2431 my $builtinname = $name;
2432 $builtinname =~ /^CORE::/ or $builtinname = "CORE::$name";
2433 if (defined prototype($builtinname)
2434 && $builtinname ne 'CORE::readline'
2435 && prototype($builtinname) =~ /^;?\*/
2436 && $kid->name eq "rv2gv") {
2441 if (($kid = $self->deparse($kid, 16)) !~ s/^\cS//) {
2442 # require foo() is a syntax error.
2443 $kid =~ /^(?!\d)\w/ and $kid = "($kid)";
2445 return $self->maybe_parens(
2446 $self->keyword($name) . " $kid", $cx, 16
2449 return $self->maybe_parens_unop($name, $kid, $cx);
2451 return $self->maybe_parens(
2452 $self->keyword($name) . ($op->flags & OPf_SPECIAL ? "()" : ""),
2458 sub pp_chop { maybe_targmy(@_, \&unop, "chop") }
2459 sub pp_chomp { maybe_targmy(@_, \&unop, "chomp") }
2460 sub pp_schop { maybe_targmy(@_, \&unop, "chop") }
2461 sub pp_schomp { maybe_targmy(@_, \&unop, "chomp") }
2462 sub pp_defined { unop(@_, "defined") }
2463 sub pp_undef { unop(@_, "undef") }
2464 sub pp_study { unop(@_, "study") }
2465 sub pp_ref { unop(@_, "ref") }
2466 sub pp_pos { maybe_local(@_, unop(@_, "pos")) }
2468 sub pp_sin { maybe_targmy(@_, \&unop, "sin") }
2469 sub pp_cos { maybe_targmy(@_, \&unop, "cos") }
2470 sub pp_rand { maybe_targmy(@_, \&unop, "rand") }
2471 sub pp_srand { unop(@_, "srand") }
2472 sub pp_exp { maybe_targmy(@_, \&unop, "exp") }
2473 sub pp_log { maybe_targmy(@_, \&unop, "log") }
2474 sub pp_sqrt { maybe_targmy(@_, \&unop, "sqrt") }
2475 sub pp_int { maybe_targmy(@_, \&unop, "int") }
2476 sub pp_hex { maybe_targmy(@_, \&unop, "hex") }
2477 sub pp_oct { maybe_targmy(@_, \&unop, "oct") }
2478 sub pp_abs { maybe_targmy(@_, \&unop, "abs") }
2480 sub pp_length { maybe_targmy(@_, \&unop, "length") }
2481 sub pp_ord { maybe_targmy(@_, \&unop, "ord") }
2482 sub pp_chr { maybe_targmy(@_, \&unop, "chr") }
2484 sub pp_each { unop(@_, "each") }
2485 sub pp_values { unop(@_, "values") }
2486 sub pp_keys { unop(@_, "keys") }
2487 { no strict 'refs'; *{"pp_r$_"} = *{"pp_$_"} for qw< keys each values >; }
2489 # no name because its an optimisation op that has no keyword
2492 sub pp_aeach { unop(@_, "each") }
2493 sub pp_avalues { unop(@_, "values") }
2494 sub pp_akeys { unop(@_, "keys") }
2495 sub pp_pop { unop(@_, "pop") }
2496 sub pp_shift { unop(@_, "shift") }
2498 sub pp_caller { unop(@_, "caller") }
2499 sub pp_reset { unop(@_, "reset") }
2500 sub pp_exit { unop(@_, "exit") }
2501 sub pp_prototype { unop(@_, "prototype") }
2503 sub pp_close { unop(@_, "close") }
2504 sub pp_fileno { unop(@_, "fileno") }
2505 sub pp_umask { unop(@_, "umask") }
2506 sub pp_untie { unop(@_, "untie") }
2507 sub pp_tied { unop(@_, "tied") }
2508 sub pp_dbmclose { unop(@_, "dbmclose") }
2509 sub pp_getc { unop(@_, "getc") }
2510 sub pp_eof { unop(@_, "eof") }
2511 sub pp_tell { unop(@_, "tell") }
2512 sub pp_getsockname { unop(@_, "getsockname") }
2513 sub pp_getpeername { unop(@_, "getpeername") }
2516 my ($self, $op, $cx) = @_;
2517 if (($op->flags & (OPf_SPECIAL|OPf_KIDS)) == (OPf_SPECIAL|OPf_KIDS)) {
2518 my $kw = $self->keyword("chdir");
2519 my $kid = $self->const_sv($op->first)->PV;
2521 . ($cx >= 16 || $self->{'parens'} ? "($kid)" : " $kid");
2522 maybe_targmy(@_, sub { $_[3] }, $code);
2524 maybe_targmy(@_, \&unop, "chdir")
2528 sub pp_chroot { maybe_targmy(@_, \&unop, "chroot") }
2529 sub pp_readlink { unop(@_, "readlink") }
2530 sub pp_rmdir { maybe_targmy(@_, \&unop, "rmdir") }
2531 sub pp_readdir { unop(@_, "readdir") }
2532 sub pp_telldir { unop(@_, "telldir") }
2533 sub pp_rewinddir { unop(@_, "rewinddir") }
2534 sub pp_closedir { unop(@_, "closedir") }
2535 sub pp_getpgrp { maybe_targmy(@_, \&unop, "getpgrp") }
2536 sub pp_localtime { unop(@_, "localtime") }
2537 sub pp_gmtime { unop(@_, "gmtime") }
2538 sub pp_alarm { unop(@_, "alarm") }
2539 sub pp_sleep { maybe_targmy(@_, \&unop, "sleep") }
2542 my $code = unop(@_, "do", 1); # llafr does not apply
2543 if ($code =~ s/^((?:CORE::)?do) \{/$1({/) { $code .= ')' }
2549 $_[1]->private & OPpEVAL_BYTES ? 'evalbytes' : "eval"
2553 sub pp_ghbyname { unop(@_, "gethostbyname") }
2554 sub pp_gnbyname { unop(@_, "getnetbyname") }
2555 sub pp_gpbyname { unop(@_, "getprotobyname") }
2556 sub pp_shostent { unop(@_, "sethostent") }
2557 sub pp_snetent { unop(@_, "setnetent") }
2558 sub pp_sprotoent { unop(@_, "setprotoent") }
2559 sub pp_sservent { unop(@_, "setservent") }
2560 sub pp_gpwnam { unop(@_, "getpwnam") }
2561 sub pp_gpwuid { unop(@_, "getpwuid") }
2562 sub pp_ggrnam { unop(@_, "getgrnam") }
2563 sub pp_ggrgid { unop(@_, "getgrgid") }
2565 sub pp_lock { unop(@_, "lock") }
2567 sub pp_continue { unop(@_, "continue"); }
2568 sub pp_break { unop(@_, "break"); }
2572 my($op, $cx, $givwhen) = @_;
2574 my $enterop = $op->first;
2576 if ($enterop->flags & OPf_SPECIAL) {
2577 $head = $self->keyword("default");
2578 $block = $self->deparse($enterop->first, 0);
2581 my $cond = $enterop->first;
2582 my $cond_str = $self->deparse($cond, 1);
2583 $head = "$givwhen ($cond_str)";
2584 $block = $self->deparse($cond->sibling, 0);
2592 sub pp_leavegiven { givwhen(@_, $_[0]->keyword("given")); }
2593 sub pp_leavewhen { givwhen(@_, $_[0]->keyword("when")); }
2599 my $name = $self->keyword("exists");
2600 if ($op->private & OPpEXISTS_SUB) {
2601 # Checking for the existence of a subroutine
2602 return $self->maybe_parens_func($name,
2603 $self->pp_rv2cv($op->first, 16), $cx, 16);
2605 if ($op->flags & OPf_SPECIAL) {
2606 # Array element, not hash element
2607 return $self->maybe_parens_func($name,
2608 $self->pp_aelem($op->first, 16), $cx, 16);
2610 return $self->maybe_parens_func($name, $self->pp_helem($op->first, 16),
2618 my $name = $self->keyword("delete");
2619 if ($op->private & (OPpSLICE|OPpKVSLICE)) {
2620 if ($op->flags & OPf_SPECIAL) {
2621 # Deleting from an array, not a hash
2622 return $self->maybe_parens_func($name,
2623 $self->pp_aslice($op->first, 16),
2626 return $self->maybe_parens_func($name,
2627 $self->pp_hslice($op->first, 16),
2630 if ($op->flags & OPf_SPECIAL) {
2631 # Deleting from an array, not a hash
2632 return $self->maybe_parens_func($name,
2633 $self->pp_aelem($op->first, 16),
2636 return $self->maybe_parens_func($name,
2637 $self->pp_helem($op->first, 16),
2645 my $opname = $op->flags & OPf_SPECIAL ? 'CORE::require' : 'require';
2646 my $kid = $op->first;
2647 if ($kid->name eq 'const') {
2648 my $priv = $kid->private;
2649 my $sv = $self->const_sv($kid);
2651 if ($priv & OPpCONST_BARE) {
2655 } elsif ($priv & OPpCONST_NOVER) {
2656 $opname = $self->keyword('no');
2657 $arg = $self->const($sv, 16);
2658 } elsif ((my $tmp = $self->const($sv, 16)) =~ /^v/) {
2662 return $self->maybe_parens("$opname $arg", $cx, 16);
2668 1, # llafr does not apply
2675 my $kid = $op->first;
2676 if (not null $kid->sibling) {
2677 # XXX Was a here-doc
2678 return $self->dquote($op);
2680 $self->unop(@_, "scalar");
2687 return $self->{'curcv'}->PADLIST->ARRAYelt(1)->ARRAYelt($targ);
2690 sub anon_hash_or_list {
2694 my($pre, $post) = @{{"anonlist" => ["[","]"],
2695 "anonhash" => ["{","}"]}->{$op->name}};
2697 $op = $op->first->sibling; # skip pushmark
2698 for (; !null($op); $op = $op->sibling) {
2699 $expr = $self->deparse($op, 6);
2702 if ($pre eq "{" and $cx < 1) {
2703 # Disambiguate that it's not a block
2706 return $pre . join(", ", @exprs) . $post;
2712 if ($op->flags & OPf_SPECIAL) {
2713 return $self->anon_hash_or_list($op, $cx);
2715 warn "Unexpected op pp_" . $op->name() . " without OPf_SPECIAL";
2719 *pp_anonhash = \&pp_anonlist;
2724 my $kid = $op->first;
2725 if ($kid->name eq "null") {
2726 my $anoncode = $kid = $kid->first;
2727 if ($anoncode->name eq "anonconst") {
2728 $anoncode = $anoncode->first->first->sibling;
2730 if ($anoncode->name eq "anoncode"
2731 or !null($anoncode = $kid->sibling) and
2732 $anoncode->name eq "anoncode") {
2733 return $self->e_anoncode({ code => $self->padval($anoncode->targ) });
2734 } elsif ($kid->name eq "pushmark") {
2735 my $sib_name = $kid->sibling->name;
2736 if ($sib_name eq 'entersub') {
2737 my $text = $self->deparse($kid->sibling, 1);
2738 # Always show parens for \(&func()), but only with -p otherwise
2739 $text = "($text)" if $self->{'parens'}
2740 or $kid->sibling->private & OPpENTERSUB_AMPER;
2745 local $self->{'in_refgen'} = 1;
2746 $self->pfixop($op, $cx, "\\", 20);
2750 my ($self, $info) = @_;
2751 my $text = $self->deparse_sub($info->{code});
2752 return $self->keyword("sub") . " $text";
2755 sub pp_srefgen { pp_refgen(@_) }
2760 my $kid = $op->first;
2762 and $op->flags & OPf_SPECIAL
2763 and $self->deparse($kid, 1) eq 'ARGV')
2767 return $self->unop($op, $cx, "readline");
2773 return "<" . $self->gv_name($self->gv_or_padgv($op)) . ">";
2776 # Unary operators that can occur as pseudo-listops inside double quotes
2779 my($op, $cx, $name, $prec, $flags) = (@_, 0, 0);
2781 if ($op->flags & OPf_KIDS) {
2783 # If there's more than one kid, the first is an ex-pushmark.
2784 $kid = $kid->sibling if not null $kid->sibling;
2785 return $self->maybe_parens_unop($name, $kid, $cx);
2787 return $name . ($op->flags & OPf_SPECIAL ? "()" : "");
2791 sub pp_ucfirst { dq_unop(@_, "ucfirst") }
2792 sub pp_lcfirst { dq_unop(@_, "lcfirst") }
2793 sub pp_uc { dq_unop(@_, "uc") }
2794 sub pp_lc { dq_unop(@_, "lc") }
2795 sub pp_quotemeta { maybe_targmy(@_, \&dq_unop, "quotemeta") }
2796 sub pp_fc { dq_unop(@_, "fc") }
2800 my ($op, $cx, $name) = @_;
2801 if (class($op) eq "PVOP") {
2802 $name .= " " . $op->pv;
2803 } elsif (class($op) eq "OP") {
2805 } elsif (class($op) eq "UNOP") {
2806 (my $kid = $self->deparse($op->first, 7)) =~ s/^\cS//;
2807 # last foo() is a syntax error.
2808 $kid =~ /^(?!\d)\w/ and $kid = "($kid)";
2811 return $self->maybe_parens($name, $cx, 7);
2814 sub pp_last { loopex(@_, "last") }
2815 sub pp_next { loopex(@_, "next") }
2816 sub pp_redo { loopex(@_, "redo") }
2817 sub pp_goto { loopex(@_, "goto") }
2818 sub pp_dump { loopex(@_, "CORE::dump") }
2822 my($op, $cx, $name) = @_;
2823 if (class($op) eq "UNOP") {
2824 # Genuine '-X' filetests are exempt from the LLAFR, but not
2826 if ($name =~ /^-/) {
2827 (my $kid = $self->deparse($op->first, 16)) =~ s/^\cS//;
2828 return $self->maybe_parens("$name $kid", $cx, 16);
2830 return $self->maybe_parens_unop($name, $op->first, $cx);
2831 } elsif (class($op) =~ /^(SV|PAD)OP$/) {
2832 return $self->maybe_parens_func($name, $self->pp_gv($op, 1), $cx, 16);
2833 } else { # I don't think baseop filetests ever survive ck_ftst, but...
2838 sub pp_lstat { ftst(@_, "lstat") }
2839 sub pp_stat { ftst(@_, "stat") }
2840 sub pp_ftrread { ftst(@_, "-R") }
2841 sub pp_ftrwrite { ftst(@_, "-W") }
2842 sub pp_ftrexec { ftst(@_, "-X") }
2843 sub pp_fteread { ftst(@_, "-r") }
2844 sub pp_ftewrite { ftst(@_, "-w") }
2845 sub pp_fteexec { ftst(@_, "-x") }
2846 sub pp_ftis { ftst(@_, "-e") }
2847 sub pp_fteowned { ftst(@_, "-O") }
2848 sub pp_ftrowned { ftst(@_, "-o") }
2849 sub pp_ftzero { ftst(@_, "-z") }
2850 sub pp_ftsize { ftst(@_, "-s") }
2851 sub pp_ftmtime { ftst(@_, "-M") }
2852 sub pp_ftatime { ftst(@_, "-A") }
2853 sub pp_ftctime { ftst(@_, "-C") }
2854 sub pp_ftsock { ftst(@_, "-S") }
2855 sub pp_ftchr { ftst(@_, "-c") }
2856 sub pp_ftblk { ftst(@_, "-b") }
2857 sub pp_ftfile { ftst(@_, "-f") }
2858 sub pp_ftdir { ftst(@_, "-d") }
2859 sub pp_ftpipe { ftst(@_, "-p") }
2860 sub pp_ftlink { ftst(@_, "-l") }
2861 sub pp_ftsuid { ftst(@_, "-u") }
2862 sub pp_ftsgid { ftst(@_, "-g") }
2863 sub pp_ftsvtx { ftst(@_, "-k") }
2864 sub pp_fttty { ftst(@_, "-t") }
2865 sub pp_fttext { ftst(@_, "-T") }
2866 sub pp_ftbinary { ftst(@_, "-B") }
2868 sub SWAP_CHILDREN () { 1 }
2869 sub ASSIGN () { 2 } # has OP= variant
2870 sub LIST_CONTEXT () { 4 } # Assignment is in list context
2876 my $name = $op->name;
2877 if ($name eq "concat" and $op->first->name eq "concat") {
2878 # avoid spurious '=' -- see comment in pp_concat
2881 if ($name eq "null" and class($op) eq "UNOP"
2882 and $op->first->name =~ /^(and|x?or)$/
2883 and null $op->first->sibling)
2885 # Like all conditional constructs, OP_ANDs and OP_ORs are topped
2886 # with a null that's used as the common end point of the two
2887 # flows of control. For precedence purposes, ignore it.
2888 # (COND_EXPRs have these too, but we don't bother with
2889 # their associativity).
2890 return assoc_class($op->first);
2892 return $name . ($op->flags & OPf_STACKED ? "=" : "");
2895 # Left associative operators, like '+', for which
2896 # $a + $b + $c is equivalent to ($a + $b) + $c
2899 %left = ('multiply' => 19, 'i_multiply' => 19,
2900 'divide' => 19, 'i_divide' => 19,
2901 'modulo' => 19, 'i_modulo' => 19,
2903 'add' => 18, 'i_add' => 18,
2904 'subtract' => 18, 'i_subtract' => 18,
2906 'left_shift' => 17, 'right_shift' => 17,
2907 'bit_and' => 13, 'nbit_and' => 13, 'sbit_and' => 13,
2908 'bit_or' => 12, 'bit_xor' => 12,
2909 'sbit_or' => 12, 'sbit_xor' => 12,
2910 'nbit_or' => 12, 'nbit_xor' => 12,
2912 'or' => 2, 'xor' => 2,
2916 sub deparse_binop_left {
2918 my($op, $left, $prec) = @_;
2919 if ($left{assoc_class($op)} && $left{assoc_class($left)}
2920 and $left{assoc_class($op)} == $left{assoc_class($left)})
2922 return $self->deparse($left, $prec - .00001);
2924 return $self->deparse($left, $prec);
2928 # Right associative operators, like '=', for which
2929 # $a = $b = $c is equivalent to $a = ($b = $c)
2932 %right = ('pow' => 22,
2933 'sassign=' => 7, 'aassign=' => 7,
2934 'multiply=' => 7, 'i_multiply=' => 7,
2935 'divide=' => 7, 'i_divide=' => 7,
2936 'modulo=' => 7, 'i_modulo=' => 7,
2937 'repeat=' => 7, 'refassign' => 7, 'refassign=' => 7,
2938 'add=' => 7, 'i_add=' => 7,
2939 'subtract=' => 7, 'i_subtract=' => 7,
2941 'left_shift=' => 7, 'right_shift=' => 7,
2942 'bit_and=' => 7, 'sbit_and=' => 7, 'nbit_and=' => 7,
2943 'nbit_or=' => 7, 'nbit_xor=' => 7,
2944 'sbit_or=' => 7, 'sbit_xor=' => 7,
2950 sub deparse_binop_right {
2952 my($op, $right, $prec) = @_;
2953 if ($right{assoc_class($op)} && $right{assoc_class($right)}
2954 and $right{assoc_class($op)} == $right{assoc_class($right)})
2956 return $self->deparse($right, $prec - .00001);
2958 return $self->deparse($right, $prec);
2964 my ($op, $cx, $opname, $prec, $flags) = (@_, 0);
2965 my $left = $op->first;
2966 my $right = $op->last;
2968 if ($op->flags & OPf_STACKED && $flags & ASSIGN) {
2972 if ($flags & SWAP_CHILDREN) {
2973 ($left, $right) = ($right, $left);
2976 $left = $self->deparse_binop_left($op, $left, $prec);
2977 $left = "($left)" if $flags & LIST_CONTEXT
2978 and $left !~ /^(my|our|local|state|)\s*[\@%\(]/
2980 # Parenthesize if the left argument is a
2982 my $left = $leftop->first->sibling;
2983 $left->name eq 'repeat'
2984 && null($left->sibling);
2986 $right = $self->deparse_binop_right($op, $right, $prec);
2987 return $self->maybe_parens("$left $opname$eq $right", $cx, $prec);
2990 sub pp_add { maybe_targmy(@_, \&binop, "+", 18, ASSIGN) }
2991 sub pp_multiply { maybe_targmy(@_, \&binop, "*", 19, ASSIGN) }
2992 sub pp_subtract { maybe_targmy(@_, \&binop, "-",18, ASSIGN) }
2993 sub pp_divide { maybe_targmy(@_, \&binop, "/", 19, ASSIGN) }
2994 sub pp_modulo { maybe_targmy(@_, \&binop, "%", 19, ASSIGN) }
2995 sub pp_i_add { maybe_targmy(@_, \&binop, "+", 18, ASSIGN) }
2996 sub pp_i_multiply { maybe_targmy(@_, \&binop, "*", 19, ASSIGN) }
2997 sub pp_i_subtract { maybe_targmy(@_, \&binop, "-", 18, ASSIGN) }
2998 sub pp_i_divide { maybe_targmy(@_, \&binop, "/", 19, ASSIGN) }
2999 sub pp_i_modulo { maybe_targmy(@_, \&binop, "%", 19, ASSIGN) }
3000 sub pp_pow { maybe_targmy(@_, \&binop, "**", 22, ASSIGN) }
3002 sub pp_left_shift { maybe_targmy(@_, \&binop, "<<", 17, ASSIGN) }
3003 sub pp_right_shift { maybe_targmy(@_, \&binop, ">>", 17, ASSIGN) }
3004 sub pp_bit_and { maybe_targmy(@_, \&binop, "&", 13, ASSIGN) }
3005 sub pp_bit_or { maybe_targmy(@_, \&binop, "|", 12, ASSIGN) }
3006 sub pp_bit_xor { maybe_targmy(@_, \&binop, "^", 12, ASSIGN) }
3007 *pp_nbit_and = *pp_bit_and;
3008 *pp_nbit_or = *pp_bit_or;
3009 *pp_nbit_xor = *pp_bit_xor;
3010 sub pp_sbit_and { maybe_targmy(@_, \&binop, "&.", 13, ASSIGN) }
3011 sub pp_sbit_or { maybe_targmy(@_, \&binop, "|.", 12, ASSIGN) }
3012 sub pp_sbit_xor { maybe_targmy(@_, \&binop, "^.", 12, ASSIGN) }
3014 sub pp_eq { binop(@_, "==", 14) }
3015 sub pp_ne { binop(@_, "!=", 14) }
3016 sub pp_lt { binop(@_, "<", 15) }
3017 sub pp_gt { binop(@_, ">", 15) }
3018 sub pp_ge { binop(@_, ">=", 15) }
3019 sub pp_le { binop(@_, "<=", 15) }
3020 sub pp_ncmp { binop(@_, "<=>", 14) }
3021 sub pp_i_eq { binop(@_, "==", 14) }
3022 sub pp_i_ne { binop(@_, "!=", 14) }
3023 sub pp_i_lt { binop(@_, "<", 15) }
3024 sub pp_i_gt { binop(@_, ">", 15) }
3025 sub pp_i_ge { binop(@_, ">=", 15) }
3026 sub pp_i_le { binop(@_, "<=", 15) }
3027 sub pp_i_ncmp { maybe_targmy(@_, \&binop, "<=>", 14) }
3029 sub pp_seq { binop(@_, "eq", 14) }
3030 sub pp_sne { binop(@_, "ne", 14) }
3031 sub pp_slt { binop(@_, "lt", 15) }
3032 sub pp_sgt { binop(@_, "gt", 15) }
3033 sub pp_sge { binop(@_, "ge", 15) }
3034 sub pp_sle { binop(@_, "le", 15) }
3035 sub pp_scmp { maybe_targmy(@_, \&binop, "cmp", 14) }
3037 sub pp_sassign { binop(@_, "=", 7, SWAP_CHILDREN) }
3038 sub pp_aassign { binop(@_, "=", 7, SWAP_CHILDREN | LIST_CONTEXT) }
3041 my ($self, $op, $cx) = @_;
3042 if (($op->flags & OPf_SPECIAL) && $self->{expand} < 2) {
3043 return $self->deparse($op->last, $cx);
3046 binop(@_, "~~", 14);
3050 # '.' is special because concats-of-concats are optimized to save copying
3051 # by making all but the first concat stacked. The effect is as if the
3052 # programmer had written '($a . $b) .= $c', except legal.
3053 sub pp_concat { maybe_targmy(@_, \&real_concat) }
3057 my $left = $op->first;
3058 my $right = $op->last;
3061 if (($op->flags & OPf_STACKED) and !($op->private & OPpCONCAT_NESTED)) {
3062 # '.=' rather than optimised '.'
3066 $left = $self->deparse_binop_left($op, $left, $prec);
3067 $right = $self->deparse_binop_right($op, $right, $prec);
3068 return $self->maybe_parens("$left .$eq $right", $cx, $prec);
3071 sub pp_repeat { maybe_targmy(@_, \&repeat) }
3073 # 'x' is weird when the left arg is a list
3077 my $left = $op->first;
3078 my $right = $op->last;
3081 if ($op->flags & OPf_STACKED) {
3085 if (null($right)) { # list repeat; count is inside left-side ex-list
3086 # in 5.21.5 and earlier
3087 my $kid = $left->first->sibling; # skip pushmark
3089 for (; !null($kid->sibling); $kid = $kid->sibling) {
3090 push @exprs, $self->deparse($kid, 6);
3093 $left = "(" . join(", ", @exprs). ")";
3095 my $dolist = $op->private & OPpREPEAT_DOLIST;
3096 $left = $self->deparse_binop_left($op, $left, $dolist ? 1 : $prec);
3101 $right = $self->deparse_binop_right($op, $right, $prec);
3102 return $self->maybe_parens("$left x$eq $right", $cx, $prec);
3107 my ($op, $cx, $type) = @_;
3108 my $left = $op->first;
3109 my $right = $left->sibling;
3110 $left = $self->deparse($left, 9);
3111 $right = $self->deparse($right, 9);
3112 return $self->maybe_parens("$left $type $right", $cx, 9);
3118 my $flip = $op->first;
3119 my $type = ($flip->flags & OPf_SPECIAL) ? "..." : "..";
3120 return $self->range($flip->first, $cx, $type);
3123 # one-line while/until is handled in pp_leave
3127 my ($op, $cx, $lowop, $lowprec, $highop, $highprec, $blockname) = @_;
3128 my $left = $op->first;
3129 my $right = $op->first->sibling;
3130 $blockname &&= $self->keyword($blockname);
3131 if ($cx < 1 and is_scope($right) and $blockname
3132 and $self->{'expand'} < 7)
3134 $left = $self->deparse($left, 1);
3135 $right = $self->deparse($right, 0);
3136 return "$blockname ($left) {\n\t$right\n\b}\cK";
3137 } elsif ($cx < 1 and $blockname and not $self->{'parens'}
3138 and $self->{'expand'} < 7) { # $b if $a
3139 $right = $self->deparse($right, 1);
3140 $left = $self->deparse($left, 1);
3141 return "$right $blockname $left";
3142 } elsif ($cx > $lowprec and $highop) { # $a && $b
3143 $left = $self->deparse_binop_left($op, $left, $highprec);
3144 $right = $self->deparse_binop_right($op, $right, $highprec);
3145 return $self->maybe_parens("$left $highop $right", $cx, $highprec);
3146 } else { # $a and $b
3147 $left = $self->deparse_binop_left($op, $left, $lowprec);
3148 $right = $self->deparse_binop_right($op, $right, $lowprec);
3149 return $self->maybe_parens("$left $lowop $right", $cx, $lowprec);
3153 sub pp_and { logop(@_, "and", 3, "&&", 11, "if") }
3154 sub pp_or { logop(@_, "or", 2, "||", 10, "unless") }
3155 sub pp_dor { logop(@_, "//", 10) }
3157 # xor is syntactically a logop, but it's really a binop (contrary to
3158 # old versions of opcode.pl). Syntax is what matters here.
3159 sub pp_xor { logop(@_, "xor", 2, "", 0, "") }
3163 my ($op, $cx, $opname) = @_;
3164 my $left = $op->first;
3165 my $right = $op->first->sibling->first; # skip sassign
3166 $left = $self->deparse($left, 7);
3167 $right = $self->deparse($right, 7);
3168 return $self->maybe_parens("$left $opname $right", $cx, 7);
3171 sub pp_andassign { logassignop(@_, "&&=") }
3172 sub pp_orassign { logassignop(@_, "||=") }
3173 sub pp_dorassign { logassignop(@_, "//=") }
3175 sub rv2gv_or_string {
3177 if ($op->name eq "gv") { # could be open("open") or open("###")
3179 $self->stash_variable_name("", $self->gv_or_padgv($op));
3180 $quoted ? $name : "*$name";
3183 $self->deparse($op, 6);
3189 my($op, $cx, $name, $kid, $nollafr) = @_;
3191 my $parens = ($cx >= 5) || $self->{'parens'};
3192 $kid ||= $op->first->sibling;
3193 # If there are no arguments, add final parentheses (or parenthesize the
3194 # whole thing if the llafr does not apply) to account for cases like
3195 # (return)+1 or setpgrp()+1. When the llafr does not apply, we use a
3196 # precedence of 6 (< comma), as "return, 1" does not need parentheses.
3199 ? $self->maybe_parens($self->keyword($name), $cx, 7)
3200 : $self->keyword($name) . '()' x (7 < $cx);
3203 my $fullname = $self->keyword($name);
3204 my $proto = prototype("CORE::$name");
3206 ( (defined $proto && $proto =~ /^;?\*/)
3207 || $name eq 'select' # select(F) doesn't have a proto
3209 && $kid->name eq "rv2gv"
3210 && !($kid->private & OPpLVAL_INTRO)
3212 $first = $self->rv2gv_or_string($kid->first);
3215 $first = $self->deparse($kid, 6);
3217 if ($name eq "chmod" && $first =~ /^\d+$/) {
3218 $first = sprintf("%#o", $first);
3221 if not $parens and not $nollafr and substr($first, 0, 1) eq "(";
3222 push @exprs, $first;
3223 $kid = $kid->sibling;
3224 if (defined $proto && $proto =~ /^\*\*/ && $kid->name eq "rv2gv"
3225 && !($kid->private & OPpLVAL_INTRO)) {
3226 push @exprs, $first = $self->rv2gv_or_string($kid->first);
3227 $kid = $kid->sibling;
3229 for (; !null($kid); $kid = $kid->sibling) {
3230 push @exprs, $self->deparse($kid, 6);
3232 if ($name eq "reverse" && ($op->private & OPpREVERSE_INPLACE)) {
3233 return "$exprs[0] = $fullname"
3234 . ($parens ? "($exprs[0])" : " $exprs[0]");
3237 if ($parens && $nollafr) {
3238 return "($fullname " . join(", ", @exprs) . ")";
3240 return "$fullname(" . join(", ", @exprs) . ")";
3242 return "$fullname " . join(", ", @exprs);
3246 sub pp_bless { listop(@_, "bless") }
3247 sub pp_atan2 { maybe_targmy(@_, \&listop, "atan2") }
3249 my ($self,$op,$cx) = @_;
3250 if ($op->private & OPpSUBSTR_REPL_FIRST) {
3252 listop($self, $op, 7, "substr", $op->first->sibling->sibling)
3254 . $self->deparse($op->first->sibling, 7);
3256 maybe_local(@_, listop(@_, "substr"))
3260 # Also handles pp_rindex.
3262 # The body of this function includes an unrolled maybe_targmy(),
3263 # since the two parts of that sub's actions need to have have the
3264 # '== -1' bit in between
3266 my($self, $op, $cx) = @_;
3268 my $lex = ($op->private & OPpTARGET_MY);
3269 my $bool = ($op->private & OPpTRUEBOOL);
3271 my $val = $self->listop($op, ($bool ? 14 : $lex ? 7 : $cx), $op->name);
3273 # (index() == -1) has op_eq and op_const optimised away
3275 $val .= ($op->private & OPpINDEX_BOOLNEG) ? " == -1" : " != -1";
3276 $val = "($val)" if ($op->flags & OPf_PARENS);
3279 my $var = $self->padname($op->targ);
3280 $val = $self->maybe_parens("$var = $val", $cx, 7);
3285 sub pp_rindex { pp_index(@_); }
3286 sub pp_vec { maybe_targmy(@_, \&maybe_local, listop(@_, "vec")) }
3287 sub pp_sprintf { maybe_targmy(@_, \&listop, "sprintf") }
3288 sub pp_formline { listop(@_, "formline") } # see also deparse_format
3289 sub pp_crypt { maybe_targmy(@_, \&listop, "crypt") }
3290 sub pp_unpack { listop(@_, "unpack") }
3291 sub pp_pack { listop(@_, "pack") }
3292 sub pp_join { maybe_targmy(@_, \&listop, "join") }
3293 sub pp_splice { listop(@_, "splice") }
3294 sub pp_push { maybe_targmy(@_, \&listop, "push") }
3295 sub pp_unshift { maybe_targmy(@_, \&listop, "unshift") }
3296 sub pp_reverse { listop(@_, "reverse") }
3297 sub pp_warn { listop(@_, "warn") }
3298 sub pp_die { listop(@_, "die") }
3299 sub pp_return { listop(@_, "return", undef, 1) } # llafr does not apply
3300 sub pp_open { listop(@_, "open") }
3301 sub pp_pipe_op { listop(@_, "pipe") }
3302 sub pp_tie { listop(@_, "tie") }
3303 sub pp_binmode { listop(@_, "binmode") }
3304 sub pp_dbmopen { listop(@_, "dbmopen") }
3305 sub pp_sselect { listop(@_, "select") }
3306 sub pp_select { listop(@_, "select") }
3307 sub pp_read { listop(@_, "read") }
3308 sub pp_sysopen { listop(@_, "sysopen") }
3309 sub pp_sysseek { listop(@_, "sysseek") }
3310 sub pp_sysread { listop(@_, "sysread") }
3311 sub pp_syswrite { listop(@_, "syswrite") }
3312 sub pp_send { listop(@_, "send") }
3313 sub pp_recv { listop(@_, "recv") }
3314 sub pp_seek { listop(@_, "seek") }
3315 sub pp_fcntl { listop(@_, "fcntl") }
3316 sub pp_ioctl { listop(@_, "ioctl") }
3317 sub pp_flock { maybe_targmy(@_, \&listop, "flock") }
3318 sub pp_socket { listop(@_, "socket") }
3319 sub pp_sockpair { listop(@_, "socketpair") }
3320 sub pp_bind { listop(@_, "bind") }
3321 sub pp_connect { listop(@_, "connect") }
3322 sub pp_listen { listop(@_, "listen") }
3323 sub pp_accept { listop(@_, "accept") }
3324 sub pp_shutdown { listop(@_, "shutdown") }
3325 sub pp_gsockopt { listop(@_, "getsockopt") }
3326 sub pp_ssockopt { listop(@_, "setsockopt") }
3327 sub pp_chown { maybe_targmy(@_, \&listop, "chown") }
3328 sub pp_unlink { maybe_targmy(@_, \&listop, "unlink") }
3329 sub pp_chmod { maybe_targmy(@_, \&listop, "chmod") }
3330 sub pp_utime { maybe_targmy(@_, \&listop, "utime") }
3331 sub pp_rename { maybe_targmy(@_, \&listop, "rename") }
3332 sub pp_link { maybe_targmy(@_, \&listop, "link") }
3333 sub pp_symlink { maybe_targmy(@_, \&listop, "symlink") }
3334 sub pp_mkdir { maybe_targmy(@_, \&listop, "mkdir") }
3335 sub pp_open_dir { listop(@_, "opendir") }
3336 sub pp_seekdir { listop(@_, "seekdir") }
3337 sub pp_waitpid { maybe_targmy(@_, \&listop, "waitpid") }
3338 sub pp_system { maybe_targmy(@_, \&indirop, "system") }
3339 sub pp_exec { maybe_targmy(@_, \&indirop, "exec") }
3340 sub pp_kill { maybe_targmy(@_, \&listop, "kill") }
3341 sub pp_setpgrp { maybe_targmy(@_, \&listop, "setpgrp") }
3342 sub pp_getpriority { maybe_targmy(@_, \&listop, "getpriority") }
3343 sub pp_setpriority { maybe_targmy(@_, \&listop, "setpriority") }
3344 sub pp_shmget { listop(@_, "shmget") }
3345 sub pp_shmctl { listop(@_, "shmctl") }
3346 sub pp_shmread { listop(@_, "shmread") }
3347 sub pp_shmwrite { listop(@_, "shmwrite") }
3348 sub pp_msgget { listop(@_, "msgget") }
3349 sub pp_msgctl { listop(@_, "msgctl") }
3350 sub pp_msgsnd { listop(@_, "msgsnd") }
3351 sub pp_msgrcv { listop(@_, "msgrcv") }
3352 sub pp_semget { listop(@_, "semget") }
3353 sub pp_semctl { listop(@_, "semctl") }
3354 sub pp_semop { listop(@_, "semop") }
3355 sub pp_ghbyaddr { listop(@_, "gethostbyaddr") }
3356 sub pp_gnbyaddr { listop(@_, "getnetbyaddr") }
3357 sub pp_gpbynumber { listop(@_, "getprotobynumber") }
3358 sub pp_gsbyname { listop(@_, "getservbyname") }
3359 sub pp_gsbyport { listop(@_, "getservbyport") }
3360 sub pp_syscall { listop(@_, "syscall") }
3365 my $kid = $op->first->sibling; # skip pushmark
3367 $op->flags & OPf_SPECIAL ? 'glob' : $self->keyword('glob');
3368 my $text = $self->deparse($kid);
3369 return $cx >= 5 || $self->{'parens'}
3374 # Truncate is special because OPf_SPECIAL makes a bareword first arg
3375 # be a filehandle. This could probably be better fixed in the core
3376 # by moving the GV lookup into ck_truc.
3382 my $parens = ($cx >= 5) || $self->{'parens'};
3383 my $kid = $op->first->sibling;
3385 if ($op->flags & OPf_SPECIAL) {
3386 # $kid is an OP_CONST
3387 $fh = $self->const_sv($kid)->PV;
3389 $fh = $self->deparse($kid, 6);
3390 $fh = "+$fh" if not $parens and substr($fh, 0, 1) eq "(";
3392 my $len = $self->deparse($kid->sibling, 6);
3393 my $name = $self->keyword('truncate');
3395 return "$name($fh, $len)";
3397 return "$name $fh, $len";
3403 my($op, $cx, $name) = @_;
3405 my $firstkid = my $kid = $op->first->sibling;
3407 if ($op->flags & OPf_STACKED) {
3409 $indir = $indir->first; # skip rv2gv
3410 if (is_scope($indir)) {
3411 $indir = "{" . $self->deparse($indir, 0) . "}";
3412 $indir = "{;}" if $indir eq "{}";
3413 } elsif ($indir->name eq "const" && $indir->private & OPpCONST_BARE) {
3414 $indir = $self->const_sv($indir)->PV;
3416 $indir = $self->deparse($indir, 24);
3418 $indir = $indir . " ";
3419 $kid = $kid->sibling;
3421 if ($name eq "sort" && $op->private & (OPpSORT_NUMERIC | OPpSORT_INTEGER)) {
3422 $indir = ($op->private & OPpSORT_DESCEND) ? '{$b <=> $a} '
3425 elsif ($name eq "sort" && $op->private & OPpSORT_DESCEND) {
3426 $indir = '{$b cmp $a} ';
3428 for (; !null($kid); $kid = $kid->sibling) {
3429 $expr = $self->deparse($kid, !$indir && $kid == $firstkid && $name eq "sort" && $firstkid->name eq "entersub" ? 16 : 6);
3433 if ($name eq "sort" && $op->private & OPpSORT_REVERSE) {
3434 $name2 = $self->keyword('reverse') . ' ' . $self->keyword('sort');
3436 else { $name2 = $self->keyword($name) }
3437 if ($name eq "sort" && ($op->private & OPpSORT_INPLACE)) {
3438 return "$exprs[0] = $name2 $indir $exprs[0]";
3441 my $args = $indir . join(", ", @exprs);
3442 if ($indir ne "" && $name eq "sort") {
3443 # We don't want to say "sort(f 1, 2, 3)", since perl -w will
3444 # give bareword warnings in that case. Therefore if context
3445 # requires, we'll put parens around the outside "(sort f 1, 2,
3446 # 3)". Unfortunately, we'll currently think the parens are
3447 # necessary more often that they really are, because we don't
3448 # distinguish which side of an assignment we're on.
3450 return "($name2 $args)";
3452 return "$name2 $args";
3455 !$indir && $name eq "sort"
3456 && !null($op->first->sibling)
3457 && $op->first->sibling->name eq 'entersub'
3459 # We cannot say sort foo(bar), as foo will be interpreted as a
3460 # comparison routine. We have to say sort(...) in that case.
3461 return "$name2($args)";
3464 ? $self->maybe_parens_func($name2, $args, $cx, 5)
3465 : $name2 . '()' x (7 < $cx);
3470 sub pp_prtf { indirop(@_, "printf") }
3471 sub pp_print { indirop(@_, "print") }
3472 sub pp_say { indirop(@_, "say") }
3473 sub pp_sort { indirop(@_, "sort") }
3477 my($op, $cx, $name) = @_;
3479 my $kid = $op->first; # this is the (map|grep)start
3480 $kid = $kid->first->sibling; # skip a pushmark
3481 my $code = $kid->first; # skip a null
3482 if (is_scope $code) {
3483 $code = "{" . $self->deparse($code, 0) . "} ";
3485 $code = $self->deparse($code, 24);
3486 $code .= ", " if !null($kid->sibling);
3488 $kid = $kid->sibling;
3489 for (; !null($kid); $kid = $kid->sibling) {
3490 $expr = $self->deparse($kid, 6);
3491 push @exprs, $expr if defined $expr;
3493 return $self->maybe_parens_func($self->keyword($name),
3494 $code . join(", ", @exprs), $cx, 5);
3497 sub pp_mapwhile { mapop(@_, "map") }
3498 sub pp_grepwhile { mapop(@_, "grep") }
3499 sub pp_mapstart { baseop(@_, "map") }
3500 sub pp_grepstart { baseop(@_, "grep") }
3505 eval { require B::Op_private }
3506 ? @{$B::Op_private::ops_using{OPpLVAL_INTRO}}
3507 : qw(gvsv rv2sv rv2hv rv2gv rv2av aelem helem aslice
3508 hslice delete padsv padav padhv enteriter entersub padrange
3509 pushmark cond_expr refassign list)
3511 delete @uses_intro{qw( lvref lvrefslice lvavref entersub )};
3515 # Look for a my/state attribute declaration in a list or ex-list.
3516 # Returns undef if not found, 'my($x, @a) :Foo(bar)' etc otherwise.
3518 # There are three basic tree structs that are expected:
3521 # <1> ex-list vK/LVINTRO ->c
3522 # <0> ex-pushmark v ->3
3523 # <1> entersub[t2] vKRS*/TARG ->b
3525 # <0> padsv[$x:64,65] vM/LVINTRO ->c
3530 # <1> ex-list vK ->c
3531 # <0> ex-pushmark v ->3
3532 # <0> padav[@a:64,65] vM/LVINTRO ->4
3533 # <1> entersub[t2] vKRS*/TARG ->c
3536 # my ($x,@a,%h) :foo;
3538 # <;> nextstate(main 64 -e:1) v:{ ->3
3540 # <0> pushmark vM/LVINTRO ->4
3541 # <0> padsv[$x:64,65] vM/LVINTRO ->5
3542 # <0> padav[@a:64,65] vM/LVINTRO ->6
3543 # <0> padhv[%h:64,65] vM/LVINTRO ->7
3544 # <1> entersub[t4] vKRS*/TARG ->f
3546 # <1> entersub[t5] vKRS*/TARG ->n
3548 # <1> entersub[t6] vKRS*/TARG ->v
3550 # where the entersub in all cases looks like
3551 # <1> entersub[t2] vKRS*/TARG ->c
3552 # <0> pushmark s ->5
3553 # <$> const[PV "attributes"] sM ->6
3554 # <$> const[PV "main"] sM ->7
3555 # <1> srefgen sKM/1 ->9
3556 # <1> ex-list lKRM ->8
3557 # <0> padsv[@a:64,65] sRM ->8
3558 # <$> const[PV "foo"] sM ->a
3559 # <.> method_named[PV "import"] ->b
3561 sub maybe_var_attr {
3562 my ($self, $op, $cx) = @_;
3564 my $kid = $op->first->sibling; # skip pushmark
3565 return if class($kid) eq 'NULL';
3570 # Extract out all the pad ops and entersub ops into
3571 # @padops and @entersubops. Return if anything else seen.
3572 # Also determine what class (if any) all the pad vars belong to
3574 my $decl; # 'my' or 'state'
3575 my (@padops, @entersubops);
3576 for ($lop = $kid; !null($lop); $lop = $lop->sibling) {
3577 my $lopname = $lop->name;
3578 my $loppriv = $lop->private;
3579 if ($lopname =~ /^pad[sah]v$/) {
3580 return unless $loppriv & OPpLVAL_INTRO;
3582 my $padname = $self->padname_sv($lop->targ);
3583 my $thisclass = ($padname->FLAGS & SVpad_TYPED)
3584 ? $padname->SvSTASH->NAME : 'main';
3586 # all pad vars must be in the same class
3587 $class //= $thisclass;
3588 return unless $thisclass eq $class;
3590 # all pad vars must be the same sort of declaration
3591 # (all my, all state, etc)
3592 my $this = ($loppriv & OPpPAD_STATE) ? 'state' : 'my';
3593 if (defined $decl) {
3594 return unless $this eq $decl;
3600 elsif ($lopname eq 'entersub') {
3601 push @entersubops, $lop;
3608 return unless @padops && @padops == @entersubops;
3610 # there should be a balance: each padop has a corresponding
3611 # 'attributes'->import() method call, in the same order.
3616 for my $i (0..$#padops) {
3617 my $padop = $padops[$i];
3618 my $esop = $entersubops[$i];
3620 push @varnames, $self->padname($padop->targ);
3622 return unless ($esop->flags & OPf_KIDS);
3624 my $kid = $esop->first;
3625 return unless $kid->type == OP_PUSHMARK;
3627 $kid = $kid->sibling;
3628 return unless $$kid && $kid->type == OP_CONST;
3629 return unless $self->const_sv($kid)->PV eq 'attributes';
3631 $kid = $kid->sibling;
3632 return unless $$kid && $kid->type == OP_CONST; # __PACKAGE__
3634 $kid = $kid->sibling;
3636 && $kid->name eq "srefgen"
3637 && ($kid->flags & OPf_KIDS)
3638 && ($kid->first->flags & OPf_KIDS)
3639 && $kid->first->first->name =~ /^pad[sah]v$/
3640 && $kid->first->first->targ == $padop->targ;
3642 $kid = $kid->sibling;
3645 last if ($kid->type != OP_CONST);
3646 push @attr, $self->const_sv($kid)->PV;
3647 $kid = $kid->sibling;
3649 return unless @attr;
3650 my $thisattr = ":" . join(' ', @attr);
3651 $attr_text //= $thisattr;
3652 # all import calls must have the same list of attributes
3653 return unless $attr_text eq $thisattr;
3655 return unless $kid->name eq 'method_named';
3656 return unless $self->meth_sv($kid)->PV eq 'import';
3658 $kid = $kid->sibling;
3663 $res .= " $class " if $class ne 'main';
3666 ? "(" . join(', ', @varnames) . ')'
3669 return "$res $attr_text";
3678 # might be my ($s,@a,%h) :Foo(bar);
3679 my $my_attr = maybe_var_attr($self, $op, $cx);
3680 return $my_attr if defined $my_attr;
3684 my $kid = $op->first->sibling; # skip pushmark
3685 return '' if class($kid) eq 'NULL';
3687 my $local = "either"; # could be local(...), my(...), state(...) or our(...)
3689 for ($lop = $kid; !null($lop); $lop = $lop->sibling) {
3690 my $lopname = $lop->name;
3691 my $loppriv = $lop->private;
3693 if ($lopname =~ /^pad[ash]v$/ && $loppriv & OPpLVAL_INTRO) {
3694 if ($loppriv & OPpPAD_STATE) { # state()
3695 ($local = "", last) if $local !~ /^(?:either|state)$/;
3698 ($local = "", last) if $local !~ /^(?:either|my)$/;
3701 my $padname = $self->padname_sv($lop->targ);
3702 if ($padname->FLAGS & SVpad_TYPED) {
3703 $newtype = $padname->SvSTASH->NAME;
3705 } elsif ($lopname =~ /^(?:gv|rv2)([ash])v$/
3706 && $loppriv & OPpOUR_INTRO
3707 or $lopname eq "null" && class($lop) eq 'UNOP'
3708 && $lop->first->name eq "gvsv"
3709 && $lop->first->private & OPpOUR_INTRO) { # our()
3710 my $newlocal = "local " x !!($loppriv & OPpLVAL_INTRO) . "our";
3712 if $local ne 'either' && $local ne $newlocal;
3714 my $funny = !$1 || $1 eq 's' ? '$' : $1 eq 'a' ? '@' : '%';
3715 if (my $t = $self->find_our_type(
3716 $funny . $self->gv_or_padgv($lop->first)->NAME
3720 } elsif ($lopname ne 'undef'
3721 and !($loppriv & OPpLVAL_INTRO)
3722 || !exists $uses_intro{$lopname eq 'null'
3723 ? substr B::ppname($lop->targ), 3
3726 $local = ""; # or not
3728 } elsif ($lopname ne "undef")
3731 ($local = "", last) if $local !~ /^(?:either|local)$/;
3734 if (defined $type && defined $newtype && $newtype ne $type) {
3740 $local = "" if $local eq "either"; # no point if it's all undefs
3741 $local &&= join ' ', map $self->keyword($_), split / /, $local;
3742 $local .= " $type " if $local && length $type;
3743 return $self->deparse($kid, $cx) if null $kid->sibling and not $local;
3744 for (; !null($kid); $kid = $kid->sibling) {
3746 if (class($kid) eq "UNOP" and $kid->first->name eq "gvsv") {
3751 $self->{'avoid_local'}{$$lop}++;
3752 $expr = $self->deparse($kid, 6);
3753 delete $self->{'avoid_local'}{$$lop};
3755 $expr = $self->deparse($kid, 6);
3760 if (@exprs == 1 && ($local eq 'state' || $local eq 'CORE::state')) {
3761 # 'state @a = ...' is legal, while 'state(@a) = ...' currently isn't
3762 return "$local $exprs[0]";
3764 return "$local(" . join(", ", @exprs) . ")";
3766 return $self->maybe_parens( join(", ", @exprs), $cx, 6);
3770 sub is_ifelse_cont {
3772 return ($op->name eq "null" and class($op) eq "UNOP"
3773 and $op->first->name =~ /^(and|cond_expr)$/
3774 and is_scope($op->first->first->sibling));
3780 my $cond = $op->first;
3781 my $true = $cond->sibling;
3782 my $false = $true->sibling;
3783 my $cuddle = $self->{'cuddle'};
3784 unless ($cx < 1 and (is_scope($true) and $true->name ne "null") and
3785 (is_scope($false) || is_ifelse_cont($false))
3786 and $self->{'expand'} < 7) {
3787 $cond = $self->deparse($cond, 8);
3788 $true = $self->deparse($true, 6);
3789 $false = $self->deparse($false, 8);
3790 return $self->maybe_parens("$cond ? $true : $false", $cx, 8);
3793 $cond = $self->deparse($cond, 1);
3794 $true = $self->deparse($true, 0);
3795 my $head = $self->keyword("if") . " ($cond) {\n\t$true\n\b}";
3798 while (!null($false) and is_ifelse_cont($false)) {
3799 my $newop = $false->first;
3800 my $newcond = $newop->first;
3801 my $newtrue = $newcond->sibling;
3802 $false = $newtrue->sibling; # last in chain is OP_AND => no else
3803 if ($newcond->name eq "lineseq")
3805 # lineseq to ensure correct line numbers in elsif()
3806 # Bug #37302 fixed by change #33710.
3807 $newcond = $newcond->first->sibling;
3809 $newcond = $self->deparse($newcond, 1);
3810 $newtrue = $self->deparse($newtrue, 0);
3811 $elsif ||= $self->keyword("elsif");
3812 push @elsifs, "$elsif ($newcond) {\n\t$newtrue\n\b}";
3814 if (!null($false)) {
3815 $false = $cuddle . $self->keyword("else") . " {\n\t" .
3816 $self->deparse($false, 0) . "\n\b}\cK";
3820 return $head . join($cuddle, "", @elsifs) . $false;
3824 my ($self, $op, $cx) = @_;
3825 my $cond = $op->first;
3826 my $true = $cond->sibling;
3828 my $ret = $self->deparse($true, $cx);
3829 $ret =~ s/^(\(?)\$/$1 . $self->keyword("state") . ' $'/e;
3835 my($op, $cx, $init) = @_;
3836 my $enter = $op->first;
3837 my $kid = $enter->sibling;
3838 local(@$self{qw'curstash warnings hints hinthash'})
3839 = @$self{qw'curstash warnings hints hinthash'};
3845 if ($kid->name eq "lineseq") { # bare or infinite loop
3846 if ($kid->last->name eq "unstack") { # infinite
3847 $head = "while (1) "; # Can't use for(;;) if there's a continue
3853 } elsif ($enter->name eq "enteriter") { # foreach
3854 my $ary = $enter->first->sibling; # first was pushmark
3855 my $var = $ary->sibling;
3856 if ($ary->name eq 'null' and $enter->private & OPpITER_REVERSED) {
3857 # "reverse" was optimised away
3858 $ary = listop($self, $ary->first->sibling, 1, 'reverse');
3859 } elsif ($enter->flags & OPf_STACKED
3860 and not null $ary->first->sibling->sibling)
3862 $ary = $self->deparse($ary->first->sibling, 9) . " .. " .
3863 $self->deparse($ary->first->sibling->sibling, 9);
3865 $ary = $self->deparse($ary, 1);
3868 $var = $self->pp_padsv($enter, 1, 1);
3869 } elsif ($var->name eq "rv2gv") {
3870 $var = $self->pp_rv2sv($var, 1);
3871 if ($enter->private & OPpOUR_INTRO) {
3872 # our declarations don't have package names
3873 $var =~ s/^(.).*::/$1/;
3876 } elsif ($var->name eq "gv") {
3877 $var = "\$" . $self->deparse($var, 1);
3879 $var = $self->deparse($var, 1);
3881 $body = $kid->first->first->sibling; # skip OP_AND and OP_ITER
3882 if (!is_state $body->first and $body->first->name !~ /^(?:stub|leave|scope)$/) {
3883 confess unless $var eq '$_';
3884 $body = $body->first;
3885 return $self->deparse($body, 2) . " "
3886 . $self->keyword("foreach") . " ($ary)";
3888 $head = "foreach $var ($ary) ";
3889 } elsif ($kid->name eq "null") { # while/until
3891 $name = {"and" => "while", "or" => "until"}->{$kid->name};
3892 $cond = $kid->first;
3893 $body = $kid->first->sibling;
3894 } elsif ($kid->name eq "stub") { # bare and empty
3895 return "{;}"; # {} could be a hashref
3897 # If there isn't a continue block, then the next pointer for the loop
3898 # will point to the unstack, which is kid's last child, except
3899 # in a bare loop, when it will point to the leaveloop. When neither of
3900 # these conditions hold, then the second-to-last child is the continue
3901 # block (or the last in a bare loop).
3902 my $cont_start = $enter->nextop;
3906 if ($$cont_start != $$op && ${$cont_start} != ${$body->last}) {
3908 $cont = $body->last;
3910 $cont = $body->first;
3911 while (!null($cont->sibling->sibling)) {
3912 $cont = $cont->sibling;
3915 my $state = $body->first;
3916 my $cuddle = $self->{'cuddle'};
3918 for (; $$state != $$cont; $state = $state->sibling) {
3919 push @states, $state;
3921 $body = $self->lineseq(undef, 0, @states);
3922 if (defined $cond and not is_scope $cont and $self->{'expand'} < 3) {
3923 $precond = "for ($init; ";
3924 $postcond = "; " . $self->deparse($cont, 1) .") ";
3927 $cont = $cuddle . "continue {\n\t" .
3928 $self->deparse($cont, 0) . "\n\b}\cK";
3931 return "" if !defined $body;
3933 $precond = "for ($init; ";
3937 $body = $self->deparse($body, 0);
3939 if ($precond) { # for(;;)
3940 $cond &&= $name eq 'until'
3941 ? listop($self, undef, 1, "not", $cond->first)
3942 : $self->deparse($cond, 1);
3943 $head = "$precond$cond$postcond";
3945 if ($name && !$head) {
3946 ref $cond and $cond = $self->deparse($cond, 1);
3947 $head = "$name ($cond) ";
3949 $head =~ s/^(for(?:each)?|while|until)/$self->keyword($1)/e;
3950 $body =~ s/;?$/;\n/;
3952 return $head . "{\n\t" . $body . "\b}" . $cont;
3955 sub pp_leaveloop { shift->loop_common(@_, "") }
3960 my $init = $self->deparse($op, 1);
3961 my $s = $op->sibling;
3962 my $ll = $s->name eq "unstack" ? $s->sibling : $s->first->sibling;
3963 return $self->loop_common($ll, $cx, $init);
3968 return "eval {\n\t" . $self->pp_leave(@_) . "\n\b}";
3972 my ($op, $expect_type) = @_;
3973 my $type = $op->type;
3974 return($type == $expect_type
3975 || ($type == OP_NULL && $op->targ == $expect_type));
3979 my($self, $op, $cx) = @_;
3981 # might be 'my $s :Foo(bar);'
3982 if ($op->targ == OP_LIST) {
3983 my $my_attr = maybe_var_attr($self, $op, $cx);
3984 return $my_attr if defined $my_attr;
3987 if (class($op) eq "OP") {
3989 return $self->{'ex_const'} if $op->targ == OP_CONST;
3990 } elsif (class ($op) eq "COP") {
3991 return &pp_nextstate;
3992 } elsif ($op->first->name eq 'pushmark'
3993 or $op->first->name eq 'null'
3994 && $op->first->targ == OP_PUSHMARK
3995 && _op_is_or_was($op, OP_LIST)) {
3996 return $self->pp_list($op, $cx);
3997 } elsif ($op->first->name eq "enter") {
3998 return $self->pp_leave($op, $cx);
3999 } elsif ($op->first->name eq "leave") {
4000 return $self->pp_leave($op->first, $cx);
4001 } elsif ($op->first->name eq "scope") {
4002 return $self->pp_scope($op->first, $cx);
4003 } elsif ($op->targ == OP_STRINGIFY) {
4004 return $self->dquote($op, $cx);
4005 } elsif ($op->targ == OP_GLOB) {
4006 return $self->pp_glob(
4007 $op->first # entersub
4013 } elsif (!null($op->first->sibling) and
4014 $op->first->sibling->name eq "readline" and
4015 $op->first->sibling->flags & OPf_STACKED) {
4016 return $self->maybe_parens($self->deparse($op->first, 7) . " = "
4017 . $self->deparse($op->first->sibling, 7),
4019 } elsif (!null($op->first->sibling) and
4020 $op->first->sibling->name =~ /^transr?\z/ and
4021 $op->first->sibling->flags & OPf_STACKED) {
4022 return $self->maybe_parens($self->deparse($op->first, 20) . " =~ "
4023 . $self->deparse($op->first->sibling, 20),
4025 } elsif ($op->flags & OPf_SPECIAL && $cx < 1 && !$op->targ) {
4026 return ($self->lex_in_scope("&do") ? "CORE::do" : "do")
4027 . " {\n\t". $self->deparse($op->first, $cx) ."\n\b};";
4028 } elsif (!null($op->first->sibling) and
4029 $op->first->sibling->name eq "null" and
4030 class($op->first->sibling) eq "UNOP" and
4031 $op->first->sibling->first->flags & OPf_STACKED and
4032 $op->first->sibling->first->name eq "rcatline") {
4033 return $self->maybe_parens($self->deparse($op->first, 18) . " .= "
4034 . $self->deparse($op->first->sibling, 18),
4037 return $self->deparse($op->first, $cx);
4044 return $self->padname_sv($targ)->PVX;
4050 return substr($self->padname($op->targ), 1); # skip $/@/%
4055 my($op, $cx, $forbid_parens) = @_;
4056 my $targ = $op->targ;
4057 return $self->maybe_my($op, $cx, $self->padname($targ),
4058 $self->padname_sv($targ),
4062 sub pp_padav { pp_padsv(@_) }
4064 # prepend 'keys' where its been optimised away, with suitable handling
4065 # of CORE:: and parens
4067 sub add_keys_keyword {
4068 my ($self, $str, $cx) = @_;
4069 $str = $self->maybe_parens($str, $cx, 16);
4070 # 'keys %h' versus 'keys(%h)'
4071 $str = " $str" unless $str =~ /^\(/;
4072 return $self->keyword("keys") . $str;
4076 my ($self, $op, $cx) = @_;
4077 my $str = pp_padsv(@_);
4078 # with OPpPADHV_ISKEYS the keys op is optimised away, except
4079 # in scalar context the old op is kept (but not executed) so its targ
4081 if ( ($op->private & OPpPADHV_ISKEYS)
4082 && !(($op->flags & OPf_WANT) == OPf_WANT_SCALAR))
4084 $str = $self->add_keys_keyword($str, $cx);
4092 if (class($op) eq "PADOP") {
4093 return $self->padval($op->padix);
4094 } else { # class($op) eq "SVOP"
4102 my $gv = $self->gv_or_padgv($op);
4103 return $self->maybe_local($op, $cx, $self->stash_variable("\$",
4104 $self->gv_name($gv), $cx));
4110 my $gv = $self->gv_or_padgv($op);
4111 return $self->maybe_qualify("", $self->gv_name($gv));
4114 sub pp_aelemfast_lex {
4117 my $name = $self->padname($op->targ);
4119 my $i = $op->private;
4120 $i -= 256 if $i > 127;
4121 return $name . "[" . ($i + $self->{'arybase'}) . "]";
4127 # optimised PADAV, pre 5.15
4128 return $self->pp_aelemfast_lex(@_) if ($op->flags & OPf_SPECIAL);
4130 my $gv = $self->gv_or_padgv($op);
4131 my($name,$quoted) = $self->stash_variable_name('@',$gv);
4132 $name = $quoted ? "$name->" : '$' . $name;
4133 my $i = $op->private;
4134 $i -= 256 if $i > 127;
4135 return $name . "[" . ($i + $self->{'arybase'}) . "]";
4140 my($op, $cx, $type) = @_;
4142 if (class($op) eq 'NULL' || !$op->can("first")) {
4143 carp("Unexpected op in pp_rv2x");
4146 my $kid = $op->first;
4147 if ($kid->name eq "gv") {
4148 return $self->stash_variable($type,
4149 $self->gv_name($self->gv_or_padgv($kid)), $cx);
4150 } elsif (is_scalar $kid) {
4151 my $str = $self->deparse($kid, 0);
4152 if ($str =~ /^\$([^\w\d])\z/) {
4153 # "$$+" isn't a legal way to write the scalar dereference
4154 # of $+, since the lexer can't tell you aren't trying to
4155 # do something like "$$ + 1" to get one more than your
4156 # PID. Either "${$+}" or "$${+}" are workable
4157 # disambiguations, but if the programmer did the former,
4158 # they'd be in the "else" clause below rather than here.
4159 # It's not clear if this should somehow be unified with
4160 # the code in dq and re_dq that also adds lexer
4161 # disambiguation braces.
4162 $str = '$' . "{$1}"; #'
4164 return $type . $str;
4166 return $type . "{" . $self->deparse($kid, 0) . "}";
4170 sub pp_rv2sv { maybe_local(@_, rv2x(@_, "\$")) }
4171 sub pp_rv2gv { maybe_local(@_, rv2x(@_, "*")) }
4174 my ($self, $op, $cx) = @_;
4175 my $str = rv2x(@_, "%");
4176 if ($op->private & OPpRV2HV_ISKEYS) {
4177 $str = $self->add_keys_keyword($str, $cx);
4179 return maybe_local(@_, $str);
4186 if ($op->first->name eq "padav") {
4187 return $self->maybe_local($op, $cx, '$#' . $self->padany($op->first));
4189 return $self->maybe_local($op, $cx,
4190 $self->rv2x($op->first, $cx, '$#'));
4194 # skip down to the old, ex-rv2cv
4196 my ($self, $op, $cx) = @_;
4197 if (!null($op->first) && $op->first->name eq 'null' &&
4198 $op->first->targ == OP_LIST)
4200 return $self->rv2x($op->first->first->sibling, $cx, "&")
4203 return $self->rv2x($op, $cx, "")
4209 my($cx, @list) = @_;
4210 my @a = map $self->const($_, 6), @list;
4215 } elsif ( @a > 2 and !grep(!/^-?\d+$/, @a)) {
4216 # collapse (-1,0,1,2) into (-1..2)
4217 my ($s, $e) = @a[0,-1];
4219 return $self->maybe_parens("$s..$e", $cx, 9)
4220 unless grep $i++ != $_, @a;
4222 return $self->maybe_parens(join(", ", @a), $cx, 6);
4228 my $kid = $op->first;
4229 if ($kid->name eq "const") { # constant list
4230 my $av = $self->const_sv($kid);
4231 return $self->list_const($cx, $av->ARRAY);
4233 return $self->maybe_local($op, $cx, $self->rv2x($op, $cx, "\@"));
4237 sub is_subscriptable {
4239 if ($op->name =~ /^([ahg]elem|multideref$)/) {
4241 } elsif ($op->name eq "entersub") {
4242 my $kid = $op->first;
4243 return 0 unless null $kid->sibling;
4245 $kid = $kid->sibling until null $kid->sibling;
4246 return 0 if is_scope($kid);
4248 return 0 if $kid->name eq "gv" || $kid->name eq "padcv";
4249 return 0 if is_scalar($kid);
4250 return is_subscriptable($kid);
4256 sub elem_or_slice_array_name
4259 my ($array, $left, $padname, $allow_arrow) = @_;
4261 if ($array->name eq $padname) {
4262 return $self->padany($array);
4263 } elsif (is_scope($array)) { # ${expr}[0]
4264 return "{" . $self->deparse($array, 0) . "}";
4265 } elsif ($array->name eq "gv") {
4266 ($array, my $quoted) =
4267 $self->stash_variable_name(
4268 $left eq '[' ? '@' : '%', $self->gv_or_padgv($array)
4270 if (!$allow_arrow && $quoted) {
4271 # This cannot happen.
4272 die "Invalid variable name $array for slice";
4274 return $quoted ? "$array->" : $array;
4275 } elsif (!$allow_arrow || is_scalar $array) { # $x[0], $$x[0], ...
4276 return $self->deparse($array, 24);
4282 sub elem_or_slice_single_index
4287 $idx = $self->deparse($idx, 1);
4289 # Outer parens in an array index will confuse perl
4290 # if we're interpolating in a regular expression, i.e.
4291 # /$x$foo[(-1)]/ is *not* the same as /$x$foo[-1]/
4293 # If $self->{parens}, then an initial '(' will
4294 # definitely be paired with a final ')'. If
4295 # !$self->{parens}, the misleading parens won't
4296 # have been added in the first place.
4298 # [You might think that we could get "(...)...(...)"
4299 # where the initial and final parens do not match
4300 # each other. But we can't, because the above would
4301 # only happen if there's an infix binop between the
4302 # two pairs of parens, and *that* means that the whole
4303 # expression would be parenthesized as well.]
4305 $idx =~ s/^\((.*)\)$/$1/ if $self->{'parens'};
4307 # Hash-element braces will autoquote a bareword inside themselves.
4308 # We need to make sure that C<$hash{warn()}> doesn't come out as
4309 # C<$hash{warn}>, which has a quite different meaning. Currently
4310 # B::Deparse will always quote strings, even if the string was a
4311 # bareword in the original (i.e. the OPpCONST_BARE flag is ignored
4312 # for constant strings.) So we can cheat slightly here - if we see
4313 # a bareword, we know that it is supposed to be a function call.
4315 $idx =~ s/^([A-Za-z_]\w*)$/$1()/;
4322 my ($op, $cx, $left, $right, $padname) = @_;
4323 my($array, $idx) = ($op->first, $op->first->sibling);
4325 $idx = $self->elem_or_slice_single_index($idx);
4327 unless ($array->name eq $padname) { # Maybe this has been fixed
4328 $array = $array->first; # skip rv2av (or ex-rv2av in _53+)
4330 if (my $array_name=$self->elem_or_slice_array_name
4331 ($array, $left, $padname, 1)) {
4332 return ($array_name =~ /->\z/
4334 : $array_name eq '#' ? '${#}' : "\$" . $array_name)
4335 . $left . $idx . $right;
4337 # $x[20][3]{hi} or expr->[20]
4338 my $arrow = is_subscriptable($array) ? "" : "->";
4339 return $self->deparse($array, 24) . $arrow . $left . $idx . $right;
4344 # a simplified version of elem_or_slice_array_name()
4345 # for the use of pp_multideref
4347 sub multideref_var_name {
4349 my ($gv, $is_hash) = @_;
4351 my ($name, $quoted) =
4352 $self->stash_variable_name( $is_hash ? '%' : '@', $gv);
4353 return $quoted ? "$name->"
4355 ? '${#}' # avoid ${#}[1] => $#[1]
4360 # deparse an OP_MULTICONCAT. If $in_dq is 1, we're within
4361 # a double-quoted string, so for example.
4363 # might get compiled as
4364 # multiconcat("abc", metaquote(multiconcat("def", $x)), "bar")
4365 # and the inner multiconcat should be deparsed as C<def$x> rather than
4366 # the normal C<def . $x>
4367 # Ditto if $in_dq is 2, handle qr/...\Qdef$x\E.../.
4369 sub do_multiconcat {
4371 my($op, $cx, $in_dq) = @_;
4379 for ($kid = $op->first; !null $kid; $kid = $kid->sibling) {
4380 # skip the consts and/or padsv we've optimised away
4382 unless $kid->type == OP_NULL
4383 && ( $kid->targ == OP_PADSV
4384 || $kid->targ == OP_CONST
4385 || $kid->targ == OP_PUSHMARK);
4388 $append = ($op->private & OPpMULTICONCAT_APPEND);
4390 if ($op->private & OPpTARGET_MY) {
4391 # '$lex = ...' or '$lex .= ....' or 'my $lex = '
4392 $lhs = $self->padname($op->targ);
4393 $lhs = "my $lhs" if ($op->private & OPpLVAL_INTRO);
4396 elsif ($op->flags & OPf_STACKED) {
4397 # 'expr = ...' or 'expr .= ....'
4398 my $expr = $append ? shift(@kids) : pop(@kids);
4399 $lhs = $self->deparse($expr, 7);
4404 $lhs .= $append ? ' .= ' : ' = ';
4407 my ($nargs, $const_str, @const_lens) = $op->aux_list($self->{curcv});
4413 push @consts, undef;
4416 push @consts, substr($const_str, $i, $_);
4425 || (($op->private & OPpMULTICONCAT_STRINGIFY) && !$self->{'unquote'}))
4427 # "foo=$foo bar=$bar "
4431 my $s = $self->dq(shift(@kids), 18);
4432 # don't deparse "a${$}b" as "a$$b"
4433 $s = '${$}' if $s eq '$$';
4434 $rhs = dq_disambiguate($rhs, $s);
4437 my $c = shift @consts;
4440 # in pattern: don't convert newline to '\n' etc etc
4441 my $s = re_uninterp(escape_re(re_unback($c)));
4442 $rhs = re_dq_disambiguate($rhs, $s)
4445 my $s = uninterp(escape_str(unback($c)));
4446 $rhs = dq_disambiguate($rhs, $s)
4450 return $rhs if $in_dq;
4451 $rhs = single_delim("qq", '"', $rhs, $self);
4453 elsif ($op->private & OPpMULTICONCAT_FAKE) {
4454 # sprintf("foo=%s bar=%s ", $foo, $bar)
4457 @consts = map { $_ //= ''; s/%/%%/g; $_ } @consts;
4458 my $fmt = join '%s', @consts;
4459 push @all, $self->quoted_const_str($fmt);
4461 # the following is a stripped down copy of sub listop {}
4462 my $parens = $assign || ($cx >= 5) || $self->{'parens'};
4463 my $fullname = $self->keyword('sprintf');
4464 push @all, map $self->deparse($_, 6), @kids;
4467 ? "$fullname(" . join(", ", @all) . ")"
4468 : "$fullname " . join(", ", @all);
4471 # "foo=" . $foo . " bar=" . $bar
4475 push @all, $self->deparse(shift(@kids), 18) if $not_first;
4477 my $c = shift @consts;