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
15 OPpLVAL_INTRO OPpOUR_INTRO OPpENTERSUB_AMPER OPpSLICE OPpCONST_BARE
16 OPpTRANS_SQUASH OPpTRANS_DELETE OPpTRANS_COMPLEMENT OPpTARGET_MY
17 OPpEXISTS_SUB OPpSORT_NUMERIC OPpSORT_INTEGER
19 SVf_IOK SVf_NOK SVf_ROK SVf_POK SVpad_OUR SVf_FAKE SVs_RMG SVs_SMG
21 PMf_KEEP PMf_GLOBAL PMf_CONTINUE PMf_EVAL PMf_ONCE
22 PMf_MULTILINE PMf_SINGLELINE PMf_FOLD PMf_EXTENDED),
23 ($] < 5.008004 ? () : 'OPpSORT_INPLACE'),
24 ($] < 5.008006 ? () : qw(OPpSORT_DESCEND OPpITER_REVERSED)),
25 ($] < 5.008009 ? () : qw(OPpCONST_NOVER OPpPAD_STATE)),
26 ($] < 5.009 ? 'PMf_SKIPWHITE' : qw(RXf_SKIPWHITE)),
27 ($] < 5.011 ? 'CVf_LOCKED' : 'OPpREVERSE_INPLACE'),
28 ($] < 5.013 ? () : 'PMf_NONDESTRUCT'),
30 # This empirical feature test is required during the
31 # transitional phase where blead still identifies itself
32 # as 5.15.2 but has had $[ removed. After blead has its
33 # version number bumped to 5.15.3, this can be reduced to
34 # just test $] < 5.015003.
35 ($] < 5.015002 || do { require B; exists(&B::OPpCONST_ARYBASE) })
36 ? qw(OPpCONST_ARYBASE) : ());
39 use vars qw/$AUTOLOAD/;
43 # Easiest way to keep this code portable between version looks to
44 # be to fake up a dummy constant that will never actually be true.
45 foreach (qw(OPpSORT_INPLACE OPpSORT_DESCEND OPpITER_REVERSED OPpCONST_NOVER
46 OPpPAD_STATE RXf_SKIPWHITE CVf_LOCKED OPpREVERSE_INPLACE
47 PMf_NONDESTRUCT OPpCONST_ARYBASE)) {
49 *{$_} = sub () {0} unless *{$_}{CODE};
53 # Changes between 0.50 and 0.51:
54 # - fixed nulled leave with live enter in sort { }
55 # - fixed reference constants (\"str")
56 # - handle empty programs gracefully
57 # - handle infinite loops (for (;;) {}, while (1) {})
58 # - differentiate between `for my $x ...' and `my $x; for $x ...'
59 # - various minor cleanups
60 # - moved globals into an object
61 # - added `-u', like B::C
62 # - package declarations using cop_stash
63 # - subs, formats and code sorted by cop_seq
64 # Changes between 0.51 and 0.52:
65 # - added pp_threadsv (special variables under USE_5005THREADS)
66 # - added documentation
67 # Changes between 0.52 and 0.53:
68 # - many changes adding precedence contexts and associativity
69 # - added `-p' and `-s' output style options
70 # - various other minor fixes
71 # Changes between 0.53 and 0.54:
72 # - added support for new `for (1..100)' optimization,
74 # Changes between 0.54 and 0.55:
75 # - added support for new qr// construct
76 # - added support for new pp_regcreset OP
77 # Changes between 0.55 and 0.56:
78 # - tested on base/*.t, cmd/*.t, comp/*.t, io/*.t
79 # - fixed $# on non-lexicals broken in last big rewrite
80 # - added temporary fix for change in opcode of OP_STRINGIFY
81 # - fixed problem in 0.54's for() patch in `for (@ary)'
82 # - fixed precedence in conditional of ?:
83 # - tweaked list paren elimination in `my($x) = @_'
84 # - made continue-block detection trickier wrt. null ops
85 # - fixed various prototype problems in pp_entersub
86 # - added support for sub prototypes that never get GVs
87 # - added unquoting for special filehandle first arg in truncate
88 # - print doubled rv2gv (a bug) as `*{*GV}' instead of illegal `**GV'
89 # - added semicolons at the ends of blocks
90 # - added -l `#line' declaration option -- fixes cmd/subval.t 27,28
91 # Changes between 0.56 and 0.561:
92 # - fixed multiply-declared my var in pp_truncate (thanks to Sarathy)
93 # - used new B.pm symbolic constants (done by Nick Ing-Simmons)
94 # Changes between 0.561 and 0.57:
95 # - stylistic changes to symbolic constant stuff
96 # - handled scope in s///e replacement code
97 # - added unquote option for expanding "" into concats, etc.
98 # - split method and proto parts of pp_entersub into separate functions
99 # - various minor cleanups
100 # Changes after 0.57:
101 # - added parens in \&foo (patch by Albert Dvornik)
102 # Changes between 0.57 and 0.58:
103 # - fixed `0' statements that weren't being printed
104 # - added methods for use from other programs
105 # (based on patches from James Duncan and Hugo van der Sanden)
106 # - added -si and -sT to control indenting (also based on a patch from Hugo)
107 # - added -sv to print something else instead of '???'
108 # - preliminary version of utf8 tr/// handling
109 # Changes after 0.58:
110 # - uses of $op->ppaddr changed to new $op->name (done by Sarathy)
111 # - added support for Hugo's new OP_SETSTATE (like nextstate)
112 # Changes between 0.58 and 0.59
113 # - added support for Chip's OP_METHOD_NAMED
114 # - added support for Ilya's OPpTARGET_MY optimization
115 # - elided arrows before `()' subscripts when possible
116 # Changes between 0.59 and 0.60
117 # - support for method attributes was added
118 # - some warnings fixed
119 # - separate recognition of constant subs
120 # - rewrote continue block handling, now recognizing for loops
121 # - added more control of expanding control structures
122 # Changes between 0.60 and 0.61 (mostly by Robin Houston)
124 # - support for pragmas and 'use'
125 # - support for the little-used $[ variable
126 # - support for __DATA__ sections
128 # - BEGIN, CHECK, INIT and END blocks
129 # - scoping of subroutine declarations fixed
130 # - compile-time output from the input program can be suppressed, so that the
131 # output is just the deparsed code. (a change to O.pm in fact)
132 # - our() declarations
133 # - *all* the known bugs are now listed in the BUGS section
134 # - comprehensive test mechanism (TEST -deparse)
135 # Changes between 0.62 and 0.63 (mostly by Rafael Garcia-Suarez)
138 # - support for command-line switches (-l, -0, etc.)
139 # Changes between 0.63 and 0.64
140 # - support for //, CHECK blocks, and assertions
141 # - improved handling of foreach loops and lexicals
142 # - option to use Data::Dumper for constants
144 # - discovered lots more bugs not yet fixed
148 # Changes between 0.72 and 0.73
149 # - support new switch constructs
152 # (See also BUGS section at the end of this file)
154 # - finish tr/// changes
155 # - add option for even more parens (generalize \&foo change)
156 # - left/right context
157 # - copy comments (look at real text with $^P?)
158 # - avoid semis in one-statement blocks
159 # - associativity of &&=, ||=, ?:
160 # - ',' => '=>' (auto-unquote?)
161 # - break long lines ("\r" as discretionary break?)
162 # - configurable syntax highlighting: ANSI color, HTML, TeX, etc.
163 # - more style options: brace style, hex vs. octal, quotes, ...
164 # - print big ints as hex/octal instead of decimal (heuristic?)
165 # - handle `my $x if 0'?
166 # - version using op_next instead of op_first/sibling?
167 # - avoid string copies (pass arrays, one big join?)
170 # Current test.deparse failures
171 # comp/hints 6 - location of BEGIN blocks wrt. block openings
172 # run/switchI 1 - missing -I switches entirely
173 # perl -Ifoo -e 'print @INC'
174 # op/caller 2 - warning mask propagates backwards before warnings::register
175 # 'use warnings; BEGIN {${^WARNING_BITS} eq "U"x12;} use warnings::register'
176 # op/getpid 2 - can't assign to shared my() declaration (threads only)
177 # 'my $x : shared = 5'
178 # op/override 7 - parens on overridden require change v-string interpretation
179 # 'BEGIN{*CORE::GLOBAL::require=sub {}} require v5.6'
180 # c.f. 'BEGIN { *f = sub {0} }; f 2'
181 # op/pat 774 - losing Unicode-ness of Latin1-only strings
182 # 'use charnames ":short"; $x="\N{latin:a with acute}"'
183 # op/recurse 12 - missing parens on recursive call makes it look like method
185 # op/subst 90 - inconsistent handling of utf8 under "use utf8"
186 # op/taint 29 - "use re 'taint'" deparsed in the wrong place wrt. block open
187 # op/tiehandle compile - "use strict" deparsed in the wrong place
189 # ext/B/t/xref 11 - line numbers when we add newlines to one-line subs
190 # ext/Data/Dumper/t/dumper compile
191 # ext/DB_file/several
193 # ext/Ernno/Errno warnings
194 # ext/IO/lib/IO/t/io_sel 23
195 # ext/PerlIO/t/encoding compile
196 # ext/POSIX/t/posix 6
197 # ext/Socket/Socket 8
198 # ext/Storable/t/croak compile
199 # lib/Attribute/Handlers/t/multi compile
200 # lib/bignum/ several
204 # lib/ExtUtils/t/bytes 4
205 # lib/File/DosGlob compile
206 # lib/Filter/Simple/t/data 1
207 # lib/Math/BigInt/t/constant 1
208 # lib/Net/t/config Deparse-warning
209 # lib/overload compile
210 # lib/Switch/ several
212 # lib/Test/Simple several
214 # lib/Tie/File/t/29_downcopy 5
217 # Object fields (were globals):
220 # (local($a), local($b)) and local($a, $b) have the same internal
221 # representation but the short form looks better. We notice we can
222 # use a large-scale local when checking the list, but need to prevent
223 # individual locals too. This hash holds the addresses of OPs that
224 # have already had their local-ness accounted for. The same thing
228 # CV for current sub (or main program) being deparsed
231 # Cached hash of lexical variables for curcv: keys are names,
232 # each value is an array of pairs, indicating the cop_seq of scopes
233 # in which a var of that name is valid.
236 # COP for statement being deparsed
239 # name of the current package for deparsed code
242 # array of [cop_seq, CV, is_format?] for subs and formats we still
246 # as above, but [name, prototype] for subs that never got a GV
248 # subs_done, forms_done:
249 # keys are addresses of GVs for subs and formats we've already
250 # deparsed (or at least put into subs_todo)
253 # keys are names of subs for which we've printed declarations.
254 # That means we can omit parentheses from the arguments. It also means we
255 # need to put CORE:: on core functions of the same name.
258 # Keeps track of fully qualified names of all deparsed subs.
263 # cuddle: ` ' or `\n', depending on -sC
268 # A little explanation of how precedence contexts and associativity
271 # deparse() calls each per-op subroutine with an argument $cx (short
272 # for context, but not the same as the cx* in the perl core), which is
273 # a number describing the op's parents in terms of precedence, whether
274 # they're inside an expression or at statement level, etc. (see
275 # chart below). When ops with children call deparse on them, they pass
276 # along their precedence. Fractional values are used to implement
277 # associativity (`($x + $y) + $z' => `$x + $y + $y') and related
278 # parentheses hacks. The major disadvantage of this scheme is that
279 # it doesn't know about right sides and left sides, so say if you
280 # assign a listop to a variable, it can't tell it's allowed to leave
281 # the parens off the listop.
284 # 26 [TODO] inside interpolation context ("")
285 # 25 left terms and list operators (leftward)
289 # 21 right ! ~ \ and unary + and -
294 # 16 nonassoc named unary operators
295 # 15 nonassoc < > <= >= lt gt le ge
296 # 14 nonassoc == != <=> eq ne cmp
303 # 7 right = += -= *= etc.
305 # 5 nonassoc list operators (rightward)
309 # 1 statement modifiers
310 # 0.5 statements, but still print scopes as do { ... }
313 # Nonprinting characters with special meaning:
314 # \cS - steal parens (see maybe_parens_unop)
315 # \n - newline and indent
316 # \t - increase indent
317 # \b - decrease indent (`outdent')
318 # \f - flush left (no indent)
319 # \cK - kill following semicolon, if any
323 return class($op) eq "NULL";
328 my($cv, $is_form) = @_;
329 return unless ($cv->FILE eq $0 || exists $self->{files}{$cv->FILE});
331 if ($cv->OUTSIDE_SEQ) {
332 $seq = $cv->OUTSIDE_SEQ;
333 } elsif (!null($cv->START) and is_state($cv->START)) {
334 $seq = $cv->START->cop_seq;
338 push @{$self->{'subs_todo'}}, [$seq, $cv, $is_form];
339 unless ($is_form || class($cv->STASH) eq 'SPECIAL') {
340 $self->{'subs_deparsed'}{$cv->STASH->NAME."::".$cv->GV->NAME} = 1;
346 my $ent = shift @{$self->{'subs_todo'}};
349 my $name = $self->gv_name($gv);
351 return "format $name =\n"
352 . $self->deparse_format($ent->[1]). "\n";
354 $self->{'subs_declared'}{$name} = 1;
355 if ($name eq "BEGIN") {
356 my $use_dec = $self->begin_is_use($cv);
357 if (defined ($use_dec) and $self->{'expand'} < 5) {
358 return () if 0 == length($use_dec);
363 if ($self->{'linenums'}) {
364 my $line = $gv->LINE;
365 my $file = $gv->FILE;
366 $l = "\n\f#line $line \"$file\"\n";
369 if (class($cv->STASH) ne "SPECIAL") {
370 my $stash = $cv->STASH->NAME;
371 if ($stash ne $self->{'curstash'}) {
372 $p = "package $stash;\n";
373 $name = "$self->{'curstash'}::$name" unless $name =~ /::/;
374 $self->{'curstash'} = $stash;
376 $name =~ s/^\Q$stash\E::(?!\z|.*::)//;
378 return "${p}${l}sub $name " . $self->deparse_sub($cv);
382 # Return a "use" declaration for this BEGIN block, if appropriate
384 my ($self, $cv) = @_;
385 my $root = $cv->ROOT;
386 local @$self{qw'curcv curcvlex'} = ($cv);
388 #B::walkoptree($cv->ROOT, "debug");
389 my $lineseq = $root->first;
390 return if $lineseq->name ne "lineseq";
392 my $req_op = $lineseq->first->sibling;
393 return if $req_op->name ne "require";
396 if ($req_op->first->private & OPpCONST_BARE) {
397 # Actually it should always be a bareword
398 $module = $self->const_sv($req_op->first)->PV;
399 $module =~ s[/][::]g;
403 $module = $self->const($self->const_sv($req_op->first), 6);
407 my $version_op = $req_op->sibling;
408 return if class($version_op) eq "NULL";
409 if ($version_op->name eq "lineseq") {
410 # We have a version parameter; skip nextstate & pushmark
411 my $constop = $version_op->first->next->next;
413 return unless $self->const_sv($constop)->PV eq $module;
414 $constop = $constop->sibling;
415 $version = $self->const_sv($constop);
416 if (class($version) eq "IV") {
417 $version = $version->int_value;
418 } elsif (class($version) eq "NV") {
419 $version = $version->NV;
420 } elsif (class($version) ne "PVMG") {
421 # Includes PVIV and PVNV
422 $version = $version->PV;
424 # version specified as a v-string
425 $version = 'v'.join '.', map ord, split //, $version->PV;
427 $constop = $constop->sibling;
428 return if $constop->name ne "method_named";
429 return if $self->const_sv($constop)->PV ne "VERSION";
432 $lineseq = $version_op->sibling;
433 return if $lineseq->name ne "lineseq";
434 my $entersub = $lineseq->first->sibling;
435 if ($entersub->name eq "stub") {
436 return "use $module $version ();\n" if defined $version;
437 return "use $module ();\n";
439 return if $entersub->name ne "entersub";
441 # See if there are import arguments
444 my $svop = $entersub->first->sibling; # Skip over pushmark
445 return unless $self->const_sv($svop)->PV eq $module;
447 # Pull out the arguments
448 for ($svop=$svop->sibling; $svop->name ne "method_named";
449 $svop = $svop->sibling) {
450 $args .= ", " if length($args);
451 $args .= $self->deparse($svop, 6);
455 my $method_named = $svop;
456 return if $method_named->name ne "method_named";
457 my $method_name = $self->const_sv($method_named)->PV;
459 if ($method_name eq "unimport") {
463 # Certain pragmas are dealt with using hint bits,
464 # so we ignore them here
465 if ($module eq 'strict' || $module eq 'integer'
466 || $module eq 'bytes' || $module eq 'warnings'
467 || $module eq 'feature') {
471 if (defined $version && length $args) {
472 return "$use $module $version ($args);\n";
473 } elsif (defined $version) {
474 return "$use $module $version;\n";
475 } elsif (length $args) {
476 return "$use $module ($args);\n";
478 return "$use $module;\n";
483 my ($self, $pack) = @_;
485 if (!defined $pack) {
490 $pack =~ s/(::)?$/::/;
492 $stash = \%{"main::$pack"};
494 my %stash = svref_2object($stash)->ARRAY;
495 while (my ($key, $val) = each %stash) {
496 my $class = class($val);
497 if ($class eq "PV") {
498 # Just a prototype. As an ugly but fairly effective way
499 # to find out if it belongs here is to see if the AUTOLOAD
500 # (if any) for the stash was defined in one of our files.
501 my $A = $stash{"AUTOLOAD"};
502 if (defined ($A) && class($A) eq "GV" && defined($A->CV)
503 && class($A->CV) eq "CV") {
505 next unless $AF eq $0 || exists $self->{'files'}{$AF};
507 push @{$self->{'protos_todo'}}, [$pack . $key, $val->PV];
508 } elsif ($class eq "IV" && !($val->FLAGS & SVf_ROK)) {
509 # Just a name. As above.
510 # But skip proxy constant subroutines, as some form of perl-space
511 # visible code must have created them, be it a use statement, or
512 # some direct symbol-table manipulation code that we will Deparse
513 my $A = $stash{"AUTOLOAD"};
514 if (defined ($A) && class($A) eq "GV" && defined($A->CV)
515 && class($A->CV) eq "CV") {
517 next unless $AF eq $0 || exists $self->{'files'}{$AF};
519 push @{$self->{'protos_todo'}}, [$pack . $key, undef];
520 } elsif ($class eq "GV") {
521 if (class(my $cv = $val->CV) ne "SPECIAL") {
522 next if $self->{'subs_done'}{$$val}++;
523 next if $$val != ${$cv->GV}; # Ignore imposters
526 if (class(my $cv = $val->FORM) ne "SPECIAL") {
527 next if $self->{'forms_done'}{$$val}++;
528 next if $$val != ${$cv->GV}; # Ignore imposters
531 if (class($val->HV) ne "SPECIAL" && $key =~ /::$/) {
532 $self->stash_subs($pack . $key)
533 unless $pack eq '' && $key eq 'main::';
534 # avoid infinite recursion
544 foreach $ar (@{$self->{'protos_todo'}}) {
545 my $proto = (defined $ar->[1] ? " (". $ar->[1] . ")" : "");
546 push @ret, "sub " . $ar->[0] . "$proto;\n";
548 delete $self->{'protos_todo'};
556 while (length($opt = substr($opts, 0, 1))) {
558 $self->{'cuddle'} = " ";
559 $opts = substr($opts, 1);
560 } elsif ($opt eq "i") {
561 $opts =~ s/^i(\d+)//;
562 $self->{'indent_size'} = $1;
563 } elsif ($opt eq "T") {
564 $self->{'use_tabs'} = 1;
565 $opts = substr($opts, 1);
566 } elsif ($opt eq "v") {
567 $opts =~ s/^v([^.]*)(.|$)//;
568 $self->{'ex_const'} = $1;
575 my $self = bless {}, $class;
576 $self->{'cuddle'} = "\n";
577 $self->{'curcop'} = undef;
578 $self->{'curstash'} = "main";
579 $self->{'ex_const'} = "'???'";
580 $self->{'expand'} = 0;
581 $self->{'files'} = {};
582 $self->{'indent_size'} = 4;
583 $self->{'linenums'} = 0;
584 $self->{'parens'} = 0;
585 $self->{'subs_todo'} = [];
586 $self->{'unquote'} = 0;
587 $self->{'use_dumper'} = 0;
588 $self->{'use_tabs'} = 0;
590 $self->{'ambient_arybase'} = 0;
591 $self->{'ambient_warnings'} = undef; # Assume no lexical warnings
592 $self->{'ambient_hints'} = 0;
593 $self->{'ambient_hinthash'} = undef;
596 while (my $arg = shift @_) {
598 $self->{'use_dumper'} = 1;
599 require Data::Dumper;
600 } elsif ($arg =~ /^-f(.*)/) {
601 $self->{'files'}{$1} = 1;
602 } elsif ($arg eq "-l") {
603 $self->{'linenums'} = 1;
604 } elsif ($arg eq "-p") {
605 $self->{'parens'} = 1;
606 } elsif ($arg eq "-P") {
607 $self->{'noproto'} = 1;
608 } elsif ($arg eq "-q") {
609 $self->{'unquote'} = 1;
610 } elsif (substr($arg, 0, 2) eq "-s") {
611 $self->style_opts(substr $arg, 2);
612 } elsif ($arg =~ /^-x(\d)$/) {
613 $self->{'expand'} = $1;
620 # Mask out the bits that L<warnings::register> uses
623 $WARN_MASK = $warnings::Bits{all} | $warnings::DeadBits{all};
630 # Initialise the contextual information, either from
631 # defaults provided with the ambient_pragmas method,
632 # or from perl's own defaults otherwise.
636 $self->{'arybase'} = $self->{'ambient_arybase'};
637 $self->{'warnings'} = defined ($self->{'ambient_warnings'})
638 ? $self->{'ambient_warnings'} & WARN_MASK
640 $self->{'hints'} = $self->{'ambient_hints'};
641 $self->{'hints'} &= 0xFF if $] < 5.009;
642 $self->{'hinthash'} = $self->{'ambient_hinthash'};
644 # also a convenient place to clear out subs_declared
645 delete $self->{'subs_declared'};
651 my $self = B::Deparse->new(@args);
652 # First deparse command-line args
653 if (defined $^I) { # deparse -i
654 print q(BEGIN { $^I = ).perlstring($^I).qq(; }\n);
656 if ($^W) { # deparse -w
657 print qq(BEGIN { \$^W = $^W; }\n);
659 if ($/ ne "\n" or defined $O::savebackslash) { # deparse -l and -0
660 my $fs = perlstring($/) || 'undef';
661 my $bs = perlstring($O::savebackslash) || 'undef';
662 print qq(BEGIN { \$/ = $fs; \$\\ = $bs; }\n);
664 my @BEGINs = B::begin_av->isa("B::AV") ? B::begin_av->ARRAY : ();
665 my @UNITCHECKs = B::unitcheck_av->isa("B::AV")
666 ? B::unitcheck_av->ARRAY
668 my @CHECKs = B::check_av->isa("B::AV") ? B::check_av->ARRAY : ();
669 my @INITs = B::init_av->isa("B::AV") ? B::init_av->ARRAY : ();
670 my @ENDs = B::end_av->isa("B::AV") ? B::end_av->ARRAY : ();
671 for my $block (@BEGINs, @UNITCHECKs, @CHECKs, @INITs, @ENDs) {
672 $self->todo($block, 0);
675 local($SIG{"__DIE__"}) =
677 if ($self->{'curcop'}) {
678 my $cop = $self->{'curcop'};
679 my($line, $file) = ($cop->line, $cop->file);
680 print STDERR "While deparsing $file near line $line,\n";
683 $self->{'curcv'} = main_cv;
684 $self->{'curcvlex'} = undef;
685 print $self->print_protos;
686 @{$self->{'subs_todo'}} =
687 sort {$a->[0] <=> $b->[0]} @{$self->{'subs_todo'}};
688 print $self->indent($self->deparse_root(main_root)), "\n"
689 unless null main_root;
691 while (scalar(@{$self->{'subs_todo'}})) {
692 push @text, $self->next_todo;
694 print $self->indent(join("", @text)), "\n" if @text;
696 # Print __DATA__ section, if necessary
698 my $laststash = defined $self->{'curcop'}
699 ? $self->{'curcop'}->stash->NAME : $self->{'curstash'};
700 if (defined *{$laststash."::DATA"}{IO}) {
701 print "package $laststash;\n"
702 unless $laststash eq $self->{'curstash'};
704 print readline(*{$laststash."::DATA"});
712 croak "Usage: ->coderef2text(CODEREF)" unless UNIVERSAL::isa($sub, "CODE");
715 return $self->indent($self->deparse_sub(svref_2object($sub)));
718 sub ambient_pragmas {
720 my ($arybase, $hint_bits, $warning_bits, $hinthash) = (0, 0);
726 if ($name eq 'strict') {
729 if ($val eq 'none') {
730 $hint_bits &= ~strict::bits(qw/refs subs vars/);
736 @names = qw/refs subs vars/;
742 @names = split' ', $val;
744 $hint_bits |= strict::bits(@names);
747 elsif ($name eq '$[') {
748 if (OPpCONST_ARYBASE) {
751 croak "\$[ can't be non-zero on this perl" unless $val == 0;
755 elsif ($name eq 'integer'
757 || $name eq 'utf8') {
760 $hint_bits |= ${$::{"${name}::"}{"hint_bits"}};
763 $hint_bits &= ~${$::{"${name}::"}{"hint_bits"}};
767 elsif ($name eq 're') {
769 if ($val eq 'none') {
770 $hint_bits &= ~re::bits(qw/taint eval/);
776 @names = qw/taint eval/;
782 @names = split' ',$val;
784 $hint_bits |= re::bits(@names);
787 elsif ($name eq 'warnings') {
788 if ($val eq 'none') {
789 $warning_bits = $warnings::NONE;
798 @names = split/\s+/, $val;
801 $warning_bits = $warnings::NONE if !defined ($warning_bits);
802 $warning_bits |= warnings::bits(@names);
805 elsif ($name eq 'warning_bits') {
806 $warning_bits = $val;
809 elsif ($name eq 'hint_bits') {
813 elsif ($name eq '%^H') {
818 croak "Unknown pragma type: $name";
822 croak "The ambient_pragmas method expects an even number of args";
825 $self->{'ambient_arybase'} = $arybase;
826 $self->{'ambient_warnings'} = $warning_bits;
827 $self->{'ambient_hints'} = $hint_bits;
828 $self->{'ambient_hinthash'} = $hinthash;
831 # This method is the inner loop, so try to keep it simple
836 Carp::confess("Null op in deparse") if !defined($op)
837 || class($op) eq "NULL";
838 my $meth = "pp_" . $op->name;
839 return $self->$meth($op, $cx);
845 my @lines = split(/\n/, $txt);
850 my $cmd = substr($line, 0, 1);
851 if ($cmd eq "\t" or $cmd eq "\b") {
852 $level += ($cmd eq "\t" ? 1 : -1) * $self->{'indent_size'};
853 if ($self->{'use_tabs'}) {
854 $leader = "\t" x ($level / 8) . " " x ($level % 8);
856 $leader = " " x $level;
858 $line = substr($line, 1);
860 if (substr($line, 0, 1) eq "\f") {
861 $line = substr($line, 1); # no indent
863 $line = $leader . $line;
867 return join("\n", @lines);
874 Carp::confess("NULL in deparse_sub") if !defined($cv) || $cv->isa("B::NULL");
875 Carp::confess("SPECIAL in deparse_sub") if $cv->isa("B::SPECIAL");
876 local $self->{'curcop'} = $self->{'curcop'};
877 if ($cv->FLAGS & SVf_POK) {
878 $proto = "(". $cv->PV . ") ";
880 if ($cv->CvFLAGS & (CVf_METHOD|CVf_LOCKED|CVf_LVALUE)) {
882 $proto .= "lvalue " if $cv->CvFLAGS & CVf_LVALUE;
883 $proto .= "locked " if $cv->CvFLAGS & CVf_LOCKED;
884 $proto .= "method " if $cv->CvFLAGS & CVf_METHOD;
887 local($self->{'curcv'}) = $cv;
888 local($self->{'curcvlex'});
889 local(@$self{qw'curstash warnings hints hinthash'})
890 = @$self{qw'curstash warnings hints hinthash'};
892 if (not null $cv->ROOT) {
893 my $lineseq = $cv->ROOT->first;
894 if ($lineseq->name eq "lineseq") {
896 for(my$o=$lineseq->first; $$o; $o=$o->sibling) {
899 $body = $self->lineseq(undef, @ops).";";
900 my $scope_en = $self->find_scope_en($lineseq);
901 if (defined $scope_en) {
902 my $subs = join"", $self->seq_subs($scope_en);
903 $body .= ";\n$subs" if length($subs);
907 $body = $self->deparse($cv->ROOT->first, 0);
911 my $sv = $cv->const_sv;
913 # uh-oh. inlinable sub... format it differently
914 return $proto . "{ " . $self->const($sv, 0) . " }\n";
915 } else { # XSUB? (or just a declaration)
919 return $proto ."{\n\t$body\n\b}" ."\n";
926 local($self->{'curcv'}) = $form;
927 local($self->{'curcvlex'});
928 local($self->{'in_format'}) = 1;
929 local(@$self{qw'curstash warnings hints hinthash'})
930 = @$self{qw'curstash warnings hints hinthash'};
931 my $op = $form->ROOT;
933 return "\f." if $op->first->name eq 'stub'
934 || $op->first->name eq 'nextstate';
935 $op = $op->first->first; # skip leavewrite, lineseq
936 while (not null $op) {
937 $op = $op->sibling; # skip nextstate
939 $kid = $op->first->sibling; # skip pushmark
940 push @text, "\f".$self->const_sv($kid)->PV;
941 $kid = $kid->sibling;
942 for (; not null $kid; $kid = $kid->sibling) {
943 push @exprs, $self->deparse($kid, 0);
945 push @text, "\f".join(", ", @exprs)."\n" if @exprs;
948 return join("", @text) . "\f.";
953 return $op->name eq "leave" || $op->name eq "scope"
954 || $op->name eq "lineseq"
955 || ($op->name eq "null" && class($op) eq "UNOP"
956 && (is_scope($op->first) || $op->first->name eq "enter"));
960 my $name = $_[0]->name;
961 return $name eq "nextstate" || $name eq "dbstate" || $name eq "setstate";
964 sub is_miniwhile { # check for one-line loop (`foo() while $y--')
966 return (!null($op) and null($op->sibling)
967 and $op->name eq "null" and class($op) eq "UNOP"
968 and (($op->first->name =~ /^(and|or)$/
969 and $op->first->first->sibling->name eq "lineseq")
970 or ($op->first->name eq "lineseq"
971 and not null $op->first->first->sibling
972 and $op->first->first->sibling->name eq "unstack")
976 # Check if the op and its sibling are the initialization and the rest of a
977 # for (..;..;..) { ... } loop
980 # This OP might be almost anything, though it won't be a
981 # nextstate. (It's the initialization, so in the canonical case it
982 # will be an sassign.) The sibling is (old style) a lineseq whose
983 # first child is a nextstate and whose second is a leaveloop, or
984 # (new style) an unstack whose sibling is a leaveloop.
985 my $lseq = $op->sibling;
986 return 0 unless !is_state($op) and !null($lseq);
987 if ($lseq->name eq "lineseq") {
988 if ($lseq->first && !null($lseq->first) && is_state($lseq->first)
989 && (my $sib = $lseq->first->sibling)) {
990 return (!null($sib) && $sib->name eq "leaveloop");
992 } elsif ($lseq->name eq "unstack" && ($lseq->flags & OPf_SPECIAL)) {
993 my $sib = $lseq->sibling;
994 return $sib && !null($sib) && $sib->name eq "leaveloop";
1001 return ($op->name eq "rv2sv" or
1002 $op->name eq "padsv" or
1003 $op->name eq "gv" or # only in array/hash constructs
1004 $op->flags & OPf_KIDS && !null($op->first)
1005 && $op->first->name eq "gvsv");
1010 my($text, $cx, $prec) = @_;
1011 if ($prec < $cx # unary ops nest just fine
1012 or $prec == $cx and $cx != 4 and $cx != 16 and $cx != 21
1013 or $self->{'parens'})
1016 # In a unop, let parent reuse our parens; see maybe_parens_unop
1017 $text = "\cS" . $text if $cx == 16;
1024 # same as above, but get around the `if it looks like a function' rule
1025 sub maybe_parens_unop {
1027 my($name, $kid, $cx) = @_;
1028 if ($cx > 16 or $self->{'parens'}) {
1029 $kid = $self->deparse($kid, 1);
1030 if ($name eq "umask" && $kid =~ /^\d+$/) {
1031 $kid = sprintf("%#o", $kid);
1033 return $self->keyword($name) . "($kid)";
1035 $kid = $self->deparse($kid, 16);
1036 if ($name eq "umask" && $kid =~ /^\d+$/) {
1037 $kid = sprintf("%#o", $kid);
1039 $name = $self->keyword($name);
1040 if (substr($kid, 0, 1) eq "\cS") {
1042 return $name . substr($kid, 1);
1043 } elsif (substr($kid, 0, 1) eq "(") {
1044 # avoid looks-like-a-function trap with extra parens
1045 # (`+' can lead to ambiguities)
1046 return "$name(" . $kid . ")";
1048 return "$name $kid";
1053 sub maybe_parens_func {
1055 my($func, $text, $cx, $prec) = @_;
1056 if ($prec <= $cx or substr($text, 0, 1) eq "(" or $self->{'parens'}) {
1057 return "$func($text)";
1059 return "$func $text";
1065 my($op, $cx, $text) = @_;
1066 my $our_intro = ($op->name =~ /^(gv|rv2)[ash]v$/) ? OPpOUR_INTRO : 0;
1067 if ($op->private & (OPpLVAL_INTRO|$our_intro)
1068 and not $self->{'avoid_local'}{$$op}) {
1069 my $our_local = ($op->private & OPpLVAL_INTRO) ? "local" : "our";
1070 if( $our_local eq 'our' ) {
1071 if ( $text !~ /^\W(\w+::)*\w+\z/
1072 and !utf8::decode($text) || $text !~ /^\W(\w+::)*\w+\z/
1074 die "Unexpected our($text)\n";
1076 $text =~ s/(\w+::)+//;
1078 if (want_scalar($op)) {
1079 return "$our_local $text";
1081 return $self->maybe_parens_func("$our_local", $text, $cx, 16);
1090 my($op, $cx, $func, @args) = @_;
1091 if ($op->private & OPpTARGET_MY) {
1092 my $var = $self->padname($op->targ);
1093 my $val = $func->($self, $op, 7, @args);
1094 return $self->maybe_parens("$var = $val", $cx, 7);
1096 return $func->($self, $op, $cx, @args);
1103 return $self->{'curcv'}->PADLIST->ARRAYelt(0)->ARRAYelt($targ);
1108 my($op, $cx, $text) = @_;
1109 if ($op->private & OPpLVAL_INTRO and not $self->{'avoid_local'}{$$op}) {
1110 my $my = $op->private & OPpPAD_STATE
1111 ? $self->keyword("state")
1113 if (want_scalar($op)) {
1116 return $self->maybe_parens_func($my, $text, $cx, 16);
1123 # The following OPs don't have functions:
1125 # pp_padany -- does not exist after parsing
1128 if ($AUTOLOAD =~ s/^.*::pp_//) {
1129 warn "unexpected OP_".uc $AUTOLOAD;
1132 die "Undefined subroutine $AUTOLOAD called";
1136 sub DESTROY {} # Do not AUTOLOAD
1138 # $root should be the op which represents the root of whatever
1139 # we're sequencing here. If it's undefined, then we don't append
1140 # any subroutine declarations to the deparsed ops, otherwise we
1141 # append appropriate declarations.
1143 my($self, $root, @ops) = @_;
1146 my $out_cop = $self->{'curcop'};
1147 my $out_seq = defined($out_cop) ? $out_cop->cop_seq : undef;
1149 if (defined $root) {
1150 $limit_seq = $out_seq;
1152 $nseq = $self->find_scope_st($root->sibling) if ${$root->sibling};
1153 $limit_seq = $nseq if !defined($limit_seq)
1154 or defined($nseq) && $nseq < $limit_seq;
1156 $limit_seq = $self->{'limit_seq'}
1157 if defined($self->{'limit_seq'})
1158 && (!defined($limit_seq) || $self->{'limit_seq'} < $limit_seq);
1159 local $self->{'limit_seq'} = $limit_seq;
1161 $self->walk_lineseq($root, \@ops,
1162 sub { push @exprs, $_[0]} );
1164 my $body = join(";\n", grep {length} @exprs);
1166 if (defined $root && defined $limit_seq && !$self->{'in_format'}) {
1167 $subs = join "\n", $self->seq_subs($limit_seq);
1169 return join(";\n", grep {length} $body, $subs);
1173 my($real_block, $self, $op, $cx) = @_;
1177 local(@$self{qw'curstash warnings hints hinthash'})
1178 = @$self{qw'curstash warnings hints hinthash'} if $real_block;
1180 $kid = $op->first->sibling; # skip enter
1181 if (is_miniwhile($kid)) {
1182 my $top = $kid->first;
1183 my $name = $top->name;
1184 if ($name eq "and") {
1186 } elsif ($name eq "or") {
1188 } else { # no conditional -> while 1 or until 0
1189 return $self->deparse($top->first, 1) . " while 1";
1191 my $cond = $top->first;
1192 my $body = $cond->sibling->first; # skip lineseq
1193 $cond = $self->deparse($cond, 1);
1194 $body = $self->deparse($body, 1);
1195 return "$body $name $cond";
1200 for (; !null($kid); $kid = $kid->sibling) {
1203 if ($cx > 0) { # inside an expression, (a do {} while for lineseq)
1204 return "do {\n\t" . $self->lineseq($op, @kids) . "\n\b}";
1206 my $lineseq = $self->lineseq($op, @kids);
1207 return (length ($lineseq) ? "$lineseq;" : "");
1211 sub pp_scope { scopeop(0, @_); }
1212 sub pp_lineseq { scopeop(0, @_); }
1213 sub pp_leave { scopeop(1, @_); }
1215 # This is a special case of scopeop and lineseq, for the case of the
1216 # main_root. The difference is that we print the output statements as
1217 # soon as we get them, for the sake of impatient users.
1221 local(@$self{qw'curstash warnings hints hinthash'})
1222 = @$self{qw'curstash warnings hints hinthash'};
1224 return if null $op->first; # Can happen, e.g., for Bytecode without -k
1225 for (my $kid = $op->first->sibling; !null($kid); $kid = $kid->sibling) {
1228 $self->walk_lineseq($op, \@kids,
1229 sub { print $self->indent($_[0].';');
1230 print "\n" unless $_[1] == $#kids;
1235 my ($self, $op, $kids, $callback) = @_;
1237 for (my $i = 0; $i < @kids; $i++) {
1239 if (is_state $kids[$i]) {
1240 $expr = $self->deparse($kids[$i++], 0);
1242 $callback->($expr, $i);
1246 if (is_for_loop($kids[$i])) {
1247 $callback->($expr . $self->for_loop($kids[$i], 0),
1248 $i += $kids[$i]->sibling->name eq "unstack" ? 2 : 1);
1251 $expr .= $self->deparse($kids[$i], (@kids != 1)/2);
1252 $expr =~ s/;\n?\z//;
1253 $callback->($expr, $i);
1257 # The BEGIN {} is used here because otherwise this code isn't executed
1258 # when you run B::Deparse on itself.
1260 BEGIN { map($globalnames{$_}++, "SIG", "STDIN", "STDOUT", "STDERR", "INC",
1261 "ENV", "ARGV", "ARGVOUT", "_"); }
1266 Carp::confess() unless ref($gv) eq "B::GV";
1267 my $stash = $gv->STASH->NAME;
1268 my $name = $gv->SAFENAME;
1269 if ($stash eq 'main' && $name =~ /^::/) {
1272 elsif (($stash eq 'main' && $globalnames{$name})
1273 or ($stash eq $self->{'curstash'} && !$globalnames{$name}
1274 && ($stash eq 'main' || $name !~ /::/))
1275 or $name =~ /^[^A-Za-z_:]/)
1279 $stash = $stash . "::";
1281 if ($name =~ /^(\^..|{)/) {
1282 $name = "{$name}"; # ${^WARNING_BITS}, etc and ${
1284 return $stash . $name;
1287 # Return the name to use for a stash variable.
1288 # If a lexical with the same name is in scope, it may need to be
1290 sub stash_variable {
1291 my ($self, $prefix, $name, $cx) = @_;
1293 return "$prefix$name" if $name =~ /::/;
1295 unless ($prefix eq '$' || $prefix eq '@' || #'
1296 $prefix eq '%' || $prefix eq '$#') {
1297 return "$prefix$name";
1300 if (defined $cx && $cx == 26) {
1301 if ($prefix eq '@' && $name =~ /^[^\w+-]$/) {
1302 return "$prefix\{$name}";
1305 if ($prefix eq '$#' && $name =~ /^[^\w+-]$/) {
1306 return "\$#{$name}";
1309 my $v = ($prefix eq '$#' ? '@' : $prefix) . $name;
1310 return $prefix .$self->{'curstash'}.'::'. $name if $self->lex_in_scope($v);
1311 return "$prefix$name";
1315 my ($self, $name) = @_;
1316 $self->populate_curcvlex() if !defined $self->{'curcvlex'};
1318 return 0 if !defined($self->{'curcop'});
1319 my $seq = $self->{'curcop'}->cop_seq;
1320 return 0 if !exists $self->{'curcvlex'}{$name};
1321 for my $a (@{$self->{'curcvlex'}{$name}}) {
1322 my ($st, $en) = @$a;
1323 return 1 if $seq > $st && $seq <= $en;
1328 sub populate_curcvlex {
1330 for (my $cv = $self->{'curcv'}; class($cv) eq "CV"; $cv = $cv->OUTSIDE) {
1331 my $padlist = $cv->PADLIST;
1332 # an undef CV still in lexical chain
1333 next if class($padlist) eq "SPECIAL";
1334 my @padlist = $padlist->ARRAY;
1335 my @ns = $padlist[0]->ARRAY;
1337 for (my $i=0; $i<@ns; ++$i) {
1338 next if class($ns[$i]) eq "SPECIAL";
1339 next if $ns[$i]->FLAGS & SVpad_OUR; # Skip "our" vars
1340 if (class($ns[$i]) eq "PV") {
1341 # Probably that pesky lexical @_
1344 my $name = $ns[$i]->PVX;
1345 my ($seq_st, $seq_en) =
1346 ($ns[$i]->FLAGS & SVf_FAKE)
1348 : ($ns[$i]->COP_SEQ_RANGE_LOW, $ns[$i]->COP_SEQ_RANGE_HIGH);
1350 push @{$self->{'curcvlex'}{$name}}, [$seq_st, $seq_en];
1355 sub find_scope_st { ((find_scope(@_))[0]); }
1356 sub find_scope_en { ((find_scope(@_))[1]); }
1358 # Recurses down the tree, looking for pad variable introductions and COPs
1360 my ($self, $op, $scope_st, $scope_en) = @_;
1361 carp("Undefined op in find_scope") if !defined $op;
1362 return ($scope_st, $scope_en) unless $op->flags & OPf_KIDS;
1365 while(my $op = shift @queue ) {
1366 for (my $o=$op->first; $$o; $o=$o->sibling) {
1367 if ($o->name =~ /^pad.v$/ && $o->private & OPpLVAL_INTRO) {
1368 my $s = int($self->padname_sv($o->targ)->COP_SEQ_RANGE_LOW);
1369 my $e = $self->padname_sv($o->targ)->COP_SEQ_RANGE_HIGH;
1370 $scope_st = $s if !defined($scope_st) || $s < $scope_st;
1371 $scope_en = $e if !defined($scope_en) || $e > $scope_en;
1372 return ($scope_st, $scope_en);
1374 elsif (is_state($o)) {
1375 my $c = $o->cop_seq;
1376 $scope_st = $c if !defined($scope_st) || $c < $scope_st;
1377 $scope_en = $c if !defined($scope_en) || $c > $scope_en;
1378 return ($scope_st, $scope_en);
1380 elsif ($o->flags & OPf_KIDS) {
1381 unshift (@queue, $o);
1386 return ($scope_st, $scope_en);
1389 # Returns a list of subs which should be inserted before the COP
1391 my ($self, $op, $out_seq) = @_;
1392 my $seq = $op->cop_seq;
1393 # If we have nephews, then our sequence number indicates
1394 # the cop_seq of the end of some sort of scope.
1395 if (class($op->sibling) ne "NULL" && $op->sibling->flags & OPf_KIDS
1396 and my $nseq = $self->find_scope_st($op->sibling) ) {
1399 $seq = $out_seq if defined($out_seq) && $out_seq < $seq;
1400 return $self->seq_subs($seq);
1404 my ($self, $seq) = @_;
1406 #push @text, "# ($seq)\n";
1408 return "" if !defined $seq;
1409 while (scalar(@{$self->{'subs_todo'}})
1410 and $seq > $self->{'subs_todo'}[0][0]) {
1411 push @text, $self->next_todo;
1416 # Notice how subs and formats are inserted between statements here;
1417 # also $[ assignments and pragmas.
1421 $self->{'curcop'} = $op;
1423 push @text, $self->cop_subs($op);
1424 my $stash = $op->stashpv;
1425 if ($stash ne $self->{'curstash'}) {
1426 push @text, "package $stash;\n";
1427 $self->{'curstash'} = $stash;
1430 if (OPpCONST_ARYBASE && $self->{'arybase'} != $op->arybase) {
1431 push @text, '$[ = '. $op->arybase .";\n";
1432 $self->{'arybase'} = $op->arybase;
1435 my $warnings = $op->warnings;
1437 if ($warnings->isa("B::SPECIAL") && $$warnings == 4) {
1438 $warning_bits = $warnings::Bits{"all"} & WARN_MASK;
1440 elsif ($warnings->isa("B::SPECIAL") && $$warnings == 5) {
1441 $warning_bits = $warnings::NONE;
1443 elsif ($warnings->isa("B::SPECIAL")) {
1444 $warning_bits = undef;
1447 $warning_bits = $warnings->PV & WARN_MASK;
1450 if (defined ($warning_bits) and
1451 !defined($self->{warnings}) || $self->{'warnings'} ne $warning_bits) {
1452 push @text, declare_warnings($self->{'warnings'}, $warning_bits);
1453 $self->{'warnings'} = $warning_bits;
1456 my $hints = $] < 5.008009 ? $op->private : $op->hints;
1457 if ($self->{'hints'} != $hints) {
1458 push @text, declare_hints($self->{'hints'}, $hints);
1459 $self->{'hints'} = $hints;
1462 # hack to check that the hint hash hasn't changed
1464 "@{[sort %{$self->{'hinthash'} || {}}]}"
1465 ne "@{[sort %{$op->hints_hash->HASH || {}}]}") {
1466 push @text, declare_hinthash($self->{'hinthash'}, $op->hints_hash->HASH, $self->{indent_size});
1467 $self->{'hinthash'} = $op->hints_hash->HASH;
1470 # This should go after of any branches that add statements, to
1471 # increase the chances that it refers to the same line it did in
1472 # the original program.
1473 if ($self->{'linenums'}) {
1474 push @text, "\f#line " . $op->line .
1475 ' "' . $op->file, qq'"\n';
1478 push @text, $op->label . ": " if $op->label;
1480 return join("", @text);
1483 sub declare_warnings {
1484 my ($from, $to) = @_;
1485 if (($to & WARN_MASK) eq (warnings::bits("all") & WARN_MASK)) {
1486 return "use warnings;\n";
1488 elsif (($to & WARN_MASK) eq ("\0"x length($to) & WARN_MASK)) {
1489 return "no warnings;\n";
1491 return "BEGIN {\${^WARNING_BITS} = ".perlstring($to)."}\n";
1495 my ($from, $to) = @_;
1496 my $use = $to & ~$from;
1497 my $no = $from & ~$to;
1499 for my $pragma (hint_pragmas($use)) {
1500 $decls .= "use $pragma;\n";
1502 for my $pragma (hint_pragmas($no)) {
1503 $decls .= "no $pragma;\n";
1508 # Internal implementation hints that the core sets automatically, so don't need
1509 # (or want) to be passed back to the user
1510 my %ignored_hints = (
1516 sub declare_hinthash {
1517 my ($from, $to, $indent) = @_;
1519 for my $key (keys %$to) {
1520 next if $ignored_hints{$key};
1521 if (!defined $from->{$key} or $from->{$key} ne $to->{$key}) {
1522 push @decls, qq(\$^H{'$key'} = q($to->{$key}););
1525 for my $key (keys %$from) {
1526 next if $ignored_hints{$key};
1527 if (!exists $to->{$key}) {
1528 push @decls, qq(delete \$^H{'$key'};);
1531 @decls or return '';
1532 return join("\n" . (" " x $indent), "BEGIN {", @decls) . "\n}\n";
1538 push @pragmas, "integer" if $bits & 0x1;
1539 push @pragmas, "strict 'refs'" if $bits & 0x2;
1540 push @pragmas, "bytes" if $bits & 0x8;
1544 sub pp_dbstate { pp_nextstate(@_) }
1545 sub pp_setstate { pp_nextstate(@_) }
1547 sub pp_unstack { return "" } # see also leaveloop
1549 my %feature_keywords = (
1550 # keyword => 'feature',
1555 default => 'switch',
1562 return $name if $name =~ /^CORE::/; # just in case
1563 if (exists $feature_keywords{$name}) {
1566 && $self->{'hinthash'}{"feature_$feature_keywords{$name}"}
1571 $name !~ /^(?:chom?p|exec|s(?:elect|ystem))\z/
1572 && !defined eval{prototype "CORE::$name"}
1575 exists $self->{subs_declared}{$name}
1577 exists &{"$self->{curstash}::$name"}
1579 return "CORE::$name"
1586 my($op, $cx, $name) = @_;
1587 return $self->keyword($name);
1592 my($op, $cx, $name) = @_;
1600 sub pp_wantarray { baseop(@_, "wantarray") }
1601 sub pp_fork { baseop(@_, "fork") }
1602 sub pp_wait { maybe_targmy(@_, \&baseop, "wait") }
1603 sub pp_getppid { maybe_targmy(@_, \&baseop, "getppid") }
1604 sub pp_time { maybe_targmy(@_, \&baseop, "time") }
1605 sub pp_tms { baseop(@_, "times") }
1606 sub pp_ghostent { baseop(@_, "gethostent") }
1607 sub pp_gnetent { baseop(@_, "getnetent") }
1608 sub pp_gprotoent { baseop(@_, "getprotoent") }
1609 sub pp_gservent { baseop(@_, "getservent") }
1610 sub pp_ehostent { baseop(@_, "endhostent") }
1611 sub pp_enetent { baseop(@_, "endnetent") }
1612 sub pp_eprotoent { baseop(@_, "endprotoent") }
1613 sub pp_eservent { baseop(@_, "endservent") }
1614 sub pp_gpwent { baseop(@_, "getpwent") }
1615 sub pp_spwent { baseop(@_, "setpwent") }
1616 sub pp_epwent { baseop(@_, "endpwent") }
1617 sub pp_ggrent { baseop(@_, "getgrent") }
1618 sub pp_sgrent { baseop(@_, "setgrent") }
1619 sub pp_egrent { baseop(@_, "endgrent") }
1620 sub pp_getlogin { baseop(@_, "getlogin") }
1622 sub POSTFIX () { 1 }
1624 # I couldn't think of a good short name, but this is the category of
1625 # symbolic unary operators with interesting precedence
1629 my($op, $cx, $name, $prec, $flags) = (@_, 0);
1630 my $kid = $op->first;
1631 $kid = $self->deparse($kid, $prec);
1632 return $self->maybe_parens(($flags & POSTFIX) ? "$kid$name" : "$name$kid",
1636 sub pp_preinc { pfixop(@_, "++", 23) }
1637 sub pp_predec { pfixop(@_, "--", 23) }
1638 sub pp_postinc { maybe_targmy(@_, \&pfixop, "++", 23, POSTFIX) }
1639 sub pp_postdec { maybe_targmy(@_, \&pfixop, "--", 23, POSTFIX) }
1640 sub pp_i_preinc { pfixop(@_, "++", 23) }
1641 sub pp_i_predec { pfixop(@_, "--", 23) }
1642 sub pp_i_postinc { maybe_targmy(@_, \&pfixop, "++", 23, POSTFIX) }
1643 sub pp_i_postdec { maybe_targmy(@_, \&pfixop, "--", 23, POSTFIX) }
1644 sub pp_complement { maybe_targmy(@_, \&pfixop, "~", 21) }
1646 sub pp_negate { maybe_targmy(@_, \&real_negate) }
1650 if ($op->first->name =~ /^(i_)?negate$/) {
1652 $self->pfixop($op, $cx, "-", 21.5);
1654 $self->pfixop($op, $cx, "-", 21);
1657 sub pp_i_negate { pp_negate(@_) }
1663 $self->pfixop($op, $cx, $self->keyword("not")." ", 4);
1665 $self->pfixop($op, $cx, "!", 21);
1671 my($op, $cx, $name) = @_;
1673 if ($op->flags & OPf_KIDS) {
1676 # this deals with 'boolkeys' right now
1677 return $self->deparse($kid,$cx);
1679 my $builtinname = $name;
1680 $builtinname =~ /^CORE::/ or $builtinname = "CORE::$name";
1681 if (defined prototype($builtinname)
1682 && prototype($builtinname) =~ /^;?\*/
1683 && $kid->name eq "rv2gv") {
1687 return $self->maybe_parens_unop($name, $kid, $cx);
1689 return $self->keyword($name)
1690 . ($op->flags & OPf_SPECIAL ? "()" : "");
1694 sub pp_chop { maybe_targmy(@_, \&unop, "chop") }
1695 sub pp_chomp { maybe_targmy(@_, \&unop, "chomp") }
1696 sub pp_schop { maybe_targmy(@_, \&unop, "chop") }
1697 sub pp_schomp { maybe_targmy(@_, \&unop, "chomp") }
1698 sub pp_defined { unop(@_, "defined") }
1699 sub pp_undef { unop(@_, "undef") }
1700 sub pp_study { unop(@_, "study") }
1701 sub pp_ref { unop(@_, "ref") }
1702 sub pp_pos { maybe_local(@_, unop(@_, "pos")) }
1704 sub pp_sin { maybe_targmy(@_, \&unop, "sin") }
1705 sub pp_cos { maybe_targmy(@_, \&unop, "cos") }
1706 sub pp_rand { maybe_targmy(@_, \&unop, "rand") }
1707 sub pp_srand { unop(@_, "srand") }
1708 sub pp_exp { maybe_targmy(@_, \&unop, "exp") }
1709 sub pp_log { maybe_targmy(@_, \&unop, "log") }
1710 sub pp_sqrt { maybe_targmy(@_, \&unop, "sqrt") }
1711 sub pp_int { maybe_targmy(@_, \&unop, "int") }
1712 sub pp_hex { maybe_targmy(@_, \&unop, "hex") }
1713 sub pp_oct { maybe_targmy(@_, \&unop, "oct") }
1714 sub pp_abs { maybe_targmy(@_, \&unop, "abs") }
1716 sub pp_length { maybe_targmy(@_, \&unop, "length") }
1717 sub pp_ord { maybe_targmy(@_, \&unop, "ord") }
1718 sub pp_chr { maybe_targmy(@_, \&unop, "chr") }
1720 sub pp_each { unop(@_, "each") }
1721 sub pp_values { unop(@_, "values") }
1722 sub pp_keys { unop(@_, "keys") }
1723 { no strict 'refs'; *{"pp_r$_"} = *{"pp_$_"} for qw< keys each values >; }
1725 # no name because its an optimisation op that has no keyword
1728 sub pp_aeach { unop(@_, "each") }
1729 sub pp_avalues { unop(@_, "values") }
1730 sub pp_akeys { unop(@_, "keys") }
1731 sub pp_pop { unop(@_, "pop") }
1732 sub pp_shift { unop(@_, "shift") }
1734 sub pp_caller { unop(@_, "caller") }
1735 sub pp_reset { unop(@_, "reset") }
1736 sub pp_exit { unop(@_, "exit") }
1737 sub pp_prototype { unop(@_, "prototype") }
1739 sub pp_close { unop(@_, "close") }
1740 sub pp_fileno { unop(@_, "fileno") }
1741 sub pp_umask { unop(@_, "umask") }
1742 sub pp_untie { unop(@_, "untie") }
1743 sub pp_tied { unop(@_, "tied") }
1744 sub pp_dbmclose { unop(@_, "dbmclose") }
1745 sub pp_getc { unop(@_, "getc") }
1746 sub pp_eof { unop(@_, "eof") }
1747 sub pp_tell { unop(@_, "tell") }
1748 sub pp_getsockname { unop(@_, "getsockname") }
1749 sub pp_getpeername { unop(@_, "getpeername") }
1751 sub pp_chdir { maybe_targmy(@_, \&unop, "chdir") }
1752 sub pp_chroot { maybe_targmy(@_, \&unop, "chroot") }
1753 sub pp_readlink { unop(@_, "readlink") }
1754 sub pp_rmdir { maybe_targmy(@_, \&unop, "rmdir") }
1755 sub pp_readdir { unop(@_, "readdir") }
1756 sub pp_telldir { unop(@_, "telldir") }
1757 sub pp_rewinddir { unop(@_, "rewinddir") }
1758 sub pp_closedir { unop(@_, "closedir") }
1759 sub pp_getpgrp { maybe_targmy(@_, \&unop, "getpgrp") }
1760 sub pp_localtime { unop(@_, "localtime") }
1761 sub pp_gmtime { unop(@_, "gmtime") }
1762 sub pp_alarm { unop(@_, "alarm") }
1763 sub pp_sleep { maybe_targmy(@_, \&unop, "sleep") }
1765 sub pp_dofile { unop(@_, "do") }
1766 sub pp_entereval { unop(@_, "eval") }
1768 sub pp_ghbyname { unop(@_, "gethostbyname") }
1769 sub pp_gnbyname { unop(@_, "getnetbyname") }
1770 sub pp_gpbyname { unop(@_, "getprotobyname") }
1771 sub pp_shostent { unop(@_, "sethostent") }
1772 sub pp_snetent { unop(@_, "setnetent") }
1773 sub pp_sprotoent { unop(@_, "setprotoent") }
1774 sub pp_sservent { unop(@_, "setservent") }
1775 sub pp_gpwnam { unop(@_, "getpwnam") }
1776 sub pp_gpwuid { unop(@_, "getpwuid") }
1777 sub pp_ggrnam { unop(@_, "getgrnam") }
1778 sub pp_ggrgid { unop(@_, "getgrgid") }
1780 sub pp_lock { unop(@_, "lock") }
1782 sub pp_continue { unop(@_, "continue"); }
1783 sub pp_break { unop(@_, "break"); }
1787 my($op, $cx, $givwhen) = @_;
1789 my $enterop = $op->first;
1791 if ($enterop->flags & OPf_SPECIAL) {
1792 $head = $self->keyword("default");
1793 $block = $self->deparse($enterop->first, 0);
1796 my $cond = $enterop->first;
1797 my $cond_str = $self->deparse($cond, 1);
1798 $head = "$givwhen ($cond_str)";
1799 $block = $self->deparse($cond->sibling, 0);
1807 sub pp_leavegiven { givwhen(@_, $_[0]->keyword("given")); }
1808 sub pp_leavewhen { givwhen(@_, $_[0]->keyword("when")); }
1814 if ($op->private & OPpEXISTS_SUB) {
1815 # Checking for the existence of a subroutine
1816 return $self->maybe_parens_func("exists",
1817 $self->pp_rv2cv($op->first, 16), $cx, 16);
1819 if ($op->flags & OPf_SPECIAL) {
1820 # Array element, not hash element
1821 return $self->maybe_parens_func("exists",
1822 $self->pp_aelem($op->first, 16), $cx, 16);
1824 return $self->maybe_parens_func("exists", $self->pp_helem($op->first, 16),
1832 if ($op->private & OPpSLICE) {
1833 if ($op->flags & OPf_SPECIAL) {
1834 # Deleting from an array, not a hash
1835 return $self->maybe_parens_func("delete",
1836 $self->pp_aslice($op->first, 16),
1839 return $self->maybe_parens_func("delete",
1840 $self->pp_hslice($op->first, 16),
1843 if ($op->flags & OPf_SPECIAL) {
1844 # Deleting from an array, not a hash
1845 return $self->maybe_parens_func("delete",
1846 $self->pp_aelem($op->first, 16),
1849 return $self->maybe_parens_func("delete",
1850 $self->pp_helem($op->first, 16),
1858 my $opname = $op->flags & OPf_SPECIAL ? 'CORE::require' : 'require';
1859 if (class($op) eq "UNOP" and $op->first->name eq "const"
1860 and $op->first->private & OPpCONST_BARE)
1862 my $name = $self->const_sv($op->first)->PV;
1865 return "$opname $name";
1867 $self->unop($op, $cx, $op->first->private & OPpCONST_NOVER ? "no" : $opname);
1874 my $kid = $op->first;
1875 if (not null $kid->sibling) {
1876 # XXX Was a here-doc
1877 return $self->dquote($op);
1879 $self->unop(@_, "scalar");
1886 return $self->{'curcv'}->PADLIST->ARRAYelt(1)->ARRAYelt($targ);
1889 sub anon_hash_or_list {
1893 my($pre, $post) = @{{"anonlist" => ["[","]"],
1894 "anonhash" => ["{","}"]}->{$op->name}};
1896 $op = $op->first->sibling; # skip pushmark
1897 for (; !null($op); $op = $op->sibling) {
1898 $expr = $self->deparse($op, 6);
1901 if ($pre eq "{" and $cx < 1) {
1902 # Disambiguate that it's not a block
1905 return $pre . join(", ", @exprs) . $post;
1911 if ($op->flags & OPf_SPECIAL) {
1912 return $self->anon_hash_or_list($op, $cx);
1914 warn "Unexpected op pp_" . $op->name() . " without OPf_SPECIAL";
1918 *pp_anonhash = \&pp_anonlist;
1923 my $kid = $op->first;
1924 if ($kid->name eq "null") {
1926 if (!null($kid->sibling) and
1927 $kid->sibling->name eq "anoncode") {
1928 return $self->e_anoncode({ code => $self->padval($kid->sibling->targ) });
1929 } elsif ($kid->name eq "pushmark") {
1930 my $sib_name = $kid->sibling->name;
1931 if ($sib_name =~ /^(pad|rv2)[ah]v$/
1932 and not $kid->sibling->flags & OPf_REF)
1934 # The @a in \(@a) isn't in ref context, but only when the
1936 return "\\(" . $self->pp_list($op->first) . ")";
1937 } elsif ($sib_name eq 'entersub') {
1938 my $text = $self->deparse($kid->sibling, 1);
1939 # Always show parens for \(&func()), but only with -p otherwise
1940 $text = "($text)" if $self->{'parens'}
1941 or $kid->sibling->private & OPpENTERSUB_AMPER;
1946 $self->pfixop($op, $cx, "\\", 20);
1950 my ($self, $info) = @_;
1951 my $text = $self->deparse_sub($info->{code});
1952 return "sub " . $text;
1955 sub pp_srefgen { pp_refgen(@_) }
1960 my $kid = $op->first;
1961 $kid = $kid->first if $kid->name eq "rv2gv"; # <$fh>
1962 return "<" . $self->deparse($kid, 1) . ">" if is_scalar($kid);
1963 return $self->unop($op, $cx, "readline");
1969 return "<" . $self->gv_name($self->gv_or_padgv($op)) . ">";
1972 # Unary operators that can occur as pseudo-listops inside double quotes
1975 my($op, $cx, $name, $prec, $flags) = (@_, 0, 0);
1977 if ($op->flags & OPf_KIDS) {
1979 # If there's more than one kid, the first is an ex-pushmark.
1980 $kid = $kid->sibling if not null $kid->sibling;
1981 return $self->maybe_parens_unop($name, $kid, $cx);
1983 return $name . ($op->flags & OPf_SPECIAL ? "()" : "");
1987 sub pp_ucfirst { dq_unop(@_, "ucfirst") }
1988 sub pp_lcfirst { dq_unop(@_, "lcfirst") }
1989 sub pp_uc { dq_unop(@_, "uc") }
1990 sub pp_lc { dq_unop(@_, "lc") }
1991 sub pp_quotemeta { maybe_targmy(@_, \&dq_unop, "quotemeta") }
1995 my ($op, $cx, $name) = @_;
1996 if (class($op) eq "PVOP") {
1997 return "$name " . $op->pv;
1998 } elsif (class($op) eq "OP") {
2000 } elsif (class($op) eq "UNOP") {
2001 # Note -- loop exits are actually exempt from the
2002 # looks-like-a-func rule, but a few extra parens won't hurt
2003 return $self->maybe_parens_unop($name, $op->first, $cx);
2007 sub pp_last { loopex(@_, "last") }
2008 sub pp_next { loopex(@_, "next") }
2009 sub pp_redo { loopex(@_, "redo") }
2010 sub pp_goto { loopex(@_, "goto") }
2011 sub pp_dump { loopex(@_, $_[0]->keyword("dump")) }
2015 my($op, $cx, $name) = @_;
2016 if (class($op) eq "UNOP") {
2017 # Genuine `-X' filetests are exempt from the LLAFR, but not
2018 # l?stat(); for the sake of clarity, give'em all parens
2019 return $self->maybe_parens_unop($name, $op->first, $cx);
2020 } elsif (class($op) =~ /^(SV|PAD)OP$/) {
2021 return $self->maybe_parens_func($name, $self->pp_gv($op, 1), $cx, 16);
2022 } else { # I don't think baseop filetests ever survive ck_ftst, but...
2027 sub pp_lstat { ftst(@_, "lstat") }
2028 sub pp_stat { ftst(@_, "stat") }
2029 sub pp_ftrread { ftst(@_, "-R") }
2030 sub pp_ftrwrite { ftst(@_, "-W") }
2031 sub pp_ftrexec { ftst(@_, "-X") }
2032 sub pp_fteread { ftst(@_, "-r") }
2033 sub pp_ftewrite { ftst(@_, "-w") }
2034 sub pp_fteexec { ftst(@_, "-x") }
2035 sub pp_ftis { ftst(@_, "-e") }
2036 sub pp_fteowned { ftst(@_, "-O") }
2037 sub pp_ftrowned { ftst(@_, "-o") }
2038 sub pp_ftzero { ftst(@_, "-z") }
2039 sub pp_ftsize { ftst(@_, "-s") }
2040 sub pp_ftmtime { ftst(@_, "-M") }
2041 sub pp_ftatime { ftst(@_, "-A") }
2042 sub pp_ftctime { ftst(@_, "-C") }
2043 sub pp_ftsock { ftst(@_, "-S") }
2044 sub pp_ftchr { ftst(@_, "-c") }
2045 sub pp_ftblk { ftst(@_, "-b") }
2046 sub pp_ftfile { ftst(@_, "-f") }
2047 sub pp_ftdir { ftst(@_, "-d") }
2048 sub pp_ftpipe { ftst(@_, "-p") }
2049 sub pp_ftlink { ftst(@_, "-l") }
2050 sub pp_ftsuid { ftst(@_, "-u") }
2051 sub pp_ftsgid { ftst(@_, "-g") }
2052 sub pp_ftsvtx { ftst(@_, "-k") }
2053 sub pp_fttty { ftst(@_, "-t") }
2054 sub pp_fttext { ftst(@_, "-T") }
2055 sub pp_ftbinary { ftst(@_, "-B") }
2057 sub SWAP_CHILDREN () { 1 }
2058 sub ASSIGN () { 2 } # has OP= variant
2059 sub LIST_CONTEXT () { 4 } # Assignment is in list context
2065 my $name = $op->name;
2066 if ($name eq "concat" and $op->first->name eq "concat") {
2067 # avoid spurious `=' -- see comment in pp_concat
2070 if ($name eq "null" and class($op) eq "UNOP"
2071 and $op->first->name =~ /^(and|x?or)$/
2072 and null $op->first->sibling)
2074 # Like all conditional constructs, OP_ANDs and OP_ORs are topped
2075 # with a null that's used as the common end point of the two
2076 # flows of control. For precedence purposes, ignore it.
2077 # (COND_EXPRs have these too, but we don't bother with
2078 # their associativity).
2079 return assoc_class($op->first);
2081 return $name . ($op->flags & OPf_STACKED ? "=" : "");
2084 # Left associative operators, like `+', for which
2085 # $a + $b + $c is equivalent to ($a + $b) + $c
2088 %left = ('multiply' => 19, 'i_multiply' => 19,
2089 'divide' => 19, 'i_divide' => 19,
2090 'modulo' => 19, 'i_modulo' => 19,
2092 'add' => 18, 'i_add' => 18,
2093 'subtract' => 18, 'i_subtract' => 18,
2095 'left_shift' => 17, 'right_shift' => 17,
2097 'bit_or' => 12, 'bit_xor' => 12,
2099 'or' => 2, 'xor' => 2,
2103 sub deparse_binop_left {
2105 my($op, $left, $prec) = @_;
2106 if ($left{assoc_class($op)} && $left{assoc_class($left)}
2107 and $left{assoc_class($op)} == $left{assoc_class($left)})
2109 return $self->deparse($left, $prec - .00001);
2111 return $self->deparse($left, $prec);
2115 # Right associative operators, like `=', for which
2116 # $a = $b = $c is equivalent to $a = ($b = $c)
2119 %right = ('pow' => 22,
2120 'sassign=' => 7, 'aassign=' => 7,
2121 'multiply=' => 7, 'i_multiply=' => 7,
2122 'divide=' => 7, 'i_divide=' => 7,
2123 'modulo=' => 7, 'i_modulo=' => 7,
2125 'add=' => 7, 'i_add=' => 7,
2126 'subtract=' => 7, 'i_subtract=' => 7,
2128 'left_shift=' => 7, 'right_shift=' => 7,
2130 'bit_or=' => 7, 'bit_xor=' => 7,
2136 sub deparse_binop_right {
2138 my($op, $right, $prec) = @_;
2139 if ($right{assoc_class($op)} && $right{assoc_class($right)}
2140 and $right{assoc_class($op)} == $right{assoc_class($right)})
2142 return $self->deparse($right, $prec - .00001);
2144 return $self->deparse($right, $prec);
2150 my ($op, $cx, $opname, $prec, $flags) = (@_, 0);
2151 my $left = $op->first;
2152 my $right = $op->last;
2154 if ($op->flags & OPf_STACKED && $flags & ASSIGN) {
2158 if ($flags & SWAP_CHILDREN) {
2159 ($left, $right) = ($right, $left);
2161 $left = $self->deparse_binop_left($op, $left, $prec);
2162 $left = "($left)" if $flags & LIST_CONTEXT
2163 && $left !~ /^(my|our|local|)[\@\(]/;
2164 $right = $self->deparse_binop_right($op, $right, $prec);
2165 return $self->maybe_parens("$left $opname$eq $right", $cx, $prec);
2168 sub pp_add { maybe_targmy(@_, \&binop, "+", 18, ASSIGN) }
2169 sub pp_multiply { maybe_targmy(@_, \&binop, "*", 19, ASSIGN) }
2170 sub pp_subtract { maybe_targmy(@_, \&binop, "-",18, ASSIGN) }
2171 sub pp_divide { maybe_targmy(@_, \&binop, "/", 19, ASSIGN) }
2172 sub pp_modulo { maybe_targmy(@_, \&binop, "%", 19, ASSIGN) }
2173 sub pp_i_add { maybe_targmy(@_, \&binop, "+", 18, ASSIGN) }
2174 sub pp_i_multiply { maybe_targmy(@_, \&binop, "*", 19, ASSIGN) }
2175 sub pp_i_subtract { maybe_targmy(@_, \&binop, "-", 18, ASSIGN) }
2176 sub pp_i_divide { maybe_targmy(@_, \&binop, "/", 19, ASSIGN) }
2177 sub pp_i_modulo { maybe_targmy(@_, \&binop, "%", 19, ASSIGN) }
2178 sub pp_pow { maybe_targmy(@_, \&binop, "**", 22, ASSIGN) }
2180 sub pp_left_shift { maybe_targmy(@_, \&binop, "<<", 17, ASSIGN) }
2181 sub pp_right_shift { maybe_targmy(@_, \&binop, ">>", 17, ASSIGN) }
2182 sub pp_bit_and { maybe_targmy(@_, \&binop, "&", 13, ASSIGN) }
2183 sub pp_bit_or { maybe_targmy(@_, \&binop, "|", 12, ASSIGN) }
2184 sub pp_bit_xor { maybe_targmy(@_, \&binop, "^", 12, ASSIGN) }
2186 sub pp_eq { binop(@_, "==", 14) }
2187 sub pp_ne { binop(@_, "!=", 14) }
2188 sub pp_lt { binop(@_, "<", 15) }
2189 sub pp_gt { binop(@_, ">", 15) }
2190 sub pp_ge { binop(@_, ">=", 15) }
2191 sub pp_le { binop(@_, "<=", 15) }
2192 sub pp_ncmp { binop(@_, "<=>", 14) }
2193 sub pp_i_eq { binop(@_, "==", 14) }
2194 sub pp_i_ne { binop(@_, "!=", 14) }
2195 sub pp_i_lt { binop(@_, "<", 15) }
2196 sub pp_i_gt { binop(@_, ">", 15) }
2197 sub pp_i_ge { binop(@_, ">=", 15) }
2198 sub pp_i_le { binop(@_, "<=", 15) }
2199 sub pp_i_ncmp { binop(@_, "<=>", 14) }
2201 sub pp_seq { binop(@_, "eq", 14) }
2202 sub pp_sne { binop(@_, "ne", 14) }
2203 sub pp_slt { binop(@_, "lt", 15) }
2204 sub pp_sgt { binop(@_, "gt", 15) }
2205 sub pp_sge { binop(@_, "ge", 15) }
2206 sub pp_sle { binop(@_, "le", 15) }
2207 sub pp_scmp { binop(@_, "cmp", 14) }
2209 sub pp_sassign { binop(@_, "=", 7, SWAP_CHILDREN) }
2210 sub pp_aassign { binop(@_, "=", 7, SWAP_CHILDREN | LIST_CONTEXT) }
2213 my ($self, $op, $cx) = @_;
2214 if ($op->flags & OPf_SPECIAL) {
2215 return $self->deparse($op->last, $cx);
2218 binop(@_, "~~", 14);
2222 # `.' is special because concats-of-concats are optimized to save copying
2223 # by making all but the first concat stacked. The effect is as if the
2224 # programmer had written `($a . $b) .= $c', except legal.
2225 sub pp_concat { maybe_targmy(@_, \&real_concat) }
2229 my $left = $op->first;
2230 my $right = $op->last;
2233 if ($op->flags & OPf_STACKED and $op->first->name ne "concat") {
2237 $left = $self->deparse_binop_left($op, $left, $prec);
2238 $right = $self->deparse_binop_right($op, $right, $prec);
2239 return $self->maybe_parens("$left .$eq $right", $cx, $prec);
2242 # `x' is weird when the left arg is a list
2246 my $left = $op->first;
2247 my $right = $op->last;
2250 if ($op->flags & OPf_STACKED) {
2254 if (null($right)) { # list repeat; count is inside left-side ex-list
2255 my $kid = $left->first->sibling; # skip pushmark
2257 for (; !null($kid->sibling); $kid = $kid->sibling) {
2258 push @exprs, $self->deparse($kid, 6);
2261 $left = "(" . join(", ", @exprs). ")";
2263 $left = $self->deparse_binop_left($op, $left, $prec);
2265 $right = $self->deparse_binop_right($op, $right, $prec);
2266 return $self->maybe_parens("$left x$eq $right", $cx, $prec);
2271 my ($op, $cx, $type) = @_;
2272 my $left = $op->first;
2273 my $right = $left->sibling;
2274 $left = $self->deparse($left, 9);
2275 $right = $self->deparse($right, 9);
2276 return $self->maybe_parens("$left $type $right", $cx, 9);
2282 my $flip = $op->first;
2283 my $type = ($flip->flags & OPf_SPECIAL) ? "..." : "..";
2284 return $self->range($flip->first, $cx, $type);
2287 # one-line while/until is handled in pp_leave
2291 my ($op, $cx, $lowop, $lowprec, $highop, $highprec, $blockname) = @_;
2292 my $left = $op->first;
2293 my $right = $op->first->sibling;
2294 if ($cx < 1 and is_scope($right) and $blockname
2295 and $self->{'expand'} < 7)
2297 $left = $self->deparse($left, 1);
2298 $right = $self->deparse($right, 0);
2299 return "$blockname ($left) {\n\t$right\n\b}\cK";
2300 } elsif ($cx < 1 and $blockname and not $self->{'parens'}
2301 and $self->{'expand'} < 7) { # $b if $a
2302 $right = $self->deparse($right, 1);
2303 $left = $self->deparse($left, 1);
2304 return "$right $blockname $left";
2305 } elsif ($cx > $lowprec and $highop) { # $a && $b
2306 $left = $self->deparse_binop_left($op, $left, $highprec);
2307 $right = $self->deparse_binop_right($op, $right, $highprec);
2308 return $self->maybe_parens("$left $highop $right", $cx, $highprec);
2309 } else { # $a and $b
2310 $left = $self->deparse_binop_left($op, $left, $lowprec);
2311 $right = $self->deparse_binop_right($op, $right, $lowprec);
2312 return $self->maybe_parens("$left $lowop $right", $cx, $lowprec);
2316 sub pp_and { logop(@_, "and", 3, "&&", 11, "if") }
2317 sub pp_or { logop(@_, "or", 2, "||", 10, "unless") }
2318 sub pp_dor { logop(@_, "//", 10) }
2320 # xor is syntactically a logop, but it's really a binop (contrary to
2321 # old versions of opcode.pl). Syntax is what matters here.
2322 sub pp_xor { logop(@_, "xor", 2, "", 0, "") }
2326 my ($op, $cx, $opname) = @_;
2327 my $left = $op->first;
2328 my $right = $op->first->sibling->first; # skip sassign
2329 $left = $self->deparse($left, 7);
2330 $right = $self->deparse($right, 7);
2331 return $self->maybe_parens("$left $opname $right", $cx, 7);
2334 sub pp_andassign { logassignop(@_, "&&=") }
2335 sub pp_orassign { logassignop(@_, "||=") }
2336 sub pp_dorassign { logassignop(@_, "//=") }
2340 my($op, $cx, $name) = @_;
2342 my $parens = ($cx >= 5) || $self->{'parens'};
2343 my $kid = $op->first->sibling;
2344 return $self->keyword($name) if null $kid;
2346 $name = "socketpair" if $name eq "sockpair";
2347 my $fullname = $self->keyword($name);
2348 my $proto = prototype("CORE::$name");
2350 && $proto =~ /^;?\*/
2351 && $kid->name eq "rv2gv") {
2352 $first = $self->deparse($kid->first, 6);
2355 $first = $self->deparse($kid, 6);
2357 if ($name eq "chmod" && $first =~ /^\d+$/) {
2358 $first = sprintf("%#o", $first);
2360 $first = "+$first" if not $parens and substr($first, 0, 1) eq "(";
2361 push @exprs, $first;
2362 $kid = $kid->sibling;
2363 if (defined $proto && $proto =~ /^\*\*/ && $kid->name eq "rv2gv") {
2364 push @exprs, $self->deparse($kid->first, 6);
2365 $kid = $kid->sibling;
2367 for (; !null($kid); $kid = $kid->sibling) {
2368 push @exprs, $self->deparse($kid, 6);
2370 if ($name eq "reverse" && ($op->private & OPpREVERSE_INPLACE)) {
2371 return "$exprs[0] = $fullname"
2372 . ($parens ? "($exprs[0])" : " $exprs[0]");
2375 return "$fullname(" . join(", ", @exprs) . ")";
2377 return "$fullname " . join(", ", @exprs);
2381 sub pp_bless { listop(@_, "bless") }
2382 sub pp_atan2 { maybe_targmy(@_, \&listop, "atan2") }
2383 sub pp_substr { maybe_local(@_, listop(@_, "substr")) }
2384 sub pp_vec { maybe_local(@_, listop(@_, "vec")) }
2385 sub pp_index { maybe_targmy(@_, \&listop, "index") }
2386 sub pp_rindex { maybe_targmy(@_, \&listop, "rindex") }
2387 sub pp_sprintf { maybe_targmy(@_, \&listop, "sprintf") }
2388 sub pp_formline { listop(@_, "formline") } # see also deparse_format
2389 sub pp_crypt { maybe_targmy(@_, \&listop, "crypt") }
2390 sub pp_unpack { listop(@_, "unpack") }
2391 sub pp_pack { listop(@_, "pack") }
2392 sub pp_join { maybe_targmy(@_, \&listop, "join") }
2393 sub pp_splice { listop(@_, "splice") }
2394 sub pp_push { maybe_targmy(@_, \&listop, "push") }
2395 sub pp_unshift { maybe_targmy(@_, \&listop, "unshift") }
2396 sub pp_reverse { listop(@_, "reverse") }
2397 sub pp_warn { listop(@_, "warn") }
2398 sub pp_die { listop(@_, "die") }
2399 # Actually, return is exempt from the LLAFR (see examples in this very
2400 # module!), but for consistency's sake, ignore that fact
2401 sub pp_return { listop(@_, "return") }
2402 sub pp_open { listop(@_, "open") }
2403 sub pp_pipe_op { listop(@_, "pipe") }
2404 sub pp_tie { listop(@_, "tie") }
2405 sub pp_binmode { listop(@_, "binmode") }
2406 sub pp_dbmopen { listop(@_, "dbmopen") }
2407 sub pp_sselect { listop(@_, "select") }
2408 sub pp_select { listop(@_, "select") }
2409 sub pp_read { listop(@_, "read") }
2410 sub pp_sysopen { listop(@_, "sysopen") }
2411 sub pp_sysseek { listop(@_, "sysseek") }
2412 sub pp_sysread { listop(@_, "sysread") }
2413 sub pp_syswrite { listop(@_, "syswrite") }
2414 sub pp_send { listop(@_, "send") }
2415 sub pp_recv { listop(@_, "recv") }
2416 sub pp_seek { listop(@_, "seek") }
2417 sub pp_fcntl { listop(@_, "fcntl") }
2418 sub pp_ioctl { listop(@_, "ioctl") }
2419 sub pp_flock { maybe_targmy(@_, \&listop, "flock") }
2420 sub pp_socket { listop(@_, "socket") }
2421 sub pp_sockpair { listop(@_, "sockpair") }
2422 sub pp_bind { listop(@_, "bind") }
2423 sub pp_connect { listop(@_, "connect") }
2424 sub pp_listen { listop(@_, "listen") }
2425 sub pp_accept { listop(@_, "accept") }
2426 sub pp_shutdown { listop(@_, "shutdown") }
2427 sub pp_gsockopt { listop(@_, "getsockopt") }
2428 sub pp_ssockopt { listop(@_, "setsockopt") }
2429 sub pp_chown { maybe_targmy(@_, \&listop, "chown") }
2430 sub pp_unlink { maybe_targmy(@_, \&listop, "unlink") }
2431 sub pp_chmod { maybe_targmy(@_, \&listop, "chmod") }
2432 sub pp_utime { maybe_targmy(@_, \&listop, "utime") }
2433 sub pp_rename { maybe_targmy(@_, \&listop, "rename") }
2434 sub pp_link { maybe_targmy(@_, \&listop, "link") }
2435 sub pp_symlink { maybe_targmy(@_, \&listop, "symlink") }
2436 sub pp_mkdir { maybe_targmy(@_, \&listop, "mkdir") }
2437 sub pp_open_dir { listop(@_, "opendir") }
2438 sub pp_seekdir { listop(@_, "seekdir") }
2439 sub pp_waitpid { maybe_targmy(@_, \&listop, "waitpid") }
2440 sub pp_system { maybe_targmy(@_, \&listop, "system") }
2441 sub pp_exec { maybe_targmy(@_, \&listop, "exec") }
2442 sub pp_kill { maybe_targmy(@_, \&listop, "kill") }
2443 sub pp_setpgrp { maybe_targmy(@_, \&listop, "setpgrp") }
2444 sub pp_getpriority { maybe_targmy(@_, \&listop, "getpriority") }
2445 sub pp_setpriority { maybe_targmy(@_, \&listop, "setpriority") }
2446 sub pp_shmget { listop(@_, "shmget") }
2447 sub pp_shmctl { listop(@_, "shmctl") }
2448 sub pp_shmread { listop(@_, "shmread") }
2449 sub pp_shmwrite { listop(@_, "shmwrite") }
2450 sub pp_msgget { listop(@_, "msgget") }
2451 sub pp_msgctl { listop(@_, "msgctl") }
2452 sub pp_msgsnd { listop(@_, "msgsnd") }
2453 sub pp_msgrcv { listop(@_, "msgrcv") }
2454 sub pp_semget { listop(@_, "semget") }
2455 sub pp_semctl { listop(@_, "semctl") }
2456 sub pp_semop { listop(@_, "semop") }
2457 sub pp_ghbyaddr { listop(@_, "gethostbyaddr") }
2458 sub pp_gnbyaddr { listop(@_, "getnetbyaddr") }
2459 sub pp_gpbynumber { listop(@_, "getprotobynumber") }
2460 sub pp_gsbyname { listop(@_, "getservbyname") }
2461 sub pp_gsbyport { listop(@_, "getservbyport") }
2462 sub pp_syscall { listop(@_, "syscall") }
2467 my $text = $self->dq($op->first->sibling); # skip pushmark
2468 if ($text =~ /^\$?(\w|::|\`)+$/ # could look like a readline
2469 or $text =~ /[<>]/) {
2470 return 'glob(' . single_delim('qq', '"', $text) . ')';
2472 return '<' . $text . '>';
2476 # Truncate is special because OPf_SPECIAL makes a bareword first arg
2477 # be a filehandle. This could probably be better fixed in the core
2478 # by moving the GV lookup into ck_truc.
2484 my $parens = ($cx >= 5) || $self->{'parens'};
2485 my $kid = $op->first->sibling;
2487 if ($op->flags & OPf_SPECIAL) {
2488 # $kid is an OP_CONST
2489 $fh = $self->const_sv($kid)->PV;
2491 $fh = $self->deparse($kid, 6);
2492 $fh = "+$fh" if not $parens and substr($fh, 0, 1) eq "(";
2494 my $len = $self->deparse($kid->sibling, 6);
2495 my $name = $self->keyword('truncate');
2497 return "$name($fh, $len)";
2499 return "$name $fh, $len";
2505 my($op, $cx, $name) = @_;
2507 my $kid = $op->first->sibling;
2509 if ($op->flags & OPf_STACKED) {
2511 $indir = $indir->first; # skip rv2gv
2512 if (is_scope($indir)) {
2513 $indir = "{" . $self->deparse($indir, 0) . "}";
2514 $indir = "{;}" if $indir eq "{}";
2515 } elsif ($indir->name eq "const" && $indir->private & OPpCONST_BARE) {
2516 $indir = $self->const_sv($indir)->PV;
2518 $indir = $self->deparse($indir, 24);
2520 $indir = $indir . " ";
2521 $kid = $kid->sibling;
2523 if ($name eq "sort" && $op->private & (OPpSORT_NUMERIC | OPpSORT_INTEGER)) {
2524 $indir = ($op->private & OPpSORT_DESCEND) ? '{$b <=> $a} '
2527 elsif ($name eq "sort" && $op->private & OPpSORT_DESCEND) {
2528 $indir = '{$b cmp $a} ';
2530 for (; !null($kid); $kid = $kid->sibling) {
2531 $expr = $self->deparse($kid, 6);
2535 if ($name eq "sort" && $op->private & OPpSORT_REVERSE) {
2536 $name2 = $self->keyword('reverse') . ' ' . $self->keyword('sort');
2538 else { $name2 = $self->keyword($name) }
2539 if ($name eq "sort" && ($op->private & OPpSORT_INPLACE)) {
2540 return "$exprs[0] = $name2 $indir $exprs[0]";
2543 my $args = $indir . join(", ", @exprs);
2544 if ($indir ne "" and $name eq "sort") {
2545 # We don't want to say "sort(f 1, 2, 3)", since perl -w will
2546 # give bareword warnings in that case. Therefore if context
2547 # requires, we'll put parens around the outside "(sort f 1, 2,
2548 # 3)". Unfortunately, we'll currently think the parens are
2549 # necessary more often that they really are, because we don't
2550 # distinguish which side of an assignment we're on.
2552 return "($name2 $args)";
2554 return "$name2 $args";
2557 return $self->maybe_parens_func($name2, $args, $cx, 5);
2562 sub pp_prtf { indirop(@_, "printf") }
2563 sub pp_print { indirop(@_, "print") }
2564 sub pp_say { indirop(@_, "say") }
2565 sub pp_sort { indirop(@_, "sort") }
2569 my($op, $cx, $name) = @_;
2571 my $kid = $op->first; # this is the (map|grep)start
2572 $kid = $kid->first->sibling; # skip a pushmark
2573 my $code = $kid->first; # skip a null
2574 if (is_scope $code) {
2575 $code = "{" . $self->deparse($code, 0) . "} ";
2577 $code = $self->deparse($code, 24) . ", ";
2579 $kid = $kid->sibling;
2580 for (; !null($kid); $kid = $kid->sibling) {
2581 $expr = $self->deparse($kid, 6);
2582 push @exprs, $expr if defined $expr;
2584 return $self->maybe_parens_func($name, $code . join(", ", @exprs), $cx, 5);
2587 sub pp_mapwhile { mapop(@_, "map") }
2588 sub pp_grepwhile { mapop(@_, "grep") }
2589 sub pp_mapstart { baseop(@_, "map") }
2590 sub pp_grepstart { baseop(@_, "grep") }
2596 my $kid = $op->first->sibling; # skip pushmark
2598 my $local = "either"; # could be local(...), my(...), state(...) or our(...)
2599 for ($lop = $kid; !null($lop); $lop = $lop->sibling) {
2600 # This assumes that no other private flags equal 128, and that
2601 # OPs that store things other than flags in their op_private,
2602 # like OP_AELEMFAST, won't be immediate children of a list.
2604 # OP_ENTERSUB can break this logic, so check for it.
2605 # I suspect that open and exit can too.
2607 if (!($lop->private & (OPpLVAL_INTRO|OPpOUR_INTRO)
2608 or $lop->name eq "undef")
2609 or $lop->name eq "entersub"
2610 or $lop->name eq "exit"
2611 or $lop->name eq "open")
2613 $local = ""; # or not
2616 if ($lop->name =~ /^pad[ash]v$/) {
2617 if ($lop->private & OPpPAD_STATE) { # state()
2618 ($local = "", last) if $local =~ /^(?:local|our|my)$/;
2621 ($local = "", last) if $local =~ /^(?:local|our|state)$/;
2624 } elsif ($lop->name =~ /^(gv|rv2)[ash]v$/
2625 && $lop->private & OPpOUR_INTRO
2626 or $lop->name eq "null" && $lop->first->name eq "gvsv"
2627 && $lop->first->private & OPpOUR_INTRO) { # our()
2628 ($local = "", last) if $local =~ /^(?:my|local|state)$/;
2630 } elsif ($lop->name ne "undef"
2631 # specifically avoid the "reverse sort" optimisation,
2632 # where "reverse" is nullified
2633 && !($lop->name eq 'sort' && ($lop->flags & OPpSORT_REVERSE)))
2636 ($local = "", last) if $local =~ /^(?:my|our|state)$/;
2640 $local = "" if $local eq "either"; # no point if it's all undefs
2641 return $self->deparse($kid, $cx) if null $kid->sibling and not $local;
2642 for (; !null($kid); $kid = $kid->sibling) {
2644 if (class($kid) eq "UNOP" and $kid->first->name eq "gvsv") {
2649 $self->{'avoid_local'}{$$lop}++;
2650 $expr = $self->deparse($kid, 6);
2651 delete $self->{'avoid_local'}{$$lop};
2653 $expr = $self->deparse($kid, 6);
2658 return "$local(" . join(", ", @exprs) . ")";
2660 return $self->maybe_parens( join(", ", @exprs), $cx, 6);
2664 sub is_ifelse_cont {
2666 return ($op->name eq "null" and class($op) eq "UNOP"
2667 and $op->first->name =~ /^(and|cond_expr)$/
2668 and is_scope($op->first->first->sibling));
2674 my $cond = $op->first;
2675 my $true = $cond->sibling;
2676 my $false = $true->sibling;
2677 my $cuddle = $self->{'cuddle'};
2678 unless ($cx < 1 and (is_scope($true) and $true->name ne "null") and
2679 (is_scope($false) || is_ifelse_cont($false))
2680 and $self->{'expand'} < 7) {
2681 $cond = $self->deparse($cond, 8);
2682 $true = $self->deparse($true, 6);
2683 $false = $self->deparse($false, 8);
2684 return $self->maybe_parens("$cond ? $true : $false", $cx, 8);
2687 $cond = $self->deparse($cond, 1);
2688 $true = $self->deparse($true, 0);
2689 my $head = "if ($cond) {\n\t$true\n\b}";
2691 while (!null($false) and is_ifelse_cont($false)) {
2692 my $newop = $false->first;
2693 my $newcond = $newop->first;
2694 my $newtrue = $newcond->sibling;
2695 $false = $newtrue->sibling; # last in chain is OP_AND => no else
2696 if ($newcond->name eq "lineseq")
2698 # lineseq to ensure correct line numbers in elsif()
2699 # Bug #37302 fixed by change #33710.
2700 $newcond = $newcond->first->sibling;
2702 $newcond = $self->deparse($newcond, 1);
2703 $newtrue = $self->deparse($newtrue, 0);
2704 push @elsifs, "elsif ($newcond) {\n\t$newtrue\n\b}";
2706 if (!null($false)) {
2707 $false = $cuddle . "else {\n\t" .
2708 $self->deparse($false, 0) . "\n\b}\cK";
2712 return $head . join($cuddle, "", @elsifs) . $false;
2716 my ($self, $op, $cx) = @_;
2717 my $cond = $op->first;
2718 my $true = $cond->sibling;
2720 return $self->deparse($true, $cx);
2725 my($op, $cx, $init) = @_;
2726 my $enter = $op->first;
2727 my $kid = $enter->sibling;
2728 local(@$self{qw'curstash warnings hints hinthash'})
2729 = @$self{qw'curstash warnings hints hinthash'};
2734 if ($kid->name eq "lineseq") { # bare or infinite loop
2735 if ($kid->last->name eq "unstack") { # infinite
2736 $head = "while (1) "; # Can't use for(;;) if there's a continue
2742 } elsif ($enter->name eq "enteriter") { # foreach
2743 my $ary = $enter->first->sibling; # first was pushmark
2744 my $var = $ary->sibling;
2745 if ($ary->name eq 'null' and $enter->private & OPpITER_REVERSED) {
2746 # "reverse" was optimised away
2747 $ary = listop($self, $ary->first->sibling, 1, 'reverse');
2748 } elsif ($enter->flags & OPf_STACKED
2749 and not null $ary->first->sibling->sibling)
2751 $ary = $self->deparse($ary->first->sibling, 9) . " .. " .
2752 $self->deparse($ary->first->sibling->sibling, 9);
2754 $ary = $self->deparse($ary, 1);
2757 if (($enter->flags & OPf_SPECIAL) && ($] < 5.009)) {
2758 # thread special var, under 5005threads
2759 $var = $self->pp_threadsv($enter, 1);
2760 } else { # regular my() variable
2761 $var = $self->pp_padsv($enter, 1);
2763 } elsif ($var->name eq "rv2gv") {
2764 $var = $self->pp_rv2sv($var, 1);
2765 if ($enter->private & OPpOUR_INTRO) {
2766 # our declarations don't have package names
2767 $var =~ s/^(.).*::/$1/;
2770 } elsif ($var->name eq "gv") {
2771 $var = "\$" . $self->deparse($var, 1);
2773 $body = $kid->first->first->sibling; # skip OP_AND and OP_ITER
2774 if (!is_state $body->first and $body->first->name ne "stub") {
2775 confess unless $var eq '$_';
2776 $body = $body->first;
2777 return $self->deparse($body, 2) . " foreach ($ary)";
2779 $head = "foreach $var ($ary) ";
2780 } elsif ($kid->name eq "null") { # while/until
2782 my $name = {"and" => "while", "or" => "until"}->{$kid->name};
2783 $cond = $self->deparse($kid->first, 1);
2784 $head = "$name ($cond) ";
2785 $body = $kid->first->sibling;
2786 } elsif ($kid->name eq "stub") { # bare and empty
2787 return "{;}"; # {} could be a hashref
2789 # If there isn't a continue block, then the next pointer for the loop
2790 # will point to the unstack, which is kid's last child, except
2791 # in a bare loop, when it will point to the leaveloop. When neither of
2792 # these conditions hold, then the second-to-last child is the continue
2793 # block (or the last in a bare loop).
2794 my $cont_start = $enter->nextop;
2796 if ($$cont_start != $$op && ${$cont_start} != ${$body->last}) {
2798 $cont = $body->last;
2800 $cont = $body->first;
2801 while (!null($cont->sibling->sibling)) {
2802 $cont = $cont->sibling;
2805 my $state = $body->first;
2806 my $cuddle = $self->{'cuddle'};
2808 for (; $$state != $$cont; $state = $state->sibling) {
2809 push @states, $state;
2811 $body = $self->lineseq(undef, @states);
2812 if (defined $cond and not is_scope $cont and $self->{'expand'} < 3) {
2813 $head = "for ($init; $cond; " . $self->deparse($cont, 1) .") ";
2816 $cont = $cuddle . "continue {\n\t" .
2817 $self->deparse($cont, 0) . "\n\b}\cK";
2820 return "" if !defined $body;
2822 $head = "for ($init; $cond;) ";
2825 $body = $self->deparse($body, 0);
2827 $body =~ s/;?$/;\n/;
2829 return $head . "{\n\t" . $body . "\b}" . $cont;
2832 sub pp_leaveloop { shift->loop_common(@_, "") }
2837 my $init = $self->deparse($op, 1);
2838 my $s = $op->sibling;
2839 my $ll = $s->name eq "unstack" ? $s->sibling : $s->first->sibling;
2840 return $self->loop_common($ll, $cx, $init);
2845 return "eval {\n\t" . $self->pp_leave(@_) . "\n\b}";
2848 BEGIN { for (qw[ const stringify rv2sv list glob ]) {
2849 eval "sub OP_\U$_ () { " . opnumber($_) . "}"
2855 if (class($op) eq "OP") {
2857 return $self->{'ex_const'} if $op->targ == OP_CONST;
2858 } elsif ($op->first->name eq "pushmark") {
2859 return $self->pp_list($op, $cx);
2860 } elsif ($op->first->name eq "enter") {
2861 return $self->pp_leave($op, $cx);
2862 } elsif ($op->first->name eq "leave") {
2863 return $self->pp_leave($op->first, $cx);
2864 } elsif ($op->first->name eq "scope") {
2865 return $self->pp_scope($op->first, $cx);
2866 } elsif ($op->targ == OP_STRINGIFY) {
2867 return $self->dquote($op, $cx);
2868 } elsif ($op->targ == OP_GLOB) {
2869 return $self->pp_glob(
2870 $op->first # entersub
2876 } elsif (!null($op->first->sibling) and
2877 $op->first->sibling->name eq "readline" and
2878 $op->first->sibling->flags & OPf_STACKED) {
2879 return $self->maybe_parens($self->deparse($op->first, 7) . " = "
2880 . $self->deparse($op->first->sibling, 7),
2882 } elsif (!null($op->first->sibling) and
2883 $op->first->sibling->name eq "trans" and
2884 $op->first->sibling->flags & OPf_STACKED) {
2885 return $self->maybe_parens($self->deparse($op->first, 20) . " =~ "
2886 . $self->deparse($op->first->sibling, 20),
2888 } elsif ($op->flags & OPf_SPECIAL && $cx < 1 && !$op->targ) {
2889 return "do {\n\t". $self->deparse($op->first, $cx) ."\n\b};";
2890 } elsif (!null($op->first->sibling) and
2891 $op->first->sibling->name eq "null" and
2892 class($op->first->sibling) eq "UNOP" and
2893 $op->first->sibling->first->flags & OPf_STACKED and
2894 $op->first->sibling->first->name eq "rcatline") {
2895 return $self->maybe_parens($self->deparse($op->first, 18) . " .= "
2896 . $self->deparse($op->first->sibling, 18),
2899 return $self->deparse($op->first, $cx);
2906 return $self->padname_sv($targ)->PVX;
2912 return substr($self->padname($op->targ), 1); # skip $/@/%
2918 return $self->maybe_my($op, $cx, $self->padname($op->targ));
2921 sub pp_padav { pp_padsv(@_) }
2922 sub pp_padhv { pp_padsv(@_) }
2924 my @threadsv_names = B::threadsv_names;
2928 return $self->maybe_local($op, $cx, "\$" . $threadsv_names[$op->targ]);
2934 if (class($op) eq "PADOP") {
2935 return $self->padval($op->padix);
2936 } else { # class($op) eq "SVOP"
2944 my $gv = $self->gv_or_padgv($op);
2945 return $self->maybe_local($op, $cx, $self->stash_variable("\$",
2946 $self->gv_name($gv), $cx));
2952 my $gv = $self->gv_or_padgv($op);
2953 return $self->gv_name($gv);
2956 sub pp_aelemfast_lex {
2959 my $name = $self->padname($op->targ);
2961 return $name . "[" . ($op->private + $self->{'arybase'}) . "]";
2967 # optimised PADAV, pre 5.15
2968 return $self->pp_aelemfast_lex(@_) if ($op->flags & OPf_SPECIAL);
2970 my $gv = $self->gv_or_padgv($op);
2971 my $name = $self->gv_name($gv);
2972 $name = $self->{'curstash'}."::$name"
2973 if $name !~ /::/ && $self->lex_in_scope('@'.$name);
2974 $name = '$' . $name;
2975 return $name . "[" . ($op->private + $self->{'arybase'}) . "]";
2980 my($op, $cx, $type) = @_;
2982 if (class($op) eq 'NULL' || !$op->can("first")) {
2983 carp("Unexpected op in pp_rv2x");
2986 my $kid = $op->first;
2987 if ($kid->name eq "gv") {
2988 return $self->stash_variable($type, $self->deparse($kid, 0), $cx);
2989 } elsif (is_scalar $kid) {
2990 my $str = $self->deparse($kid, 0);
2991 if ($str =~ /^\$([^\w\d])\z/) {
2992 # "$$+" isn't a legal way to write the scalar dereference
2993 # of $+, since the lexer can't tell you aren't trying to
2994 # do something like "$$ + 1" to get one more than your
2995 # PID. Either "${$+}" or "$${+}" are workable
2996 # disambiguations, but if the programmer did the former,
2997 # they'd be in the "else" clause below rather than here.
2998 # It's not clear if this should somehow be unified with
2999 # the code in dq and re_dq that also adds lexer
3000 # disambiguation braces.
3001 $str = '$' . "{$1}"; #'
3003 return $type . $str;
3005 return $type . "{" . $self->deparse($kid, 0) . "}";
3009 sub pp_rv2sv { maybe_local(@_, rv2x(@_, "\$")) }
3010 sub pp_rv2hv { maybe_local(@_, rv2x(@_, "%")) }
3011 sub pp_rv2gv { maybe_local(@_, rv2x(@_, "*")) }
3017 if ($op->first->name eq "padav") {
3018 return $self->maybe_local($op, $cx, '$#' . $self->padany($op->first));
3020 return $self->maybe_local($op, $cx,
3021 $self->rv2x($op->first, $cx, '$#'));
3025 # skip down to the old, ex-rv2cv
3027 my ($self, $op, $cx) = @_;
3028 if (!null($op->first) && $op->first->name eq 'null' &&
3029 $op->first->targ eq OP_LIST)
3031 return $self->rv2x($op->first->first->sibling, $cx, "&")
3034 return $self->rv2x($op, $cx, "")
3040 my($cx, @list) = @_;
3041 my @a = map $self->const($_, 6), @list;
3046 } elsif ( @a > 2 and !grep(!/^-?\d+$/, @a)) {
3047 # collapse (-1,0,1,2) into (-1..2)
3048 my ($s, $e) = @a[0,-1];
3050 return $self->maybe_parens("$s..$e", $cx, 9)
3051 unless grep $i++ != $_, @a;
3053 return $self->maybe_parens(join(", ", @a), $cx, 6);
3059 my $kid = $op->first;
3060 if ($kid->name eq "const") { # constant list
3061 my $av = $self->const_sv($kid);
3062 return $self->list_const($cx, $av->ARRAY);
3064 return $self->maybe_local($op, $cx, $self->rv2x($op, $cx, "\@"));
3068 sub is_subscriptable {
3070 if ($op->name =~ /^[ahg]elem/) {
3072 } elsif ($op->name eq "entersub") {
3073 my $kid = $op->first;
3074 return 0 unless null $kid->sibling;
3076 $kid = $kid->sibling until null $kid->sibling;
3077 return 0 if is_scope($kid);
3079 return 0 if $kid->name eq "gv";
3080 return 0 if is_scalar($kid);
3081 return is_subscriptable($kid);
3087 sub elem_or_slice_array_name
3090 my ($array, $left, $padname, $allow_arrow) = @_;
3092 if ($array->name eq $padname) {
3093 return $self->padany($array);
3094 } elsif (is_scope($array)) { # ${expr}[0]
3095 return "{" . $self->deparse($array, 0) . "}";
3096 } elsif ($array->name eq "gv") {
3097 $array = $self->gv_name($self->gv_or_padgv($array));
3098 if ($array !~ /::/) {
3099 my $prefix = ($left eq '[' ? '@' : '%');
3100 $array = $self->{curstash}.'::'.$array
3101 if $self->lex_in_scope($prefix . $array);
3104 } elsif (!$allow_arrow || is_scalar $array) { # $x[0], $$x[0], ...
3105 return $self->deparse($array, 24);
3111 sub elem_or_slice_single_index
3116 $idx = $self->deparse($idx, 1);
3118 # Outer parens in an array index will confuse perl
3119 # if we're interpolating in a regular expression, i.e.
3120 # /$x$foo[(-1)]/ is *not* the same as /$x$foo[-1]/
3122 # If $self->{parens}, then an initial '(' will
3123 # definitely be paired with a final ')'. If
3124 # !$self->{parens}, the misleading parens won't
3125 # have been added in the first place.
3127 # [You might think that we could get "(...)...(...)"
3128 # where the initial and final parens do not match
3129 # each other. But we can't, because the above would
3130 # only happen if there's an infix binop between the
3131 # two pairs of parens, and *that* means that the whole
3132 # expression would be parenthesized as well.]
3134 $idx =~ s/^\((.*)\)$/$1/ if $self->{'parens'};
3136 # Hash-element braces will autoquote a bareword inside themselves.
3137 # We need to make sure that C<$hash{warn()}> doesn't come out as
3138 # C<$hash{warn}>, which has a quite different meaning. Currently
3139 # B::Deparse will always quote strings, even if the string was a
3140 # bareword in the original (i.e. the OPpCONST_BARE flag is ignored
3141 # for constant strings.) So we can cheat slightly here - if we see
3142 # a bareword, we know that it is supposed to be a function call.
3144 $idx =~ s/^([A-Za-z_]\w*)$/$1()/;
3151 my ($op, $cx, $left, $right, $padname) = @_;
3152 my($array, $idx) = ($op->first, $op->first->sibling);
3154 $idx = $self->elem_or_slice_single_index($idx);
3156 unless ($array->name eq $padname) { # Maybe this has been fixed
3157 $array = $array->first; # skip rv2av (or ex-rv2av in _53+)
3159 if (my $array_name=$self->elem_or_slice_array_name
3160 ($array, $left, $padname, 1)) {
3161 return "\$" . $array_name . $left . $idx . $right;
3163 # $x[20][3]{hi} or expr->[20]
3164 my $arrow = is_subscriptable($array) ? "" : "->";
3165 return $self->deparse($array, 24) . $arrow . $left . $idx . $right;
3170 sub pp_aelem { maybe_local(@_, elem(@_, "[", "]", "padav")) }
3171 sub pp_helem { maybe_local(@_, elem(@_, "{", "}", "padhv")) }
3176 my($glob, $part) = ($op->first, $op->last);
3177 $glob = $glob->first; # skip rv2gv
3178 $glob = $glob->first if $glob->name eq "rv2gv"; # this one's a bug
3179 my $scope = is_scope($glob);
3180 $glob = $self->deparse($glob, 0);
3181 $part = $self->deparse($part, 1);
3182 return "*" . ($scope ? "{$glob}" : $glob) . "{$part}";
3187 my ($op, $cx, $left, $right, $regname, $padname) = @_;
3189 my(@elems, $kid, $array, $list);
3190 if (class($op) eq "LISTOP") {
3192 } else { # ex-hslice inside delete()
3193 for ($kid = $op->first; !null $kid->sibling; $kid = $kid->sibling) {}
3197 $array = $array->first
3198 if $array->name eq $regname or $array->name eq "null";
3199 $array = $self->elem_or_slice_array_name($array,$left,$padname,0);
3200 $kid = $op->first->sibling; # skip pushmark
3201 if ($kid->name eq "list") {
3202 $kid = $kid->first->sibling; # skip list, pushmark
3203 for (; !null $kid; $kid = $kid->sibling) {
3204 push @elems, $self->deparse($kid, 6);
3206 $list = join(", ", @elems);
3208 $list = $self->elem_or_slice_single_index($kid);
3210 return "\@" . $array . $left . $list . $right;
3213 sub pp_aslice { maybe_local(@_, slice(@_, "[", "]", "rv2av", "padav")) }
3214 sub pp_hslice { maybe_local(@_, slice(@_, "{", "}", "rv2hv", "padhv")) }
3219 my $idx = $op->first;
3220 my $list = $op->last;
3222 $list = $self->deparse($list, 1);
3223 $idx = $self->deparse($idx, 1);
3224 return "($list)" . "[$idx]";
3229 return ($op->flags & OPf_WANT) == OPf_WANT_SCALAR;
3234 return ($op->flags & OPf_WANT) == OPf_WANT_LIST;
3240 my $kid = $op->first->sibling; # skip pushmark
3241 my($meth, $obj, @exprs);
3242 if ($kid->name eq "list" and want_list $kid) {
3243 # When an indirect object isn't a bareword but the args are in
3244 # parens, the parens aren't part of the method syntax (the LLAFR
3245 # doesn't apply), but they make a list with OPf_PARENS set that
3246 # doesn't get flattened by the append_elem that adds the method,
3247 # making a (object, arg1, arg2, ...) list where the object
3248 # usually is. This can be distinguished from
3249 # `($obj, $arg1, $arg2)->meth()' (which is legal if $arg2 is an
3250 # object) because in the later the list is in scalar context
3251 # as the left side of -> always is, while in the former
3252 # the list is in list context as method arguments always are.
3253 # (Good thing there aren't method prototypes!)
3254 $meth = $kid->sibling;
3255 $kid = $kid->first->sibling; # skip pushmark
3257 $kid = $kid->sibling;
3258 for (; not null $kid; $kid = $kid->sibling) {
3263 $kid = $kid->sibling;
3264 for (; !null ($kid->sibling) && $kid->name!~/^method(?:_named)?\z/;
3265 $kid = $kid->sibling) {
3271 if ($meth->name eq "method_named") {
3272 $meth = $self->const_sv($meth)->PV;
3274 $meth = $meth->first;
3275 if ($meth->name eq "const") {
3276 # As of 5.005_58, this case is probably obsoleted by the
3277 # method_named case above
3278 $meth = $self->const_sv($meth)->PV; # needs to be bare
3282 return { method => $meth, variable_method => ref($meth),
3283 object => $obj, args => \@exprs };
3286 # compat function only
3289 my $info = $self->_method(@_);
3290 return $self->e_method( $self->_method(@_) );
3294 my ($self, $info) = @_;
3295 my $obj = $self->deparse($info->{object}, 24);
3297 my $meth = $info->{method};
3298 $meth = $self->deparse($meth, 1) if $info->{variable_method};
3299 my $args = join(", ", map { $self->deparse($_, 6) } @{$info->{args}} );
3300 my $kid = $obj . "->" . $meth;
3302 return $kid . "(" . $args . ")"; # parens mandatory
3308 # returns "&" if the prototype doesn't match the args,
3309 # or ("", $args_after_prototype_demunging) if it does.
3312 return "&" if $self->{'noproto'};
3313 my($proto, @args) = @_;
3317 # An unbackslashed @ or % gobbles up the rest of the args
3318 1 while $proto =~ s/(?<!\\)([@%])[^\]]+$/$1/;
3320 $proto =~ s/^(\\?[\$\@&%*_]|\\\[[\$\@&%*]+\]|;)//;
3323 return "&" if @args;
3324 } elsif ($chr eq ";") {
3326 } elsif ($chr eq "@" or $chr eq "%") {
3327 push @reals, map($self->deparse($_, 6), @args);
3332 if ($chr eq "\$" || $chr eq "_") {
3333 if (want_scalar $arg) {
3334 push @reals, $self->deparse($arg, 6);
3338 } elsif ($chr eq "&") {
3339 if ($arg->name =~ /^(s?refgen|undef)$/) {
3340 push @reals, $self->deparse($arg, 6);
3344 } elsif ($chr eq "*") {
3345 if ($arg->name =~ /^s?refgen$/
3346 and $arg->first->first->name eq "rv2gv")
3348 $real = $arg->first->first; # skip refgen, null
3349 if ($real->first->name eq "gv") {
3350 push @reals, $self->deparse($real, 6);
3352 push @reals, $self->deparse($real->first, 6);
3357 } elsif (substr($chr, 0, 1) eq "\\") {
3359 if ($arg->name =~ /^s?refgen$/ and
3360 !null($real = $arg->first) and
3361 ($chr =~ /\$/ && is_scalar($real->first)
3363 && class($real->first->sibling) ne 'NULL'
3364 && $real->first->sibling->name
3367 && class($real->first->sibling) ne 'NULL'
3368 && $real->first->sibling->name
3370 #or ($chr =~ /&/ # This doesn't work
3371 # && $real->first->name eq "rv2cv")
3373 && $real->first->name eq "rv2gv")))
3375 push @reals, $self->deparse($real, 6);
3382 return "&" if $proto and !$doneok; # too few args and no `;'
3383 return "&" if @args; # too many args
3384 return ("", join ", ", @reals);
3390 return $self->e_method($self->_method($op, $cx))
3391 unless null $op->first->sibling;
3395 if ($op->flags & OPf_SPECIAL && !($op->flags & OPf_MOD)) {
3397 } elsif ($op->private & OPpENTERSUB_AMPER) {
3401 $kid = $kid->first->sibling; # skip ex-list, pushmark
3402 for (; not null $kid->sibling; $kid = $kid->sibling) {
3407 if (is_scope($kid)) {
3409 $kid = "{" . $self->deparse($kid, 0) . "}";
3410 } elsif ($kid->first->name eq "gv") {
3411 my $gv = $self->gv_or_padgv($kid->first);
3412 if (class($gv->CV) ne "SPECIAL") {
3413 $proto = $gv->CV->PV if $gv->CV->FLAGS & SVf_POK;
3415 $simple = 1; # only calls of named functions can be prototyped
3416 $kid = $self->deparse($kid, 24);
3418 if ($kid eq 'main::') {
3420 } elsif ($kid !~ /^(?:\w|::)(?:[\w\d]|::(?!\z))*\z/) {
3421 $kid = single_delim("q", "'", $kid) . '->';
3424 } elsif (is_scalar ($kid->first) && $kid->first->name ne 'rv2cv') {
3426 $kid = $self->deparse($kid, 24);
3429 my $arrow = is_subscriptable($kid->first) ? "" : "->";
3430 $kid = $self->deparse($kid, 24) . $arrow;
3433 # Doesn't matter how many prototypes there are, if
3434 # they haven't happened yet!
3438 no warnings 'uninitialized';
3439 $declared = exists $self->{'subs_declared'}{$kid}
3441 defined &{ ${$self->{'curstash'}."::"}{$kid} }
3443 $self->{'subs_deparsed'}{$self->{'curstash'}."::".$kid}
3444 && defined prototype $self->{'curstash'}."::".$kid
3446 if (!$declared && defined($proto)) {
3447 # Avoid "too early to check prototype" warning
3448 ($amper, $proto) = ('&');
3453 if ($declared and defined $proto and not $amper) {
3454 ($amper, $args) = $self->check_proto($proto, @exprs);
3455 if ($amper eq "&") {
3456 $args = join(", ", map($self->deparse($_, 6), @exprs));
3459 $args = join(", ", map($self->deparse($_, 6), @exprs));
3461 if ($prefix or $amper) {
3462 if ($op->flags & OPf_STACKED) {
3463 return $prefix . $amper . $kid . "(" . $args . ")";
3465 return $prefix . $amper. $kid;
3468 # It's a syntax error to call CORE::GLOBAL::foo with a prefix,
3469 # so it must have been translated from a keyword call. Translate
3471 $kid =~ s/^CORE::GLOBAL:://;
3473 my $dproto = defined($proto) ? $proto : "undefined";
3475 return "$kid(" . $args . ")";
3476 } elsif ($dproto eq "") {
3478 } elsif ($dproto eq "\$" and is_scalar($exprs[0])) {
3479 # is_scalar is an excessively conservative test here:
3480 # really, we should be comparing to the precedence of the
3481 # top operator of $exprs[0] (ala unop()), but that would
3482 # take some major code restructuring to do right.
3483 return $self->maybe_parens_func($kid, $args, $cx, 16);
3484 } elsif ($dproto ne '$' and defined($proto) || $simple) { #'
3485 return $self->maybe_parens_func($kid, $args, $cx, 5);
3487 return "$kid(" . $args . ")";
3492 sub pp_enterwrite { unop(@_, "write") }
3494 # escape things that cause interpolation in double quotes,
3495 # but not character escapes
3498 $str =~ s/(^|\G|[^\\])((?:\\\\)*)([\$\@]|\\[uUlLQE])/$1$2\\$3/g;
3506 # Matches any string which is balanced with respect to {braces}
3517 # the same, but treat $|, $), $( and $ at the end of the string differently
3531 (\(\?\??\{$bal\}\)) # $4
3537 /defined($4) && length($4) ? "$1$2$4" : "$1$2\\$3"/xeg;
3542 # This is for regular expressions with the /x modifier
3543 # We have to leave comments unmangled.
3544 sub re_uninterp_extended {
3557 ( \(\?\??\{$bal\}\) # $4 (skip over (?{}) and (??{}) blocks)
3558 | \#[^\n]* # (skip over comments)
3565 /defined($4) && length($4) ? "$1$2$4" : "$1$2\\$3"/xeg;
3571 my %unctrl = # portable to to EBCDIC
3573 "\c@" => '\c@', # unused
3600 "\c[" => '\c[', # unused
3601 "\c\\" => '\c\\', # unused
3602 "\c]" => '\c]', # unused
3603 "\c_" => '\c_', # unused
3606 # character escapes, but not delimiters that might need to be escaped
3607 sub escape_str { # ASCII, UTF8
3609 $str =~ s/(.)/ord($1) > 255 ? sprintf("\\x{%x}", ord($1)) : $1/eg;
3611 # $str =~ s/\cH/\\b/g; # \b means something different in a regex
3617 $str =~ s/([\cA-\cZ])/$unctrl{$1}/ge;
3618 $str =~ s/([[:^print:]])/sprintf("\\%03o", ord($1))/ge;
3622 # For regexes with the /x modifier.
3623 # Leave whitespace unmangled.
3624 sub escape_extended_re {
3626 $str =~ s/(.)/ord($1) > 255 ? sprintf("\\x{%x}", ord($1)) : $1/eg;
3627 $str =~ s/([[:^print:]])/
3628 ($1 =~ y! \t\n!!) ? $1 : sprintf("\\%03o", ord($1))/ge;
3629 $str =~ s/\n/\n\f/g;
3633 # Don't do this for regexen
3636 $str =~ s/\\/\\\\/g;
3640 # Remove backslashes which precede literal control characters,
3641 # to avoid creating ambiguity when we escape the latter.
3645 # the insane complexity here is due to the behaviour of "\c\"
3646 $str =~ s/(^|[^\\]|\\c\\)(?<!\\c)\\(\\\\)*(?=[[:^print:]])/$1$2/g;
3650 sub balanced_delim {
3652 my @str = split //, $str;
3653 my($ar, $open, $close, $fail, $c, $cnt, $last_bs);
3654 for $ar (['[',']'], ['(',')'], ['<','>'], ['{','}']) {
3655 ($open, $close) = @$ar;
3656 $fail = 0; $cnt = 0; $last_bs = 0;
3659 $fail = 1 if $last_bs;
3661 } elsif ($c eq $close) {
3662 $fail = 1 if $last_bs;
3670 $last_bs = $c eq '\\';
3672 $fail = 1 if $cnt != 0;
3673 return ($open, "$open$str$close") if not $fail;
3679 my($q, $default, $str) = @_;
3680 return "$default$str$default" if $default and index($str, $default) == -1;
3682 (my $succeed, $str) = balanced_delim($str);
3683 return "$q$str" if $succeed;
3685 for my $delim ('/', '"', '#') {
3686 return "$q$delim" . $str . $delim if index($str, $delim) == -1;
3689 $str =~ s/$default/\\$default/g;
3690 return "$default$str$default";
3698 BEGIN { $max_prec = int(0.999 + 8*length(pack("F", 42))*log(2)/log(10)); }
3700 # Split a floating point number into an integer mantissa and a binary
3701 # exponent. Assumes you've already made sure the number isn't zero or
3702 # some weird infinity or NaN.
3706 if ($f == int($f)) {
3707 while ($f % 2 == 0) {
3712 while ($f != int($f)) {
3717 my $mantissa = sprintf("%.0f", $f);
3718 return ($mantissa, $exponent);
3724 if ($self->{'use_dumper'}) {
3725 return $self->const_dumper($sv, $cx);
3727 if (class($sv) eq "SPECIAL") {
3728 # sv_undef, sv_yes, sv_no
3729 return ('undef', '1', $self->maybe_parens("!1", $cx, 21))[$$sv-1];
3731 if (class($sv) eq "NULL") {
3734 # convert a version object into the "v1.2.3" string in its V magic
3735 if ($sv->FLAGS & SVs_RMG) {
3736 for (my $mg = $sv->MAGIC; $mg; $mg = $mg->MOREMAGIC) {
3737 return $mg->PTR if $mg->TYPE eq 'V';
3741 if ($sv->FLAGS & SVf_IOK) {
3742 my $str = $sv->int_value;
3743 $str = $self->maybe_parens($str, $cx, 21) if $str < 0;
3745 } elsif ($sv->FLAGS & SVf_NOK) {
3748 if (pack("F", $nv) eq pack("F", 0)) {
3753 return $self->maybe_parens("-.0", $cx, 21);
3755 } elsif (1/$nv == 0) {
3758 return $self->maybe_parens("9**9**9", $cx, 22);
3761 return $self->maybe_parens("-9**9**9", $cx, 21);
3763 } elsif ($nv != $nv) {
3765 if (pack("F", $nv) eq pack("F", sin(9**9**9))) {
3767 return "sin(9**9**9)";
3768 } elsif (pack("F", $nv) eq pack("F", -sin(9**9**9))) {
3770 return $self->maybe_parens("-sin(9**9**9)", $cx, 21);
3773 my $hex = unpack("h*", pack("F", $nv));
3774 return qq'unpack("F", pack("h*", "$hex"))';
3777 # first, try the default stringification
3780 # failing that, try using more precision
3781 $str = sprintf("%.${max_prec}g", $nv);
3782 # if (pack("F", $str) ne pack("F", $nv)) {
3784 # not representable in decimal with whatever sprintf()
3785 # and atof() Perl is using here.
3786 my($mant, $exp) = split_float($nv);
3787 return $self->maybe_parens("$mant * 2**$exp", $cx, 19);
3790 $str = $self->maybe_parens($str, $cx, 21) if $nv < 0;
3792 } elsif ($sv->FLAGS & SVf_ROK && $sv->can("RV")) {
3794 if (class($ref) eq "AV") {
3795 return "[" . $self->list_const(2, $ref->ARRAY) . "]";
3796 } elsif (class($ref) eq "HV") {
3797 my %hash = $ref->ARRAY;
3799 for my $k (sort keys %hash) {
3800 push @elts, "$k => " . $self->const($hash{$k}, 6);
3802 return "{" . join(", ", @elts) . "}";
3803 } elsif (class($ref) eq "CV") {
3804 return "sub " . $self->deparse_sub($ref);
3806 if ($ref->FLAGS & SVs_SMG) {
3807 for (my $mg = $ref->MAGIC; $mg; $mg = $mg->MOREMAGIC) {
3808 if ($mg->TYPE eq 'r') {
3809 my $re = re_uninterp(escape_str(re_unback($mg->precomp)));
3810 return single_delim("qr", "", $re);
3815 return $self->maybe_parens("\\" . $self->const($ref, 20), $cx, 20);
3816 } elsif ($sv->FLAGS & SVf_POK) {
3818 if ($str =~ /[[:^print:]]/) {
3819 return single_delim("qq", '"', uninterp escape_str unback $str);
3821 return single_delim("q", "'", unback $str);
3831 my $ref = $sv->object_2svref();
3832 my $dumper = Data::Dumper->new([$$ref], ['$v']);
3833 $dumper->Purity(1)->Terse(1)->Deparse(1)->Indent(0)->Useqq(1)->Sortkeys(1);
3834 my $str = $dumper->Dump();
3835 if ($str =~ /^\$v/) {
3836 return '${my ' . $str . ' \$v}';
3846 # the constant could be in the pad (under useithreads)
3847 $sv = $self->padval($op->targ) unless $$sv;
3854 if ($op->private & OPpCONST_ARYBASE) {
3857 # if ($op->private & OPpCONST_BARE) { # trouble with `=>' autoquoting
3858 # return $self->const_sv($op)->PV;
3860 my $sv = $self->const_sv($op);
3861 return $self->const($sv, $cx);
3867 my $type = $op->name;
3868 if ($type eq "const") {
3869 return '$[' if $op->private & OPpCONST_ARYBASE;
3870 return uninterp(escape_str(unback($self->const_sv($op)->as_string)));
3871 } elsif ($type eq "concat") {
3872 my $first = $self->dq($op->first);
3873 my $last = $self->dq($op->last);
3875 # Disambiguate "${foo}bar", "${foo}{bar}", "${foo}[1]", "$foo\::bar"
3876 ($last =~ /^[A-Z\\\^\[\]_?]/ &&
3877 $first =~ s/([\$@])\^$/${1}{^}/) # "${^}W" etc
3878 || ($last =~ /^[:'{\[\w_]/ && #'
3879 $first =~ s/([\$@])([A-Za-z_]\w*)$/${1}{$2}/);
3881 return $first . $last;
3882 } elsif ($type eq "uc") {
3883 return '\U' . $self->dq($op->first->sibling) . '\E';
3884 } elsif ($type eq "lc") {
3885 return '\L' . $self->dq($op->first->sibling) . '\E';
3886 } elsif ($type eq "ucfirst") {
3887 return '\u' . $self->dq($op->first->sibling);
3888 } elsif ($type eq "lcfirst") {
3889 return '\l' . $self->dq($op->first->sibling);
3890 } elsif ($type eq "quotemeta") {
3891 return '\Q' . $self->dq($op->first->sibling) . '\E';
3892 } elsif ($type eq "join") {
3893 return $self->deparse($op->last, 26); # was join($", @ary)
3895 return $self->deparse($op, 26);
3902 # skip pushmark if it exists (readpipe() vs ``)
3903 my $child = $op->first->sibling->isa('B::NULL')
3904 ? $op->first : $op->first->sibling;
3905 if ($self->pure_string($child)) {
3906 return single_delim("qx", '`', $self->dq($child, 1));
3908 unop($self, @_, "readpipe");
3914 my $kid = $op->first->sibling; # skip ex-stringify, pushmark
3915 return $self->deparse($kid, $cx) if $self->{'unquote'};
3916 $self->maybe_targmy($kid, $cx,
3917 sub {single_delim("qq", '"', $self->dq($_[1]))});
3920 # OP_STRINGIFY is a listop, but it only ever has one arg
3921 sub pp_stringify { maybe_targmy(@_, \&dquote) }
3923 # tr/// and s/// (and tr[][], tr[]//, tr###, etc)
3924 # note that tr(from)/to/ is OK, but not tr/from/(to)
3926 my($from, $to) = @_;
3927 my($succeed, $delim);
3928 if ($from !~ m[/] and $to !~ m[/]) {
3929 return "/$from/$to/";
3930 } elsif (($succeed, $from) = balanced_delim($from) and $succeed) {
3931 if (($succeed, $to) = balanced_delim($to) and $succeed) {
3934 for $delim ('/', '"', '#') { # note no `'' -- s''' is special
3935 return "$from$delim$to$delim" if index($to, $delim) == -1;
3938 return "$from/$to/";
3941 for $delim ('/', '"', '#') { # note no '
3942 return "$delim$from$delim$to$delim"
3943 if index($to . $from, $delim) == -1;
3945 $from =~ s[/][\\/]g;
3947 return "/$from/$to/";
3951 # Only used by tr///, so backslashes hyphens
3954 if ($n == ord '\\') {
3956 } elsif ($n == ord "-") {
3958 } elsif ($n >= ord(' ') and $n <= ord('~')) {
3960 } elsif ($n == ord "\a") {
3962 } elsif ($n == ord "\b") {
3964 } elsif ($n == ord "\t") {
3966 } elsif ($n == ord "\n") {
3968 } elsif ($n == ord "\e") {
3970 } elsif ($n == ord "\f") {
3972 } elsif ($n == ord "\r") {
3974 } elsif ($n >= ord("\cA") and $n <= ord("\cZ")) {
3975 return '\\c' . chr(ord("@") + $n);
3977 # return '\x' . sprintf("%02x", $n);
3978 return '\\' . sprintf("%03o", $n);
3984 my($str, $c, $tr) = ("");
3985 for ($c = 0; $c < @chars; $c++) {
3988 if ($c <= $#chars - 2 and $chars[$c + 1] == $tr + 1 and
3989 $chars[$c + 2] == $tr + 2)
3991 for (; $c <= $#chars-1 and $chars[$c + 1] == $chars[$c] + 1; $c++)
3994 $str .= pchr($chars[$c]);
4000 sub tr_decode_byte {
4001 my($table, $flags) = @_;
4002 my(@table) = unpack("s*", $table);
4003 splice @table, 0x100, 1; # Number of subsequent elements
4004 my($c, $tr, @from, @to, @delfrom, $delhyphen);
4005 if ($table[ord "-"] != -1 and
4006 $table[ord("-") - 1] == -1 || $table[ord("-") + 1] == -1)
4008 $tr = $table[ord "-"];
4009 $table[ord "-"] = -1;
4013 } else { # -2 ==> delete
4017 for ($c = 0; $c < @table; $c++) {
4020 push @from, $c; push @to, $tr;
4021 } elsif ($tr == -2) {
4025 @from = (@from, @delfrom);
4026 if ($flags & OPpTRANS_COMPLEMENT) {
4029 @from{@from} = (1) x @from;
4030 for ($c = 0; $c < 256; $c++) {
4031 push @newfrom, $c unless $from{$c};
4035 unless ($flags & OPpTRANS_DELETE || !@to) {
4036 pop @to while $#to and $to[$#to] == $to[$#to -1];
4039 $from = collapse(@from);
4040 $to = collapse(@to);
4041 $from .= "-" if $delhyphen;
4042 return ($from, $to);
4047 if ($x == ord "-") {
4049 } elsif ($x == ord "\\") {
4056 # XXX This doesn't yet handle all cases correctly either
4058 sub tr_decode_utf8 {
4059 my($swash_hv, $flags) = @_;
4060 my %swash = $swash_hv->ARRAY;
4062 $final = $swash{'FINAL'}->IV if exists $swash{'FINAL'};
4063 my $none = $swash{"NONE"}->IV;
4064 my $extra = $none + 1;
4065 my(@from, @delfrom, @to);
4067 foreach $line (split /\n/, $swash{'LIST'}->PV) {
4068 my($min, $max, $result) = split(/\t/, $line);
4075 $result = hex $result;
4076 if ($result == $extra) {
4077 push @delfrom, [$min, $max];
4079 push @from, [$min, $max];
4080 push @to, [$result, $result + $max - $min];
4083 for my $i (0 .. $#from) {
4084 if ($from[$i][0] == ord '-') {
4085 unshift @from, splice(@from, $i, 1);
4086 unshift @to, splice(@to, $i, 1);
4088 } elsif ($from[$i][1] == ord '-') {
4091 unshift @from, ord '-';
4092 unshift @to, ord '-';
4096 for my $i (0 .. $#delfrom) {
4097 if ($delfrom[$i][0] == ord '-') {
4098 push @delfrom, splice(@delfrom, $i, 1);
4100 } elsif ($delfrom[$i][1] == ord '-') {
4102 push @delfrom, ord '-';
4106 if (defined $final and $to[$#to][1] != $final) {
4107 push @to, [$final, $final];
4109 push @from, @delfrom;
4110 if ($flags & OPpTRANS_COMPLEMENT) {
4113 for my $i (0 .. $#from) {
4114 push @newfrom, [$next, $from[$i][0] - 1];
4115 $next = $from[$i][1] + 1;
4118 for my $range (@newfrom) {
4119 if ($range->[0] <= $range->[1]) {
4124 my($from, $to, $diff);
4125 for my $chunk (@from) {
4126 $diff = $chunk->[1] - $chunk->[0];
4128 $from .= tr_chr($chunk->[0]) . "-" . tr_chr($chunk->[1]);
4129 } elsif ($diff == 1) {
4130 $from .= tr_chr($chunk->[0]) . tr_chr($chunk->[1]);
4132 $from .= tr_chr($chunk->[0]);
4135 for my $chunk (@to) {
4136 $diff = $chunk->[1] - $chunk->[0];
4138 $to .= tr_chr($chunk->[0]) . "-" . tr_chr($chunk->[1]);
4139 } elsif ($diff == 1) {
4140 $to .= tr_chr($chunk->[0]) . tr_chr($chunk->[1]);
4142 $to .= tr_chr($chunk->[0]);
4145 #$final = sprintf("%04x", $final) if defined $final;
4146 #$none = sprintf("%04x", $none) if defined $none;
4147 #$extra = sprintf("%04x", $extra) if defined $extra;
4148 #print STDERR "final: $final\n none: $none\nextra: $extra\n";
4149 #print STDERR $swash{'LIST'}->PV;
4150 return (escape_str($from), escape_str($to));
4157 my $class = class($op);
4158 my $priv_flags = $op->private;
4159 if ($class eq "PVOP") {
4160 ($from, $to) = tr_decode_byte($op->pv, $priv_flags);
4161 } elsif ($class eq "PADOP") {
4163 = tr_decode_utf8($self->padval($op->padix)->RV, $priv_flags);
4164 } else { # class($op) eq "SVOP"
4165 ($from, $to) = tr_decode_utf8($op->sv->RV, $priv_flags);
4168 $flags .= "c" if $priv_flags & OPpTRANS_COMPLEMENT;
4169 $flags .= "d" if $priv_flags & OPpTRANS_DELETE;
4170 $to = "" if $from eq $to and $flags eq "";
4171 $flags .= "s" if $priv_flags & OPpTRANS_SQUASH;
4172 return "tr" . double_delim($from, $to) . $flags;
4175 sub pp_transr { &pp_trans . 'r' }
4177 sub re_dq_disambiguate {
4178 my ($first, $last) = @_;
4179 # Disambiguate "${foo}bar", "${foo}{bar}", "${foo}[1]"
4180 ($last =~ /^[A-Z\\\^\[\]_?]/ &&
4181 $first =~ s/([\$@])\^$/${1}{^}/) # "${^}W" etc
4182 || ($last =~ /^[{\[\w_]/ &&
4183 $first =~ s/([\$@])([A-Za-z_]\w*)$/${1}{$2}/);
4184 return $first . $last;
4187 # Like dq(), but different
4190 my ($op, $extended) = @_;
4192 my $type = $op->name;
4193 if ($type eq "const") {
4194 return '$[' if $op->private & OPpCONST_ARYBASE;
4195 my $unbacked = re_unback($self->const_sv($op)->as_string);
4196 return re_uninterp_extended(escape_extended_re($unbacked))
4198 return re_uninterp(escape_str($unbacked));
4199 } elsif ($type eq "concat") {
4200 my $first = $self->re_dq($op->first, $extended);
4201 my $last = $self->re_dq($op->last, $extended);
4202 return re_dq_disambiguate($first, $last);
4203 } elsif ($type eq "uc") {
4204 return '\U' . $self->re_dq($op->first->sibling, $extended) . '\E';
4205 } elsif ($type eq "lc") {
4206 return '\L' . $self->re_dq($op->first->sibling, $extended) . '\E';
4207 } elsif ($type eq "ucfirst") {
4208 return '\u' . $self->re_dq($op->first->sibling, $extended);
4209 } elsif ($type eq "lcfirst") {
4210 return '\l' . $self->re_dq($op->first->sibling, $extended);
4211 } elsif ($type eq "quotemeta") {
4212 return '\Q' . $self->re_dq($op->first->sibling, $extended) . '\E';
4213 } elsif ($type eq "join") {
4214 return $self->deparse($op->last, 26); # was join($", @ary)
4216 return $self->deparse($op, 26);
4221 my ($self, $op) = @_;
4222 return 0 if null $op;
4223 my $type = $op->name;
4225 if ($type eq 'const') {
4228 elsif ($type =~ /^[ul]c(first)?$/ || $type eq 'quotemeta') {
4229 return $self->pure_string($op->first->sibling);
4231 elsif ($type eq 'join') {
4232 my $join_op = $op->first->sibling; # Skip pushmark
4233 return 0 unless $join_op->name eq 'null' && $join_op->targ eq OP_RV2SV;
4235 my $gvop = $join_op->first;
4236 return 0 unless $gvop->name eq 'gvsv';
4237 return 0 unless '"' eq $self->gv_name($self->gv_or_padgv($gvop));
4239 return 0 unless ${$join_op->sibling} eq ${$op->last};
4240 return 0 unless $op->last->name =~ /^(?:[ah]slice|(?:rv2|pad)av)$/;
4242 elsif ($type eq 'concat') {
4243 return $self->pure_string($op->first)
4244 && $self->pure_string($op->last);
4246 elsif (is_scalar($op) || $type =~ /^[ah]elem$/) {
4249 elsif ($type eq "null" and $op->can('first') and not null $op->first and
4250 $op->first->name eq "null" and $op->first->can('first')
4251 and not null $op->first->first and
4252 $op->first->first->name eq "aelemfast") {
4264 my($op, $cx, $extended) = @_;
4265 my $kid = $op->first;
4266 $kid = $kid->first if $kid->name eq "regcmaybe";
4267 $kid = $kid->first if $kid->name eq "regcreset";
4268 if ($kid->name eq "null" and !null($kid->first)
4269 and $kid->first->name eq 'pushmark')
4272 $kid = $kid->first->sibling;
4273 while (!null($kid)) {
4275 my $last = $self->re_dq($kid, $extended);
4276 $str = re_dq_disambiguate($first, $last);
4277 $kid = $kid->sibling;
4282 return ($self->re_dq($kid, $extended), 1) if $self->pure_string($kid);
4283 return ($self->deparse($kid, $cx), 0);
4287 my ($self, $op, $cx) = @_;
4288 return (($self->regcomp($op, $cx, 0))[0]);
4291 # osmic acid -- see osmium tetroxide
4294 map($matchwords{join "", sort split //, $_} = $_, 'cig', 'cog', 'cos', 'cogs',
4295 'cox', 'go', 'is', 'ism', 'iso', 'mig', 'mix', 'osmic', 'ox', 'sic',
4296 'sig', 'six', 'smog', 'so', 'soc', 'sog', 'xi');
4300 my($op, $cx, $name, $delim) = @_;
4301 my $kid = $op->first;
4302 my ($binop, $var, $re) = ("", "", "");
4303 if ($op->flags & OPf_STACKED) {
4305 $var = $self->deparse($kid, 20);
4306 $kid = $kid->sibling;
4309 my $extended = ($op->pmflags & PMf_EXTENDED);
4310 my $rhs_bound_to_defsv;
4312 my $unbacked = re_unback($op->precomp);
4314 $re = re_uninterp_extended(escape_extended_re($unbacked));
4316 $re = re_uninterp(escape_str(re_unback($op->precomp)));
4318 } elsif ($kid->name ne 'regcomp') {
4319 carp("found ".$kid->name." where regcomp expected");
4321 ($re, $quote) = $self->regcomp($kid, 21, $extended);
4322 $rhs_bound_to_defsv = 1 if $kid->first->first->flags & OPf_SPECIAL;
4325 $flags .= "c" if $op->pmflags & PMf_CONTINUE;
4326 $flags .= "g" if $op->pmflags & PMf_GLOBAL;
4327 $flags .= "i" if $op->pmflags & PMf_FOLD;
4328 $flags .= "m" if $op->pmflags & PMf_MULTILINE;
4329 $flags .= "o" if $op->pmflags & PMf_KEEP;
4330 $flags .= "s" if $op->pmflags & PMf_SINGLELINE;
4331 $flags .= "x" if $op->pmflags & PMf_EXTENDED;
4332 $flags = $matchwords{$flags} if $matchwords{$flags};
4333 if ($op->pmflags & PMf_ONCE) { # only one kind of delimiter works here
4337 $re = single_delim($name, $delim, $re);
4339 $re = $re . $flags if $quote;
4342 $self->maybe_parens(
4344 ? "$var =~ (\$_ =~ $re)"
4353 sub pp_match { matchop(@_, "m", "/") }
4354 sub pp_pushre { matchop(@_, "m", "/") }
4355 sub pp_qr { matchop(@_, "qr", "") }
4360 my($kid, @exprs, $ary, $expr);
4363 # For our kid (an OP_PUSHRE), pmreplroot is never actually the
4364 # root of a replacement; it's either empty, or abused to point to
4365 # the GV for an array we split into (an optimization to save
4366 # assignment overhead). Depending on whether we're using ithreads,
4367 # this OP* holds either a GV* or a PADOFFSET. Luckily, B.xs
4368 # figures out for us which it is.
4369 my $replroot = $kid->pmreplroot;
4371 if (ref($replroot) eq "B::GV") {