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);
25 use vars qw/$AUTOLOAD/;
30 # List version-specific constants here.
31 # Easiest way to keep this code portable between version looks to
32 # be to fake up a dummy constant that will never actually be true.
33 foreach (qw(OPpSORT_INPLACE OPpSORT_DESCEND OPpITER_REVERSED OPpCONST_NOVER
34 OPpPAD_STATE PMf_SKIPWHITE RXf_SKIPWHITE
35 RXf_PMf_CHARSET RXf_PMf_KEEPCOPY
36 CVf_LOCKED OPpREVERSE_INPLACE OPpSUBSTR_REPL_FIRST
37 PMf_NONDESTRUCT OPpCONST_ARYBASE OPpEVAL_BYTES)) {
40 *{$_} = sub () {0} unless *{$_}{CODE};
44 # Changes between 0.50 and 0.51:
45 # - fixed nulled leave with live enter in sort { }
46 # - fixed reference constants (\"str")
47 # - handle empty programs gracefully
48 # - handle infinite loops (for (;;) {}, while (1) {})
49 # - differentiate between 'for my $x ...' and 'my $x; for $x ...'
50 # - various minor cleanups
51 # - moved globals into an object
52 # - added '-u', like B::C
53 # - package declarations using cop_stash
54 # - subs, formats and code sorted by cop_seq
55 # Changes between 0.51 and 0.52:
56 # - added pp_threadsv (special variables under USE_5005THREADS)
57 # - added documentation
58 # Changes between 0.52 and 0.53:
59 # - many changes adding precedence contexts and associativity
60 # - added '-p' and '-s' output style options
61 # - various other minor fixes
62 # Changes between 0.53 and 0.54:
63 # - added support for new 'for (1..100)' optimization,
65 # Changes between 0.54 and 0.55:
66 # - added support for new qr// construct
67 # - added support for new pp_regcreset OP
68 # Changes between 0.55 and 0.56:
69 # - tested on base/*.t, cmd/*.t, comp/*.t, io/*.t
70 # - fixed $# on non-lexicals broken in last big rewrite
71 # - added temporary fix for change in opcode of OP_STRINGIFY
72 # - fixed problem in 0.54's for() patch in 'for (@ary)'
73 # - fixed precedence in conditional of ?:
74 # - tweaked list paren elimination in 'my($x) = @_'
75 # - made continue-block detection trickier wrt. null ops
76 # - fixed various prototype problems in pp_entersub
77 # - added support for sub prototypes that never get GVs
78 # - added unquoting for special filehandle first arg in truncate
79 # - print doubled rv2gv (a bug) as '*{*GV}' instead of illegal '**GV'
80 # - added semicolons at the ends of blocks
81 # - added -l '#line' declaration option -- fixes cmd/subval.t 27,28
82 # Changes between 0.56 and 0.561:
83 # - fixed multiply-declared my var in pp_truncate (thanks to Sarathy)
84 # - used new B.pm symbolic constants (done by Nick Ing-Simmons)
85 # Changes between 0.561 and 0.57:
86 # - stylistic changes to symbolic constant stuff
87 # - handled scope in s///e replacement code
88 # - added unquote option for expanding "" into concats, etc.
89 # - split method and proto parts of pp_entersub into separate functions
90 # - various minor cleanups
92 # - added parens in \&foo (patch by Albert Dvornik)
93 # Changes between 0.57 and 0.58:
94 # - fixed '0' statements that weren't being printed
95 # - added methods for use from other programs
96 # (based on patches from James Duncan and Hugo van der Sanden)
97 # - added -si and -sT to control indenting (also based on a patch from Hugo)
98 # - added -sv to print something else instead of '???'
99 # - preliminary version of utf8 tr/// handling
100 # Changes after 0.58:
101 # - uses of $op->ppaddr changed to new $op->name (done by Sarathy)
102 # - added support for Hugo's new OP_SETSTATE (like nextstate)
103 # Changes between 0.58 and 0.59
104 # - added support for Chip's OP_METHOD_NAMED
105 # - added support for Ilya's OPpTARGET_MY optimization
106 # - elided arrows before '()' subscripts when possible
107 # Changes between 0.59 and 0.60
108 # - support for method attributes was added
109 # - some warnings fixed
110 # - separate recognition of constant subs
111 # - rewrote continue block handling, now recognizing for loops
112 # - added more control of expanding control structures
113 # Changes between 0.60 and 0.61 (mostly by Robin Houston)
115 # - support for pragmas and 'use'
116 # - support for the little-used $[ variable
117 # - support for __DATA__ sections
119 # - BEGIN, CHECK, INIT and END blocks
120 # - scoping of subroutine declarations fixed
121 # - compile-time output from the input program can be suppressed, so that the
122 # output is just the deparsed code. (a change to O.pm in fact)
123 # - our() declarations
124 # - *all* the known bugs are now listed in the BUGS section
125 # - comprehensive test mechanism (TEST -deparse)
126 # Changes between 0.62 and 0.63 (mostly by Rafael Garcia-Suarez)
129 # - support for command-line switches (-l, -0, etc.)
130 # Changes between 0.63 and 0.64
131 # - support for //, CHECK blocks, and assertions
132 # - improved handling of foreach loops and lexicals
133 # - option to use Data::Dumper for constants
135 # - discovered lots more bugs not yet fixed
139 # Changes between 0.72 and 0.73
140 # - support new switch constructs
143 # (See also BUGS section at the end of this file)
145 # - finish tr/// changes
146 # - add option for even more parens (generalize \&foo change)
147 # - left/right context
148 # - copy comments (look at real text with $^P?)
149 # - avoid semis in one-statement blocks
150 # - associativity of &&=, ||=, ?:
151 # - ',' => '=>' (auto-unquote?)
152 # - break long lines ("\r" as discretionary break?)
153 # - configurable syntax highlighting: ANSI color, HTML, TeX, etc.
154 # - more style options: brace style, hex vs. octal, quotes, ...
155 # - print big ints as hex/octal instead of decimal (heuristic?)
156 # - handle 'my $x if 0'?
157 # - version using op_next instead of op_first/sibling?
158 # - avoid string copies (pass arrays, one big join?)
161 # Current test.deparse failures
162 # comp/hints 6 - location of BEGIN blocks wrt. block openings
163 # run/switchI 1 - missing -I switches entirely
164 # perl -Ifoo -e 'print @INC'
165 # op/caller 2 - warning mask propagates backwards before warnings::register
166 # 'use warnings; BEGIN {${^WARNING_BITS} eq "U"x12;} use warnings::register'
167 # op/getpid 2 - can't assign to shared my() declaration (threads only)
168 # 'my $x : shared = 5'
169 # op/override 7 - parens on overridden require change v-string interpretation
170 # 'BEGIN{*CORE::GLOBAL::require=sub {}} require v5.6'
171 # c.f. 'BEGIN { *f = sub {0} }; f 2'
172 # op/pat 774 - losing Unicode-ness of Latin1-only strings
173 # 'use charnames ":short"; $x="\N{latin:a with acute}"'
174 # op/recurse 12 - missing parens on recursive call makes it look like method
176 # op/subst 90 - inconsistent handling of utf8 under "use utf8"
177 # op/taint 29 - "use re 'taint'" deparsed in the wrong place wrt. block open
178 # op/tiehandle compile - "use strict" deparsed in the wrong place
180 # ext/B/t/xref 11 - line numbers when we add newlines to one-line subs
181 # ext/Data/Dumper/t/dumper compile
182 # ext/DB_file/several
184 # ext/Ernno/Errno warnings
185 # ext/IO/lib/IO/t/io_sel 23
186 # ext/PerlIO/t/encoding compile
187 # ext/POSIX/t/posix 6
188 # ext/Socket/Socket 8
189 # ext/Storable/t/croak compile
190 # lib/Attribute/Handlers/t/multi compile
191 # lib/bignum/ several
195 # lib/ExtUtils/t/bytes 4
196 # lib/File/DosGlob compile
197 # lib/Filter/Simple/t/data 1
198 # lib/Math/BigInt/t/constant 1
199 # lib/Net/t/config Deparse-warning
200 # lib/overload compile
201 # lib/Switch/ several
203 # lib/Test/Simple several
205 # lib/Tie/File/t/29_downcopy 5
208 # Object fields (were globals):
211 # (local($a), local($b)) and local($a, $b) have the same internal
212 # representation but the short form looks better. We notice we can
213 # use a large-scale local when checking the list, but need to prevent
214 # individual locals too. This hash holds the addresses of OPs that
215 # have already had their local-ness accounted for. The same thing
219 # CV for current sub (or main program) being deparsed
222 # Cached hash of lexical variables for curcv: keys are
223 # names prefixed with "m" or "o" (representing my/our), and
224 # each value is an array of pairs, indicating the cop_seq of scopes
225 # in which a var of that name is valid.
228 # COP for statement being deparsed
231 # name of the current package for deparsed code
234 # array of [cop_seq, CV, is_format?] for subs and formats we still
238 # as above, but [name, prototype] for subs that never got a GV
240 # subs_done, forms_done:
241 # keys are addresses of GVs for subs and formats we've already
242 # deparsed (or at least put into subs_todo)
245 # keys are names of subs for which we've printed declarations.
246 # That means we can omit parentheses from the arguments. It also means we
247 # need to put CORE:: on core functions of the same name.
250 # Keeps track of fully qualified names of all deparsed subs.
255 # cuddle: ' ' or '\n', depending on -sC
260 # A little explanation of how precedence contexts and associativity
263 # deparse() calls each per-op subroutine with an argument $cx (short
264 # for context, but not the same as the cx* in the perl core), which is
265 # a number describing the op's parents in terms of precedence, whether
266 # they're inside an expression or at statement level, etc. (see
267 # chart below). When ops with children call deparse on them, they pass
268 # along their precedence. Fractional values are used to implement
269 # associativity ('($x + $y) + $z' => '$x + $y + $y') and related
270 # parentheses hacks. The major disadvantage of this scheme is that
271 # it doesn't know about right sides and left sides, so say if you
272 # assign a listop to a variable, it can't tell it's allowed to leave
273 # the parens off the listop.
276 # 26 [TODO] inside interpolation context ("")
277 # 25 left terms and list operators (leftward)
281 # 21 right ! ~ \ and unary + and -
286 # 16 nonassoc named unary operators
287 # 15 nonassoc < > <= >= lt gt le ge
288 # 14 nonassoc == != <=> eq ne cmp
295 # 7 right = += -= *= etc.
297 # 5 nonassoc list operators (rightward)
301 # 1 statement modifiers
302 # 0.5 statements, but still print scopes as do { ... }
305 # Nonprinting characters with special meaning:
306 # \cS - steal parens (see maybe_parens_unop)
307 # \n - newline and indent
308 # \t - increase indent
309 # \b - decrease indent ('outdent')
310 # \f - flush left (no indent)
311 # \cK - kill following semicolon, if any
315 return class($op) eq "NULL";
320 my($cv, $is_form) = @_;
321 return unless ($cv->FILE eq $0 || exists $self->{files}{$cv->FILE});
323 if ($cv->OUTSIDE_SEQ) {
324 $seq = $cv->OUTSIDE_SEQ;
325 } elsif (!null($cv->START) and is_state($cv->START)) {
326 $seq = $cv->START->cop_seq;
330 push @{$self->{'subs_todo'}}, [$seq, $cv, $is_form];
331 unless ($is_form || class($cv->STASH) eq 'SPECIAL') {
332 $self->{'subs_deparsed'}{$cv->STASH->NAME."::".$cv->GV->NAME} = 1;
338 my $ent = shift @{$self->{'subs_todo'}};
341 my $name = $self->gv_name($gv);
343 return "format $name =\n"
344 . $self->deparse_format($ent->[1]). "\n";
346 $self->{'subs_declared'}{$name} = 1;
347 if ($name eq "BEGIN") {
348 my $use_dec = $self->begin_is_use($cv);
349 if (defined ($use_dec) and $self->{'expand'} < 5) {
350 return () if 0 == length($use_dec);
355 if ($self->{'linenums'}) {
356 my $line = $gv->LINE;
357 my $file = $gv->FILE;
358 $l = "\n\f#line $line \"$file\"\n";
361 if (class($cv->STASH) ne "SPECIAL") {
362 my $stash = $cv->STASH->NAME;
363 if ($stash ne $self->{'curstash'}) {
364 $p = "package $stash;\n";
365 $name = "$self->{'curstash'}::$name" unless $name =~ /::/;
366 $self->{'curstash'} = $stash;
368 $name =~ s/^\Q$stash\E::(?!\z|.*::)//;
370 return "${p}${l}sub $name " . $self->deparse_sub($cv);
374 # Return a "use" declaration for this BEGIN block, if appropriate
376 my ($self, $cv) = @_;
377 my $root = $cv->ROOT;
378 local @$self{qw'curcv curcvlex'} = ($cv);
380 #B::walkoptree($cv->ROOT, "debug");
381 my $lineseq = $root->first;
382 return if $lineseq->name ne "lineseq";
384 my $req_op = $lineseq->first->sibling;
385 return if $req_op->name ne "require";
388 if ($req_op->first->private & OPpCONST_BARE) {
389 # Actually it should always be a bareword
390 $module = $self->const_sv($req_op->first)->PV;
391 $module =~ s[/][::]g;
395 $module = $self->const($self->const_sv($req_op->first), 6);
399 my $version_op = $req_op->sibling;
400 return if class($version_op) eq "NULL";
401 if ($version_op->name eq "lineseq") {
402 # We have a version parameter; skip nextstate & pushmark
403 my $constop = $version_op->first->next->next;
405 return unless $self->const_sv($constop)->PV eq $module;
406 $constop = $constop->sibling;
407 $version = $self->const_sv($constop);
408 if (class($version) eq "IV") {
409 $version = $version->int_value;
410 } elsif (class($version) eq "NV") {
411 $version = $version->NV;
412 } elsif (class($version) ne "PVMG") {
413 # Includes PVIV and PVNV
414 $version = $version->PV;
416 # version specified as a v-string
417 $version = 'v'.join '.', map ord, split //, $version->PV;
419 $constop = $constop->sibling;
420 return if $constop->name ne "method_named";
421 return if $self->const_sv($constop)->PV ne "VERSION";
424 $lineseq = $version_op->sibling;
425 return if $lineseq->name ne "lineseq";
426 my $entersub = $lineseq->first->sibling;
427 if ($entersub->name eq "stub") {
428 return "use $module $version ();\n" if defined $version;
429 return "use $module ();\n";
431 return if $entersub->name ne "entersub";
433 # See if there are import arguments
436 my $svop = $entersub->first->sibling; # Skip over pushmark
437 return unless $self->const_sv($svop)->PV eq $module;
439 # Pull out the arguments
440 for ($svop=$svop->sibling; $svop->name ne "method_named";
441 $svop = $svop->sibling) {
442 $args .= ", " if length($args);
443 $args .= $self->deparse($svop, 6);
447 my $method_named = $svop;
448 return if $method_named->name ne "method_named";
449 my $method_name = $self->const_sv($method_named)->PV;
451 if ($method_name eq "unimport") {
455 # Certain pragmas are dealt with using hint bits,
456 # so we ignore them here
457 if ($module eq 'strict' || $module eq 'integer'
458 || $module eq 'bytes' || $module eq 'warnings'
459 || $module eq 'feature') {
463 if (defined $version && length $args) {
464 return "$use $module $version ($args);\n";
465 } elsif (defined $version) {
466 return "$use $module $version;\n";
467 } elsif (length $args) {
468 return "$use $module ($args);\n";
470 return "$use $module;\n";
475 my ($self, $pack, $seen) = @_;
477 if (!defined $pack) {
482 $pack =~ s/(::)?$/::/;
484 $stash = \%{"main::$pack"};
488 $INC{"overload.pm"} ? overload::StrVal($stash) : $stash
490 my %stash = svref_2object($stash)->ARRAY;
491 while (my ($key, $val) = each %stash) {
492 my $class = class($val);
493 if ($class eq "PV") {
494 # Just a prototype. As an ugly but fairly effective way
495 # to find out if it belongs here is to see if the AUTOLOAD
496 # (if any) for the stash was defined in one of our files.
497 my $A = $stash{"AUTOLOAD"};
498 if (defined ($A) && class($A) eq "GV" && defined($A->CV)
499 && class($A->CV) eq "CV") {
501 next unless $AF eq $0 || exists $self->{'files'}{$AF};
503 push @{$self->{'protos_todo'}}, [$pack . $key, $val->PV];
504 } elsif ($class eq "IV" && !($val->FLAGS & SVf_ROK)) {
505 # Just a name. As above.
506 # But skip proxy constant subroutines, as some form of perl-space
507 # visible code must have created them, be it a use statement, or
508 # some direct symbol-table manipulation code that we will Deparse
509 my $A = $stash{"AUTOLOAD"};
510 if (defined ($A) && class($A) eq "GV" && defined($A->CV)
511 && class($A->CV) eq "CV") {
513 next unless $AF eq $0 || exists $self->{'files'}{$AF};
515 push @{$self->{'protos_todo'}}, [$pack . $key, undef];
516 } elsif ($class eq "GV") {
517 if (class(my $cv = $val->CV) ne "SPECIAL") {
518 next if $self->{'subs_done'}{$$val}++;
519 next if $$val != ${$cv->GV}; # Ignore imposters
522 if (class(my $cv = $val->FORM) ne "SPECIAL") {
523 next if $self->{'forms_done'}{$$val}++;
524 next if $$val != ${$cv->GV}; # Ignore imposters
527 if (class($val->HV) ne "SPECIAL" && $key =~ /::$/) {
528 $self->stash_subs($pack . $key, $seen);
538 foreach $ar (@{$self->{'protos_todo'}}) {
539 my $proto = (defined $ar->[1] ? " (". $ar->[1] . ")" : "");
540 push @ret, "sub " . $ar->[0] . "$proto;\n";
542 delete $self->{'protos_todo'};
550 while (length($opt = substr($opts, 0, 1))) {
552 $self->{'cuddle'} = " ";
553 $opts = substr($opts, 1);
554 } elsif ($opt eq "i") {
555 $opts =~ s/^i(\d+)//;
556 $self->{'indent_size'} = $1;
557 } elsif ($opt eq "T") {
558 $self->{'use_tabs'} = 1;
559 $opts = substr($opts, 1);
560 } elsif ($opt eq "v") {
561 $opts =~ s/^v([^.]*)(.|$)//;
562 $self->{'ex_const'} = $1;
569 my $self = bless {}, $class;
570 $self->{'cuddle'} = "\n";
571 $self->{'curcop'} = undef;
572 $self->{'curstash'} = "main";
573 $self->{'ex_const'} = "'???'";
574 $self->{'expand'} = 0;
575 $self->{'files'} = {};
576 $self->{'indent_size'} = 4;
577 $self->{'linenums'} = 0;
578 $self->{'parens'} = 0;
579 $self->{'subs_todo'} = [];
580 $self->{'unquote'} = 0;
581 $self->{'use_dumper'} = 0;
582 $self->{'use_tabs'} = 0;
584 $self->{'ambient_arybase'} = 0;
585 $self->{'ambient_warnings'} = undef; # Assume no lexical warnings
586 $self->{'ambient_hints'} = 0;
587 $self->{'ambient_hinthash'} = undef;
590 while (my $arg = shift @_) {
592 $self->{'use_dumper'} = 1;
593 require Data::Dumper;
594 } elsif ($arg =~ /^-f(.*)/) {
595 $self->{'files'}{$1} = 1;
596 } elsif ($arg eq "-l") {
597 $self->{'linenums'} = 1;
598 } elsif ($arg eq "-p") {
599 $self->{'parens'} = 1;
600 } elsif ($arg eq "-P") {
601 $self->{'noproto'} = 1;
602 } elsif ($arg eq "-q") {
603 $self->{'unquote'} = 1;
604 } elsif (substr($arg, 0, 2) eq "-s") {
605 $self->style_opts(substr $arg, 2);
606 } elsif ($arg =~ /^-x(\d)$/) {
607 $self->{'expand'} = $1;
614 # Mask out the bits that L<warnings::register> uses
617 $WARN_MASK = $warnings::Bits{all} | $warnings::DeadBits{all};
624 # Initialise the contextual information, either from
625 # defaults provided with the ambient_pragmas method,
626 # or from perl's own defaults otherwise.
630 $self->{'arybase'} = $self->{'ambient_arybase'};
631 $self->{'warnings'} = defined ($self->{'ambient_warnings'})
632 ? $self->{'ambient_warnings'} & WARN_MASK
634 $self->{'hints'} = $self->{'ambient_hints'};
635 $self->{'hints'} &= 0xFF if $] < 5.009;
636 $self->{'hinthash'} = $self->{'ambient_hinthash'};
638 # also a convenient place to clear out subs_declared
639 delete $self->{'subs_declared'};
645 my $self = B::Deparse->new(@args);
646 # First deparse command-line args
647 if (defined $^I) { # deparse -i
648 print q(BEGIN { $^I = ).perlstring($^I).qq(; }\n);
650 if ($^W) { # deparse -w
651 print qq(BEGIN { \$^W = $^W; }\n);
653 if ($/ ne "\n" or defined $O::savebackslash) { # deparse -l and -0
654 my $fs = perlstring($/) || 'undef';
655 my $bs = perlstring($O::savebackslash) || 'undef';
656 print qq(BEGIN { \$/ = $fs; \$\\ = $bs; }\n);
658 my @BEGINs = B::begin_av->isa("B::AV") ? B::begin_av->ARRAY : ();
659 my @UNITCHECKs = B::unitcheck_av->isa("B::AV")
660 ? B::unitcheck_av->ARRAY
662 my @CHECKs = B::check_av->isa("B::AV") ? B::check_av->ARRAY : ();
663 my @INITs = B::init_av->isa("B::AV") ? B::init_av->ARRAY : ();
664 my @ENDs = B::end_av->isa("B::AV") ? B::end_av->ARRAY : ();
665 for my $block (@BEGINs, @UNITCHECKs, @CHECKs, @INITs, @ENDs) {
666 $self->todo($block, 0);
669 local($SIG{"__DIE__"}) =
671 if ($self->{'curcop'}) {
672 my $cop = $self->{'curcop'};
673 my($line, $file) = ($cop->line, $cop->file);
674 print STDERR "While deparsing $file near line $line,\n";
677 $self->{'curcv'} = main_cv;
678 $self->{'curcvlex'} = undef;
679 print $self->print_protos;
680 @{$self->{'subs_todo'}} =
681 sort {$a->[0] <=> $b->[0]} @{$self->{'subs_todo'}};
682 print $self->indent($self->deparse_root(main_root)), "\n"
683 unless null main_root;
685 while (scalar(@{$self->{'subs_todo'}})) {
686 push @text, $self->next_todo;
688 print $self->indent(join("", @text)), "\n" if @text;
690 # Print __DATA__ section, if necessary
692 my $laststash = defined $self->{'curcop'}
693 ? $self->{'curcop'}->stash->NAME : $self->{'curstash'};
694 if (defined *{$laststash."::DATA"}{IO}) {
695 print "package $laststash;\n"
696 unless $laststash eq $self->{'curstash'};
698 print readline(*{$laststash."::DATA"});
706 croak "Usage: ->coderef2text(CODEREF)" unless UNIVERSAL::isa($sub, "CODE");
709 return $self->indent($self->deparse_sub(svref_2object($sub)));
712 my %strict_bits = do {
714 map +($_ => strict::bits($_)), qw/refs subs vars/
717 sub ambient_pragmas {
719 my ($arybase, $hint_bits, $warning_bits, $hinthash) = (0, 0);
725 if ($name eq 'strict') {
728 if ($val eq 'none') {
729 $hint_bits &= $strict_bits{$_} for qw/refs subs vars/;
735 @names = qw/refs subs vars/;
741 @names = split' ', $val;
743 $hint_bits |= $strict_bits{$_} for @names;
746 elsif ($name eq '$[') {
747 if (OPpCONST_ARYBASE) {
750 croak "\$[ can't be non-zero on this perl" unless $val == 0;
754 elsif ($name eq 'integer'
756 || $name eq 'utf8') {
759 $hint_bits |= ${$::{"${name}::"}{"hint_bits"}};
762 $hint_bits &= ~${$::{"${name}::"}{"hint_bits"}};
766 elsif ($name eq 're') {
768 if ($val eq 'none') {
769 $hint_bits &= ~re::bits(qw/taint eval/);
775 @names = qw/taint eval/;
781 @names = split' ',$val;
783 $hint_bits |= re::bits(@names);
786 elsif ($name eq 'warnings') {
787 if ($val eq 'none') {
788 $warning_bits = $warnings::NONE;
797 @names = split/\s+/, $val;
800 $warning_bits = $warnings::NONE if !defined ($warning_bits);
801 $warning_bits |= warnings::bits(@names);
804 elsif ($name eq 'warning_bits') {
805 $warning_bits = $val;
808 elsif ($name eq 'hint_bits') {
812 elsif ($name eq '%^H') {
817 croak "Unknown pragma type: $name";
821 croak "The ambient_pragmas method expects an even number of args";
824 $self->{'ambient_arybase'} = $arybase;
825 $self->{'ambient_warnings'} = $warning_bits;
826 $self->{'ambient_hints'} = $hint_bits;
827 $self->{'ambient_hinthash'} = $hinthash;
830 # This method is the inner loop, so try to keep it simple
835 Carp::confess("Null op in deparse") if !defined($op)
836 || class($op) eq "NULL";
837 my $meth = "pp_" . $op->name;
838 return $self->$meth($op, $cx);
844 my @lines = split(/\n/, $txt);
849 my $cmd = substr($line, 0, 1);
850 if ($cmd eq "\t" or $cmd eq "\b") {
851 $level += ($cmd eq "\t" ? 1 : -1) * $self->{'indent_size'};
852 if ($self->{'use_tabs'}) {
853 $leader = "\t" x ($level / 8) . " " x ($level % 8);
855 $leader = " " x $level;
857 $line = substr($line, 1);
859 if (substr($line, 0, 1) eq "\f") {
860 $line = substr($line, 1); # no indent
862 $line = $leader . $line;
866 return join("\n", @lines);
873 Carp::confess("NULL in deparse_sub") if !defined($cv) || $cv->isa("B::NULL");
874 Carp::confess("SPECIAL in deparse_sub") if $cv->isa("B::SPECIAL");
875 local $self->{'curcop'} = $self->{'curcop'};
876 if ($cv->FLAGS & SVf_POK) {
877 $proto = "(". $cv->PV . ") ";
879 if ($cv->CvFLAGS & (CVf_METHOD|CVf_LOCKED|CVf_LVALUE)) {
881 $proto .= "lvalue " if $cv->CvFLAGS & CVf_LVALUE;
882 $proto .= "locked " if $cv->CvFLAGS & CVf_LOCKED;
883 $proto .= "method " if $cv->CvFLAGS & CVf_METHOD;
886 local($self->{'curcv'}) = $cv;
887 local($self->{'curcvlex'});
888 local(@$self{qw'curstash warnings hints hinthash'})
889 = @$self{qw'curstash warnings hints hinthash'};
891 if (not null $cv->ROOT) {
892 my $lineseq = $cv->ROOT->first;
893 if ($lineseq->name eq "lineseq") {
895 for(my$o=$lineseq->first; $$o; $o=$o->sibling) {
898 $body = $self->lineseq(undef, @ops).";";
899 my $scope_en = $self->find_scope_en($lineseq);
900 if (defined $scope_en) {
901 my $subs = join"", $self->seq_subs($scope_en);
902 $body .= ";\n$subs" if length($subs);
906 $body = $self->deparse($cv->ROOT->first, 0);
910 my $sv = $cv->const_sv;
912 # uh-oh. inlinable sub... format it differently
913 return $proto . "{ " . $self->const($sv, 0) . " }\n";
914 } else { # XSUB? (or just a declaration)
918 return $proto ."{\n\t$body\n\b}" ."\n";
925 local($self->{'curcv'}) = $form;
926 local($self->{'curcvlex'});
927 local($self->{'in_format'}) = 1;
928 local(@$self{qw'curstash warnings hints hinthash'})
929 = @$self{qw'curstash warnings hints hinthash'};
930 my $op = $form->ROOT;
932 return "\f." if $op->first->name eq 'stub'
933 || $op->first->name eq 'nextstate';
934 $op = $op->first->first; # skip leavewrite, lineseq
935 while (not null $op) {
936 $op = $op->sibling; # skip nextstate
938 $kid = $op->first->sibling; # skip pushmark
939 push @text, "\f".$self->const_sv($kid)->PV;
940 $kid = $kid->sibling;
941 for (; not null $kid; $kid = $kid->sibling) {
942 push @exprs, $self->deparse($kid, 0);
944 push @text, "\f".join(", ", @exprs)."\n" if @exprs;
947 return join("", @text) . "\f.";
952 return $op->name eq "leave" || $op->name eq "scope"
953 || $op->name eq "lineseq"
954 || ($op->name eq "null" && class($op) eq "UNOP"
955 && (is_scope($op->first) || $op->first->name eq "enter"));
959 my $name = $_[0]->name;
960 return $name eq "nextstate" || $name eq "dbstate" || $name eq "setstate";
963 sub is_miniwhile { # check for one-line loop ('foo() while $y--')
965 return (!null($op) and null($op->sibling)
966 and $op->name eq "null" and class($op) eq "UNOP"
967 and (($op->first->name =~ /^(and|or)$/
968 and $op->first->first->sibling->name eq "lineseq")
969 or ($op->first->name eq "lineseq"
970 and not null $op->first->first->sibling
971 and $op->first->first->sibling->name eq "unstack")
975 # Check if the op and its sibling are the initialization and the rest of a
976 # for (..;..;..) { ... } loop
979 # This OP might be almost anything, though it won't be a
980 # nextstate. (It's the initialization, so in the canonical case it
981 # will be an sassign.) The sibling is (old style) a lineseq whose
982 # first child is a nextstate and whose second is a leaveloop, or
983 # (new style) an unstack whose sibling is a leaveloop.
984 my $lseq = $op->sibling;
985 return 0 unless !is_state($op) and !null($lseq);
986 if ($lseq->name eq "lineseq") {
987 if ($lseq->first && !null($lseq->first) && is_state($lseq->first)
988 && (my $sib = $lseq->first->sibling)) {
989 return (!null($sib) && $sib->name eq "leaveloop");
991 } elsif ($lseq->name eq "unstack" && ($lseq->flags & OPf_SPECIAL)) {
992 my $sib = $lseq->sibling;
993 return $sib && !null($sib) && $sib->name eq "leaveloop";
1000 return ($op->name eq "rv2sv" or
1001 $op->name eq "padsv" or
1002 $op->name eq "gv" or # only in array/hash constructs
1003 $op->flags & OPf_KIDS && !null($op->first)
1004 && $op->first->name eq "gvsv");
1009 my($text, $cx, $prec) = @_;
1010 if ($prec < $cx # unary ops nest just fine
1011 or $prec == $cx and $cx != 4 and $cx != 16 and $cx != 21
1012 or $self->{'parens'})
1015 # In a unop, let parent reuse our parens; see maybe_parens_unop
1016 $text = "\cS" . $text if $cx == 16;
1023 # same as above, but get around the 'if it looks like a function' rule
1024 sub maybe_parens_unop {
1026 my($name, $kid, $cx) = @_;
1027 if ($cx > 16 or $self->{'parens'}) {
1028 $kid = $self->deparse($kid, 1);
1029 if ($name eq "umask" && $kid =~ /^\d+$/) {
1030 $kid = sprintf("%#o", $kid);
1032 return $self->keyword($name) . "($kid)";
1034 $kid = $self->deparse($kid, 16);
1035 if ($name eq "umask" && $kid =~ /^\d+$/) {
1036 $kid = sprintf("%#o", $kid);
1038 $name = $self->keyword($name);
1039 if (substr($kid, 0, 1) eq "\cS") {
1041 return $name . substr($kid, 1);
1042 } elsif (substr($kid, 0, 1) eq "(") {
1043 # avoid looks-like-a-function trap with extra parens
1044 # ('+' can lead to ambiguities)
1045 return "$name(" . $kid . ")";
1047 return "$name $kid";
1052 sub maybe_parens_func {
1054 my($func, $text, $cx, $prec) = @_;
1055 if ($prec <= $cx or substr($text, 0, 1) eq "(" or $self->{'parens'}) {
1056 return "$func($text)";
1058 return "$func $text";
1064 my($op, $cx, $text) = @_;
1065 my $our_intro = ($op->name =~ /^(gv|rv2)[ash]v$/) ? OPpOUR_INTRO : 0;
1066 if ($op->private & (OPpLVAL_INTRO|$our_intro)
1067 and not $self->{'avoid_local'}{$$op}) {
1068 my $our_local = ($op->private & OPpLVAL_INTRO) ? "local" : "our";
1069 if( $our_local eq 'our' ) {
1070 if ( $text !~ /^\W(\w+::)*\w+\z/
1071 and !utf8::decode($text) || $text !~ /^\W(\w+::)*\w+\z/
1073 die "Unexpected our($text)\n";
1075 $text =~ s/(\w+::)+//;
1077 if (want_scalar($op)) {
1078 return "$our_local $text";
1080 return $self->maybe_parens_func("$our_local", $text, $cx, 16);
1089 my($op, $cx, $func, @args) = @_;
1090 if ($op->private & OPpTARGET_MY) {
1091 my $var = $self->padname($op->targ);
1092 my $val = $func->($self, $op, 7, @args);
1093 return $self->maybe_parens("$var = $val", $cx, 7);
1095 return $func->($self, $op, $cx, @args);
1102 return $self->{'curcv'}->PADLIST->ARRAYelt(0)->ARRAYelt($targ);
1107 my($op, $cx, $text) = @_;
1108 if ($op->private & OPpLVAL_INTRO and not $self->{'avoid_local'}{$$op}) {
1109 my $my = $op->private & OPpPAD_STATE
1110 ? $self->keyword("state")
1112 if (want_scalar($op)) {
1115 return $self->maybe_parens_func($my, $text, $cx, 16);
1122 # The following OPs don't have functions:
1124 # pp_padany -- does not exist after parsing
1127 if ($AUTOLOAD =~ s/^.*::pp_//) {
1128 warn "unexpected OP_".uc $AUTOLOAD;
1131 die "Undefined subroutine $AUTOLOAD called";
1135 sub DESTROY {} # Do not AUTOLOAD
1137 # $root should be the op which represents the root of whatever
1138 # we're sequencing here. If it's undefined, then we don't append
1139 # any subroutine declarations to the deparsed ops, otherwise we
1140 # append appropriate declarations.
1142 my($self, $root, @ops) = @_;
1145 my $out_cop = $self->{'curcop'};
1146 my $out_seq = defined($out_cop) ? $out_cop->cop_seq : undef;
1148 if (defined $root) {
1149 $limit_seq = $out_seq;
1151 $nseq = $self->find_scope_st($root->sibling) if ${$root->sibling};
1152 $limit_seq = $nseq if !defined($limit_seq)
1153 or defined($nseq) && $nseq < $limit_seq;
1155 $limit_seq = $self->{'limit_seq'}
1156 if defined($self->{'limit_seq'})
1157 && (!defined($limit_seq) || $self->{'limit_seq'} < $limit_seq);
1158 local $self->{'limit_seq'} = $limit_seq;
1160 $self->walk_lineseq($root, \@ops,
1161 sub { push @exprs, $_[0]} );
1163 my $body = join(";\n", grep {length} @exprs);
1165 if (defined $root && defined $limit_seq && !$self->{'in_format'}) {
1166 $subs = join "\n", $self->seq_subs($limit_seq);
1168 return join(";\n", grep {length} $body, $subs);
1172 my($real_block, $self, $op, $cx) = @_;
1176 local(@$self{qw'curstash warnings hints hinthash'})
1177 = @$self{qw'curstash warnings hints hinthash'} if $real_block;
1179 $kid = $op->first->sibling; # skip enter
1180 if (is_miniwhile($kid)) {
1181 my $top = $kid->first;
1182 my $name = $top->name;
1183 if ($name eq "and") {
1185 } elsif ($name eq "or") {
1187 } else { # no conditional -> while 1 or until 0
1188 return $self->deparse($top->first, 1) . " while 1";
1190 my $cond = $top->first;
1191 my $body = $cond->sibling->first; # skip lineseq
1192 $cond = $self->deparse($cond, 1);
1193 $body = $self->deparse($body, 1);
1194 return "$body $name $cond";
1199 for (; !null($kid); $kid = $kid->sibling) {
1202 if ($cx > 0) { # inside an expression, (a do {} while for lineseq)
1203 return "do {\n\t" . $self->lineseq($op, @kids) . "\n\b}";
1205 my $lineseq = $self->lineseq($op, @kids);
1206 return (length ($lineseq) ? "$lineseq;" : "");
1210 sub pp_scope { scopeop(0, @_); }
1211 sub pp_lineseq { scopeop(0, @_); }
1212 sub pp_leave { scopeop(1, @_); }
1214 # This is a special case of scopeop and lineseq, for the case of the
1215 # main_root. The difference is that we print the output statements as
1216 # soon as we get them, for the sake of impatient users.
1220 local(@$self{qw'curstash warnings hints hinthash'})
1221 = @$self{qw'curstash warnings hints hinthash'};
1223 return if null $op->first; # Can happen, e.g., for Bytecode without -k
1224 for (my $kid = $op->first->sibling; !null($kid); $kid = $kid->sibling) {
1227 $self->walk_lineseq($op, \@kids,
1228 sub { print $self->indent($_[0].';');
1229 print "\n" unless $_[1] == $#kids;
1234 my ($self, $op, $kids, $callback) = @_;
1236 for (my $i = 0; $i < @kids; $i++) {
1238 if (is_state $kids[$i]) {
1239 $expr = $self->deparse($kids[$i++], 0);
1241 $callback->($expr, $i);
1245 if (is_for_loop($kids[$i])) {
1246 $callback->($expr . $self->for_loop($kids[$i], 0),
1247 $i += $kids[$i]->sibling->name eq "unstack" ? 2 : 1);
1250 $expr .= $self->deparse($kids[$i], (@kids != 1)/2);
1251 $expr =~ s/;\n?\z//;
1252 $callback->($expr, $i);
1256 # The BEGIN {} is used here because otherwise this code isn't executed
1257 # when you run B::Deparse on itself.
1259 BEGIN { map($globalnames{$_}++, "SIG", "STDIN", "STDOUT", "STDERR", "INC",
1260 "ENV", "ARGV", "ARGVOUT", "_"); }
1266 Carp::confess() unless ref($gv) eq "B::GV";
1267 my $stash = $gv->STASH->NAME;
1268 my $name = $raw ? $gv->NAME : $gv->SAFENAME;
1269 if ($stash eq 'main' && $name =~ /^::/) {
1272 elsif (($stash eq 'main'
1273 && ($globalnames{$name} || $name =~ /^[^A-Za-z_:]/))
1274 or ($stash eq $self->{'curstash'} && !$globalnames{$name}
1275 && ($stash eq 'main' || $name !~ /::/))
1280 $stash = $stash . "::";
1282 if (!$raw and $name =~ /^(\^..|{)/) {
1283 $name = "{$name}"; # ${^WARNING_BITS}, etc and ${
1285 return $stash . $name;
1288 # Return the name to use for a stash variable.
1289 # If a lexical with the same name is in scope, or
1290 # if strictures are enabled, it may need to be
1292 sub stash_variable {
1293 my ($self, $prefix, $name, $cx) = @_;
1295 return "$prefix$name" if $name =~ /::/;
1297 unless ($prefix eq '$' || $prefix eq '@' || #'
1298 $prefix eq '%' || $prefix eq '$#') {
1299 return "$prefix$name";
1302 if ($name =~ /^[^\w+-]$/) {
1303 if (defined $cx && $cx == 26) {
1304 if ($prefix eq '@') {
1305 return "$prefix\{$name}";
1307 elsif ($name eq '#') { return '${#}' } # "${#}a" vs "$#a"
1309 if ($prefix eq '$#') {
1310 return "\$#{$name}";
1314 return $prefix . $self->maybe_qualify($prefix, $name);
1317 # Return just the name, without the prefix. It may be returned as a quoted
1318 # string. The second return value is a boolean indicating that.
1319 sub stash_variable_name {
1320 my($self, $prefix, $gv) = @_;
1321 my $name = $self->gv_name($gv, 1);
1322 $name = $self->maybe_qualify($prefix,$name);
1323 if ($name =~ /^(?:\S|(?!\d)[\ca-\cz]?(?:\w|::)*|\d+)\z/) {
1324 $name =~ s/^([\ca-\cz])/'^'.($1|'@')/e;
1325 $name =~ /^(\^..|{)/ and $name = "{$name}";
1326 return $name, 0; # not quoted
1329 single_delim("q", "'", $name), 1;
1334 my ($self,$prefix,$name) = @_;
1335 my $v = ($prefix eq '$#' ? '@' : $prefix) . $name;
1336 return $name if !$prefix || $name =~ /::/;
1337 return $self->{'curstash'}.'::'. $name
1339 $name =~ /^(?!\d)\w/ # alphabetic
1340 && $v !~ /^\$[ab]\z/ # not $a or $b
1341 && !$globalnames{$name} # not a global name
1342 && $self->{hints} & $strict_bits{vars} # strict vars
1343 && !$self->lex_in_scope($v,1) # no "our"
1344 or $self->lex_in_scope($v); # conflicts with "my" variable
1349 my ($self, $name, $our) = @_;
1350 substr $name, 0, 0, = $our ? 'o' : 'm'; # our/my
1351 $self->populate_curcvlex() if !defined $self->{'curcvlex'};
1353 return 0 if !defined($self->{'curcop'});
1354 my $seq = $self->{'curcop'}->cop_seq;
1355 return 0 if !exists $self->{'curcvlex'}{$name};
1356 for my $a (@{$self->{'curcvlex'}{$name}}) {
1357 my ($st, $en) = @$a;
1358 return 1 if $seq > $st && $seq <= $en;
1363 sub populate_curcvlex {
1365 for (my $cv = $self->{'curcv'}; class($cv) eq "CV"; $cv = $cv->OUTSIDE) {
1366 my $padlist = $cv->PADLIST;
1367 # an undef CV still in lexical chain
1368 next if class($padlist) eq "SPECIAL";
1369 my @padlist = $padlist->ARRAY;
1370 my @ns = $padlist[0]->ARRAY;
1372 for (my $i=0; $i<@ns; ++$i) {
1373 next if class($ns[$i]) eq "SPECIAL";
1374 if (class($ns[$i]) eq "PV") {
1375 # Probably that pesky lexical @_
1378 my $name = $ns[$i]->PVX;
1379 my ($seq_st, $seq_en) =
1380 ($ns[$i]->FLAGS & SVf_FAKE)
1382 : ($ns[$i]->COP_SEQ_RANGE_LOW, $ns[$i]->COP_SEQ_RANGE_HIGH);
1384 push @{$self->{'curcvlex'}{
1385 ($ns[$i]->FLAGS & SVpad_OUR ? 'o' : 'm') . $name
1386 }}, [$seq_st, $seq_en];
1391 sub find_scope_st { ((find_scope(@_))[0]); }
1392 sub find_scope_en { ((find_scope(@_))[1]); }
1394 # Recurses down the tree, looking for pad variable introductions and COPs
1396 my ($self, $op, $scope_st, $scope_en) = @_;
1397 carp("Undefined op in find_scope") if !defined $op;
1398 return ($scope_st, $scope_en) unless $op->flags & OPf_KIDS;
1401 while(my $op = shift @queue ) {
1402 for (my $o=$op->first; $$o; $o=$o->sibling) {
1403 if ($o->name =~ /^pad.v$/ && $o->private & OPpLVAL_INTRO) {
1404 my $s = int($self->padname_sv($o->targ)->COP_SEQ_RANGE_LOW);
1405 my $e = $self->padname_sv($o->targ)->COP_SEQ_RANGE_HIGH;
1406 $scope_st = $s if !defined($scope_st) || $s < $scope_st;
1407 $scope_en = $e if !defined($scope_en) || $e > $scope_en;
1408 return ($scope_st, $scope_en);
1410 elsif (is_state($o)) {
1411 my $c = $o->cop_seq;
1412 $scope_st = $c if !defined($scope_st) || $c < $scope_st;
1413 $scope_en = $c if !defined($scope_en) || $c > $scope_en;
1414 return ($scope_st, $scope_en);
1416 elsif ($o->flags & OPf_KIDS) {
1417 unshift (@queue, $o);
1422 return ($scope_st, $scope_en);
1425 # Returns a list of subs which should be inserted before the COP
1427 my ($self, $op, $out_seq) = @_;
1428 my $seq = $op->cop_seq;
1429 # If we have nephews, then our sequence number indicates
1430 # the cop_seq of the end of some sort of scope.
1431 if (class($op->sibling) ne "NULL" && $op->sibling->flags & OPf_KIDS
1432 and my $nseq = $self->find_scope_st($op->sibling) ) {
1435 $seq = $out_seq if defined($out_seq) && $out_seq < $seq;
1436 return $self->seq_subs($seq);
1440 my ($self, $seq) = @_;
1442 #push @text, "# ($seq)\n";
1444 return "" if !defined $seq;
1445 while (scalar(@{$self->{'subs_todo'}})
1446 and $seq > $self->{'subs_todo'}[0][0]) {
1447 push @text, $self->next_todo;
1452 sub _features_from_bundle {
1453 my ($hints, $hh) = @_;
1454 foreach (@{$feature::feature_bundle{@feature::hint_bundles[$hints >> $feature::hint_shift]}}) {
1455 $hh->{$feature::feature{$_}} = 1;
1460 # Notice how subs and formats are inserted between statements here;
1461 # also $[ assignments and pragmas.
1465 $self->{'curcop'} = $op;
1467 push @text, $self->cop_subs($op);
1468 my $stash = $op->stashpv;
1469 if ($stash ne $self->{'curstash'}) {
1470 push @text, "package $stash;\n";
1471 $self->{'curstash'} = $stash;
1474 if (OPpCONST_ARYBASE && $self->{'arybase'} != $op->arybase) {
1475 push @text, '$[ = '. $op->arybase .";\n";
1476 $self->{'arybase'} = $op->arybase;
1479 my $warnings = $op->warnings;
1481 if ($warnings->isa("B::SPECIAL") && $$warnings == 4) {
1482 $warning_bits = $warnings::Bits{"all"} & WARN_MASK;
1484 elsif ($warnings->isa("B::SPECIAL") && $$warnings == 5) {
1485 $warning_bits = $warnings::NONE;
1487 elsif ($warnings->isa("B::SPECIAL")) {
1488 $warning_bits = undef;
1491 $warning_bits = $warnings->PV & WARN_MASK;
1494 if (defined ($warning_bits) and
1495 !defined($self->{warnings}) || $self->{'warnings'} ne $warning_bits) {
1496 push @text, declare_warnings($self->{'warnings'}, $warning_bits);
1497 $self->{'warnings'} = $warning_bits;
1500 my $hints = $] < 5.008009 ? $op->private : $op->hints;
1501 my $old_hints = $self->{'hints'};
1502 if ($self->{'hints'} != $hints) {
1503 push @text, declare_hints($self->{'hints'}, $hints);
1504 $self->{'hints'} = $hints;
1509 $newhh = $op->hints_hash->HASH;
1512 if ($] >= 5.015006) {
1513 # feature bundle hints
1514 my $from = $old_hints & $feature::hint_mask;
1515 my $to = $ hints & $feature::hint_mask;
1517 if ($to == $feature::hint_mask) {
1518 if ($self->{'hinthash'}) {
1519 delete $self->{'hinthash'}{$_}
1520 for grep /^feature_/, keys %{$self->{'hinthash'}};
1522 else { $self->{'hinthash'} = {} }
1524 = _features_from_bundle($from, $self->{'hinthash'});
1528 $feature::hint_bundles[$to >> $feature::hint_shift];
1529 $bundle =~ s/(\d[13579])\z/$1+1/e; # 5.11 => 5.12
1530 push @text, "no feature;\n",
1531 "use feature ':$bundle';\n";
1537 push @text, declare_hinthash(
1538 $self->{'hinthash'}, $newhh,
1539 $self->{indent_size}, $self->{hints},
1541 $self->{'hinthash'} = $newhh;
1544 # This should go after of any branches that add statements, to
1545 # increase the chances that it refers to the same line it did in
1546 # the original program.
1547 if ($self->{'linenums'}) {
1548 push @text, "\f#line " . $op->line .
1549 ' "' . $op->file, qq'"\n';
1552 push @text, $op->label . ": " if $op->label;
1554 return join("", @text);
1557 sub declare_warnings {
1558 my ($from, $to) = @_;
1559 if (($to & WARN_MASK) eq (warnings::bits("all") & WARN_MASK)) {
1560 return "use warnings;\n";
1562 elsif (($to & WARN_MASK) eq ("\0"x length($to) & WARN_MASK)) {
1563 return "no warnings;\n";
1565 return "BEGIN {\${^WARNING_BITS} = ".perlstring($to)."}\n";
1569 my ($from, $to) = @_;
1570 my $use = $to & ~$from;
1571 my $no = $from & ~$to;
1573 for my $pragma (hint_pragmas($use)) {
1574 $decls .= "use $pragma;\n";
1576 for my $pragma (hint_pragmas($no)) {
1577 $decls .= "no $pragma;\n";
1582 # Internal implementation hints that the core sets automatically, so don't need
1583 # (or want) to be passed back to the user
1584 my %ignored_hints = (
1595 sub declare_hinthash {
1596 my ($from, $to, $indent, $hints) = @_;
1597 my $doing_features =
1598 ($hints & $feature::hint_mask) == $feature::hint_mask;
1601 my @unfeatures; # bugs?
1602 for my $key (sort keys %$to) {
1603 next if $ignored_hints{$key};
1604 my $is_feature = $key =~ /^feature_/ && $^V ge 5.15.6;
1605 next if $is_feature and not $doing_features;
1606 if (!exists $from->{$key} or $from->{$key} ne $to->{$key}) {
1607 push(@features, $key), next if $is_feature;
1609 qq(\$^H{) . single_delim("q", "'", $key) . qq(} = )
1612 ? single_delim("q", "'", $to->{$key})
1618 for my $key (sort keys %$from) {
1619 next if $ignored_hints{$key};
1620 my $is_feature = $key =~ /^feature_/ && $^V ge 5.15.6;
1621 next if $is_feature and not $doing_features;
1622 if (!exists $to->{$key}) {
1623 push(@unfeatures, $key), next if $is_feature;
1624 push @decls, qq(delete \$^H{'$key'};);
1628 if (@features || @unfeatures) {
1629 if (!%rev_feature) { %rev_feature = reverse %feature::feature }
1632 push @ret, "use feature "
1633 . join(", ", map "'$rev_feature{$_}'", @features) . ";\n";
1636 push @ret, "no feature "
1637 . join(", ", map "'$rev_feature{$_}'", @unfeatures)
1642 join("\n" . (" " x $indent), "BEGIN {", @decls) . "\n}\n";
1648 my (@pragmas, @strict);
1649 push @pragmas, "integer" if $bits & 0x1;
1650 for (sort keys %strict_bits) {
1651 push @strict, "'$_'" if $bits & $strict_bits{$_};
1653 if (@strict == keys %strict_bits) {
1654 push @pragmas, "strict";
1657 push @pragmas, "strict " . join ', ', @strict;
1659 push @pragmas, "bytes" if $bits & 0x8;
1663 sub pp_dbstate { pp_nextstate(@_) }
1664 sub pp_setstate { pp_nextstate(@_) }
1666 sub pp_unstack { return "" } # see also leaveloop
1668 my %feature_keywords = (
1669 # keyword => 'feature',
1674 default => 'switch',
1676 evalbytes=>'evalbytes',
1677 __SUB__ => '__SUB__',
1684 return $name if $name =~ /^CORE::/; # just in case
1685 if (exists $feature_keywords{$name}) {
1687 my $hints = $self->{hints} & $feature::hint_mask;
1688 if ($hints && $hints != $feature::hint_mask) {
1689 $hh = _features_from_bundle($hints);
1691 elsif ($hints) { $hh = $self->{'hinthash'} }
1692 return "CORE::$name"
1694 || !$hh->{"feature_$feature_keywords{$name}"}
1697 $name !~ /^(?:chom?p|do|exec|glob|s(?:elect|ystem))\z/
1698 && !defined eval{prototype "CORE::$name"}
1701 exists $self->{subs_declared}{$name}
1703 exists &{"$self->{curstash}::$name"}
1705 return "CORE::$name"
1712 my($op, $cx, $name) = @_;
1713 return $self->keyword($name);
1718 my($op, $cx, $name) = @_;
1726 sub pp_wantarray { baseop(@_, "wantarray") }
1727 sub pp_fork { baseop(@_, "fork") }
1728 sub pp_wait { maybe_targmy(@_, \&baseop, "wait") }
1729 sub pp_getppid { maybe_targmy(@_, \&baseop, "getppid") }
1730 sub pp_time { maybe_targmy(@_, \&baseop, "time") }
1731 sub pp_tms { baseop(@_, "times") }
1732 sub pp_ghostent { baseop(@_, "gethostent") }
1733 sub pp_gnetent { baseop(@_, "getnetent") }
1734 sub pp_gprotoent { baseop(@_, "getprotoent") }
1735 sub pp_gservent { baseop(@_, "getservent") }
1736 sub pp_ehostent { baseop(@_, "endhostent") }
1737 sub pp_enetent { baseop(@_, "endnetent") }
1738 sub pp_eprotoent { baseop(@_, "endprotoent") }
1739 sub pp_eservent { baseop(@_, "endservent") }
1740 sub pp_gpwent { baseop(@_, "getpwent") }
1741 sub pp_spwent { baseop(@_, "setpwent") }
1742 sub pp_epwent { baseop(@_, "endpwent") }
1743 sub pp_ggrent { baseop(@_, "getgrent") }
1744 sub pp_sgrent { baseop(@_, "setgrent") }
1745 sub pp_egrent { baseop(@_, "endgrent") }
1746 sub pp_getlogin { baseop(@_, "getlogin") }
1748 sub POSTFIX () { 1 }
1750 # I couldn't think of a good short name, but this is the category of
1751 # symbolic unary operators with interesting precedence
1755 my($op, $cx, $name, $prec, $flags) = (@_, 0);
1756 my $kid = $op->first;
1757 $kid = $self->deparse($kid, $prec);
1758 return $self->maybe_parens(($flags & POSTFIX)
1760 # avoid confusion with filetests
1762 && $kid =~ /^[a-zA-Z](?!\w)/
1768 sub pp_preinc { pfixop(@_, "++", 23) }
1769 sub pp_predec { pfixop(@_, "--", 23) }
1770 sub pp_postinc { maybe_targmy(@_, \&pfixop, "++", 23, POSTFIX) }
1771 sub pp_postdec { maybe_targmy(@_, \&pfixop, "--", 23, POSTFIX) }
1772 sub pp_i_preinc { pfixop(@_, "++", 23) }
1773 sub pp_i_predec { pfixop(@_, "--", 23) }
1774 sub pp_i_postinc { maybe_targmy(@_, \&pfixop, "++", 23, POSTFIX) }
1775 sub pp_i_postdec { maybe_targmy(@_, \&pfixop, "--", 23, POSTFIX) }
1776 sub pp_complement { maybe_targmy(@_, \&pfixop, "~", 21) }
1778 sub pp_negate { maybe_targmy(@_, \&real_negate) }
1782 if ($op->first->name =~ /^(i_)?negate$/) {
1784 $self->pfixop($op, $cx, "-", 21.5);
1786 $self->pfixop($op, $cx, "-", 21);
1789 sub pp_i_negate { pp_negate(@_) }
1795 $self->listop($op, $cx, "not", $op->first);
1797 $self->pfixop($op, $cx, "!", 21);
1803 my($op, $cx, $name, $nollafr) = @_;
1805 if ($op->flags & OPf_KIDS) {
1808 # this deals with 'boolkeys' right now
1809 return $self->deparse($kid,$cx);
1811 my $builtinname = $name;
1812 $builtinname =~ /^CORE::/ or $builtinname = "CORE::$name";
1813 if (defined prototype($builtinname)
1814 && prototype($builtinname) =~ /^;?\*/
1815 && $kid->name eq "rv2gv") {
1820 ($kid = $self->deparse($kid, 16)) =~ s/^\cS//;
1821 return $self->maybe_parens(
1822 $self->keyword($name) . " $kid", $cx, 16
1825 return $self->maybe_parens_unop($name, $kid, $cx);
1827 return $self->maybe_parens(
1828 $self->keyword($name) . ($op->flags & OPf_SPECIAL ? "()" : ""),
1834 sub pp_chop { maybe_targmy(@_, \&unop, "chop") }
1835 sub pp_chomp { maybe_targmy(@_, \&unop, "chomp") }
1836 sub pp_schop { maybe_targmy(@_, \&unop, "chop") }
1837 sub pp_schomp { maybe_targmy(@_, \&unop, "chomp") }
1838 sub pp_defined { unop(@_, "defined") }
1839 sub pp_undef { unop(@_, "undef") }
1840 sub pp_study { unop(@_, "study") }
1841 sub pp_ref { unop(@_, "ref") }
1842 sub pp_pos { maybe_local(@_, unop(@_, "pos")) }
1844 sub pp_sin { maybe_targmy(@_, \&unop, "sin") }
1845 sub pp_cos { maybe_targmy(@_, \&unop, "cos") }
1846 sub pp_rand { maybe_targmy(@_, \&unop, "rand") }
1847 sub pp_srand { unop(@_, "srand") }
1848 sub pp_exp { maybe_targmy(@_, \&unop, "exp") }
1849 sub pp_log { maybe_targmy(@_, \&unop, "log") }
1850 sub pp_sqrt { maybe_targmy(@_, \&unop, "sqrt") }
1851 sub pp_int { maybe_targmy(@_, \&unop, "int") }
1852 sub pp_hex { maybe_targmy(@_, \&unop, "hex") }
1853 sub pp_oct { maybe_targmy(@_, \&unop, "oct") }
1854 sub pp_abs { maybe_targmy(@_, \&unop, "abs") }
1856 sub pp_length { maybe_targmy(@_, \&unop, "length") }
1857 sub pp_ord { maybe_targmy(@_, \&unop, "ord") }
1858 sub pp_chr { maybe_targmy(@_, \&unop, "chr") }
1860 sub pp_each { unop(@_, "each") }
1861 sub pp_values { unop(@_, "values") }
1862 sub pp_keys { unop(@_, "keys") }
1863 { no strict 'refs'; *{"pp_r$_"} = *{"pp_$_"} for qw< keys each values >; }
1865 # no name because its an optimisation op that has no keyword
1868 sub pp_aeach { unop(@_, "each") }
1869 sub pp_avalues { unop(@_, "values") }
1870 sub pp_akeys { unop(@_, "keys") }
1871 sub pp_pop { unop(@_, "pop") }
1872 sub pp_shift { unop(@_, "shift") }
1874 sub pp_caller { unop(@_, "caller") }
1875 sub pp_reset { unop(@_, "reset") }
1876 sub pp_exit { unop(@_, "exit") }
1877 sub pp_prototype { unop(@_, "prototype") }
1879 sub pp_close { unop(@_, "close") }
1880 sub pp_fileno { unop(@_, "fileno") }
1881 sub pp_umask { unop(@_, "umask") }
1882 sub pp_untie { unop(@_, "untie") }
1883 sub pp_tied { unop(@_, "tied") }
1884 sub pp_dbmclose { unop(@_, "dbmclose") }
1885 sub pp_getc { unop(@_, "getc") }
1886 sub pp_eof { unop(@_, "eof") }
1887 sub pp_tell { unop(@_, "tell") }
1888 sub pp_getsockname { unop(@_, "getsockname") }
1889 sub pp_getpeername { unop(@_, "getpeername") }
1891 sub pp_chdir { maybe_targmy(@_, \&unop, "chdir") }
1892 sub pp_chroot { maybe_targmy(@_, \&unop, "chroot") }
1893 sub pp_readlink { unop(@_, "readlink") }
1894 sub pp_rmdir { maybe_targmy(@_, \&unop, "rmdir") }
1895 sub pp_readdir { unop(@_, "readdir") }
1896 sub pp_telldir { unop(@_, "telldir") }
1897 sub pp_rewinddir { unop(@_, "rewinddir") }
1898 sub pp_closedir { unop(@_, "closedir") }
1899 sub pp_getpgrp { maybe_targmy(@_, \&unop, "getpgrp") }
1900 sub pp_localtime { unop(@_, "localtime") }
1901 sub pp_gmtime { unop(@_, "gmtime") }
1902 sub pp_alarm { unop(@_, "alarm") }
1903 sub pp_sleep { maybe_targmy(@_, \&unop, "sleep") }
1906 my $code = unop(@_, "do", 1); # llafr does not apply
1907 if ($code =~ s/^((?:CORE::)?do) \{/$1({/) { $code .= ')' }
1913 $_[1]->private & OPpEVAL_BYTES ? $_[0]->keyword('evalbytes') : "eval"
1917 sub pp_ghbyname { unop(@_, "gethostbyname") }
1918 sub pp_gnbyname { unop(@_, "getnetbyname") }
1919 sub pp_gpbyname { unop(@_, "getprotobyname") }
1920 sub pp_shostent { unop(@_, "sethostent") }
1921 sub pp_snetent { unop(@_, "setnetent") }
1922 sub pp_sprotoent { unop(@_, "setprotoent") }
1923 sub pp_sservent { unop(@_, "setservent") }
1924 sub pp_gpwnam { unop(@_, "getpwnam") }
1925 sub pp_gpwuid { unop(@_, "getpwuid") }
1926 sub pp_ggrnam { unop(@_, "getgrnam") }
1927 sub pp_ggrgid { unop(@_, "getgrgid") }
1929 sub pp_lock { unop(@_, "lock") }
1931 sub pp_continue { unop(@_, "continue"); }
1932 sub pp_break { unop(@_, "break"); }
1936 my($op, $cx, $givwhen) = @_;
1938 my $enterop = $op->first;
1940 if ($enterop->flags & OPf_SPECIAL) {
1941 $head = $self->keyword("default");
1942 $block = $self->deparse($enterop->first, 0);
1945 my $cond = $enterop->first;
1946 my $cond_str = $self->deparse($cond, 1);
1947 $head = "$givwhen ($cond_str)";
1948 $block = $self->deparse($cond->sibling, 0);
1956 sub pp_leavegiven { givwhen(@_, $_[0]->keyword("given")); }
1957 sub pp_leavewhen { givwhen(@_, $_[0]->keyword("when")); }
1963 if ($op->private & OPpEXISTS_SUB) {
1964 # Checking for the existence of a subroutine
1965 return $self->maybe_parens_func("exists",
1966 $self->pp_rv2cv($op->first, 16), $cx, 16);
1968 if ($op->flags & OPf_SPECIAL) {
1969 # Array element, not hash element
1970 return $self->maybe_parens_func("exists",
1971 $self->pp_aelem($op->first, 16), $cx, 16);
1973 return $self->maybe_parens_func("exists", $self->pp_helem($op->first, 16),
1981 if ($op->private & OPpSLICE) {
1982 if ($op->flags & OPf_SPECIAL) {
1983 # Deleting from an array, not a hash
1984 return $self->maybe_parens_func("delete",
1985 $self->pp_aslice($op->first, 16),
1988 return $self->maybe_parens_func("delete",
1989 $self->pp_hslice($op->first, 16),
1992 if ($op->flags & OPf_SPECIAL) {
1993 # Deleting from an array, not a hash
1994 return $self->maybe_parens_func("delete",
1995 $self->pp_aelem($op->first, 16),
1998 return $self->maybe_parens_func("delete",
1999 $self->pp_helem($op->first, 16),
2007 my $opname = $op->flags & OPf_SPECIAL ? 'CORE::require' : 'require';
2008 if (class($op) eq "UNOP" and $op->first->name eq "const"
2009 and $op->first->private & OPpCONST_BARE)
2011 my $name = $self->const_sv($op->first)->PV;
2014 return $self->maybe_parens("$opname $name", $cx, 16);
2018 $op->first->name eq 'const'
2019 && $op->first->private & OPpCONST_NOVER
2022 1, # llafr does not apply
2030 my $kid = $op->first;
2031 if (not null $kid->sibling) {
2032 # XXX Was a here-doc
2033 return $self->dquote($op);
2035 $self->unop(@_, "scalar");
2042 return $self->{'curcv'}->PADLIST->ARRAYelt(1)->ARRAYelt($targ);
2045 sub anon_hash_or_list {
2049 my($pre, $post) = @{{"anonlist" => ["[","]"],
2050 "anonhash" => ["{","}"]}->{$op->name}};
2052 $op = $op->first->sibling; # skip pushmark
2053 for (; !null($op); $op = $op->sibling) {
2054 $expr = $self->deparse($op, 6);
2057 if ($pre eq "{" and $cx < 1) {
2058 # Disambiguate that it's not a block
2061 return $pre . join(", ", @exprs) . $post;
2067 if ($op->flags & OPf_SPECIAL) {
2068 return $self->anon_hash_or_list($op, $cx);
2070 warn "Unexpected op pp_" . $op->name() . " without OPf_SPECIAL";
2074 *pp_anonhash = \&pp_anonlist;
2079 my $kid = $op->first;
2080 if ($kid->name eq "null") {
2082 if (!null($kid->sibling) and
2083 $kid->sibling->name eq "anoncode") {
2084 return $self->e_anoncode({ code => $self->padval($kid->sibling->targ) });
2085 } elsif ($kid->name eq "pushmark") {
2086 my $sib_name = $kid->sibling->name;
2087 if ($sib_name =~ /^(pad|rv2)[ah]v$/
2088 and not $kid->sibling->flags & OPf_REF)
2090 # The @a in \(@a) isn't in ref context, but only when the
2092 return "\\(" . $self->pp_list($op->first) . ")";
2093 } elsif ($sib_name eq 'entersub') {
2094 my $text = $self->deparse($kid->sibling, 1);
2095 # Always show parens for \(&func()), but only with -p otherwise
2096 $text = "($text)" if $self->{'parens'}
2097 or $kid->sibling->private & OPpENTERSUB_AMPER;
2102 $self->pfixop($op, $cx, "\\", 20);
2106 my ($self, $info) = @_;
2107 my $text = $self->deparse_sub($info->{code});
2108 return "sub " . $text;
2111 sub pp_srefgen { pp_refgen(@_) }
2116 my $kid = $op->first;
2117 $kid = $kid->first if $kid->name eq "rv2gv"; # <$fh>
2118 return "<" . $self->deparse($kid, 1) . ">" if is_scalar($kid);
2119 return $self->unop($op, $cx, "readline");
2125 return "<" . $self->gv_name($self->gv_or_padgv($op)) . ">";
2128 # Unary operators that can occur as pseudo-listops inside double quotes
2131 my($op, $cx, $name, $prec, $flags) = (@_, 0, 0);
2133 if ($op->flags & OPf_KIDS) {
2135 # If there's more than one kid, the first is an ex-pushmark.
2136 $kid = $kid->sibling if not null $kid->sibling;
2137 return $self->maybe_parens_unop($name, $kid, $cx);
2139 return $name . ($op->flags & OPf_SPECIAL ? "()" : "");
2143 sub pp_ucfirst { dq_unop(@_, "ucfirst") }
2144 sub pp_lcfirst { dq_unop(@_, "lcfirst") }
2145 sub pp_uc { dq_unop(@_, "uc") }
2146 sub pp_lc { dq_unop(@_, "lc") }
2147 sub pp_quotemeta { maybe_targmy(@_, \&dq_unop, "quotemeta") }
2148 sub pp_fc { dq_unop(@_, "fc") }
2152 my ($op, $cx, $name) = @_;
2153 if (class($op) eq "PVOP") {
2154 $name .= " " . $op->pv;
2155 } elsif (class($op) eq "OP") {
2157 } elsif (class($op) eq "UNOP") {
2158 (my $kid = $self->deparse($op->first, 7)) =~ s/^\cS//;
2161 return $self->maybe_parens($name, $cx, 7);
2164 sub pp_last { loopex(@_, "last") }
2165 sub pp_next { loopex(@_, "next") }
2166 sub pp_redo { loopex(@_, "redo") }
2167 sub pp_goto { loopex(@_, "goto") }
2168 sub pp_dump { loopex(@_, "CORE::dump") }
2172 my($op, $cx, $name) = @_;
2173 if (class($op) eq "UNOP") {
2174 # Genuine '-X' filetests are exempt from the LLAFR, but not
2176 if ($name =~ /^-/) {
2177 (my $kid = $self->deparse($op->first, 16)) =~ s/^\cS//;
2178 return $self->maybe_parens("$name $kid", $cx, 16);
2180 return $self->maybe_parens_unop($name, $op->first, $cx);
2181 } elsif (class($op) =~ /^(SV|PAD)OP$/) {
2182 return $self->maybe_parens_func($name, $self->pp_gv($op, 1), $cx, 16);
2183 } else { # I don't think baseop filetests ever survive ck_ftst, but...
2188 sub pp_lstat { ftst(@_, "lstat") }
2189 sub pp_stat { ftst(@_, "stat") }
2190 sub pp_ftrread { ftst(@_, "-R") }
2191 sub pp_ftrwrite { ftst(@_, "-W") }
2192 sub pp_ftrexec { ftst(@_, "-X") }
2193 sub pp_fteread { ftst(@_, "-r") }
2194 sub pp_ftewrite { ftst(@_, "-w") }
2195 sub pp_fteexec { ftst(@_, "-x") }
2196 sub pp_ftis { ftst(@_, "-e") }
2197 sub pp_fteowned { ftst(@_, "-O") }
2198 sub pp_ftrowned { ftst(@_, "-o") }
2199 sub pp_ftzero { ftst(@_, "-z") }
2200 sub pp_ftsize { ftst(@_, "-s") }
2201 sub pp_ftmtime { ftst(@_, "-M") }
2202 sub pp_ftatime { ftst(@_, "-A") }
2203 sub pp_ftctime { ftst(@_, "-C") }
2204 sub pp_ftsock { ftst(@_, "-S") }
2205 sub pp_ftchr { ftst(@_, "-c") }
2206 sub pp_ftblk { ftst(@_, "-b") }
2207 sub pp_ftfile { ftst(@_, "-f") }
2208 sub pp_ftdir { ftst(@_, "-d") }
2209 sub pp_ftpipe { ftst(@_, "-p") }
2210 sub pp_ftlink { ftst(@_, "-l") }
2211 sub pp_ftsuid { ftst(@_, "-u") }
2212 sub pp_ftsgid { ftst(@_, "-g") }
2213 sub pp_ftsvtx { ftst(@_, "-k") }
2214 sub pp_fttty { ftst(@_, "-t") }
2215 sub pp_fttext { ftst(@_, "-T") }
2216 sub pp_ftbinary { ftst(@_, "-B") }
2218 sub SWAP_CHILDREN () { 1 }
2219 sub ASSIGN () { 2 } # has OP= variant
2220 sub LIST_CONTEXT () { 4 } # Assignment is in list context
2226 my $name = $op->name;
2227 if ($name eq "concat" and $op->first->name eq "concat") {
2228 # avoid spurious '=' -- see comment in pp_concat
2231 if ($name eq "null" and class($op) eq "UNOP"
2232 and $op->first->name =~ /^(and|x?or)$/
2233 and null $op->first->sibling)
2235 # Like all conditional constructs, OP_ANDs and OP_ORs are topped
2236 # with a null that's used as the common end point of the two
2237 # flows of control. For precedence purposes, ignore it.
2238 # (COND_EXPRs have these too, but we don't bother with
2239 # their associativity).
2240 return assoc_class($op->first);
2242 return $name . ($op->flags & OPf_STACKED ? "=" : "");
2245 # Left associative operators, like '+', for which
2246 # $a + $b + $c is equivalent to ($a + $b) + $c
2249 %left = ('multiply' => 19, 'i_multiply' => 19,
2250 'divide' => 19, 'i_divide' => 19,
2251 'modulo' => 19, 'i_modulo' => 19,
2253 'add' => 18, 'i_add' => 18,
2254 'subtract' => 18, 'i_subtract' => 18,
2256 'left_shift' => 17, 'right_shift' => 17,
2258 'bit_or' => 12, 'bit_xor' => 12,
2260 'or' => 2, 'xor' => 2,
2264 sub deparse_binop_left {
2266 my($op, $left, $prec) = @_;
2267 if ($left{assoc_class($op)} && $left{assoc_class($left)}
2268 and $left{assoc_class($op)} == $left{assoc_class($left)})
2270 return $self->deparse($left, $prec - .00001);
2272 return $self->deparse($left, $prec);
2276 # Right associative operators, like '=', for which
2277 # $a = $b = $c is equivalent to $a = ($b = $c)
2280 %right = ('pow' => 22,
2281 'sassign=' => 7, 'aassign=' => 7,
2282 'multiply=' => 7, 'i_multiply=' => 7,
2283 'divide=' => 7, 'i_divide=' => 7,
2284 'modulo=' => 7, 'i_modulo=' => 7,
2286 'add=' => 7, 'i_add=' => 7,
2287 'subtract=' => 7, 'i_subtract=' => 7,
2289 'left_shift=' => 7, 'right_shift=' => 7,
2291 'bit_or=' => 7, 'bit_xor=' => 7,
2297 sub deparse_binop_right {
2299 my($op, $right, $prec) = @_;
2300 if ($right{assoc_class($op)} && $right{assoc_class($right)}
2301 and $right{assoc_class($op)} == $right{assoc_class($right)})
2303 return $self->deparse($right, $prec - .00001);
2305 return $self->deparse($right, $prec);
2311 my ($op, $cx, $opname, $prec, $flags) = (@_, 0);
2312 my $left = $op->first;
2313 my $right = $op->last;
2315 if ($op->flags & OPf_STACKED && $flags & ASSIGN) {
2319 if ($flags & SWAP_CHILDREN) {
2320 ($left, $right) = ($right, $left);
2322 $left = $self->deparse_binop_left($op, $left, $prec);
2323 $left = "($left)" if $flags & LIST_CONTEXT
2324 && $left !~ /^(my|our|local|)[\@\(]/;
2325 $right = $self->deparse_binop_right($op, $right, $prec);
2326 return $self->maybe_parens("$left $opname$eq $right", $cx, $prec);
2329 sub pp_add { maybe_targmy(@_, \&binop, "+", 18, ASSIGN) }
2330 sub pp_multiply { maybe_targmy(@_, \&binop, "*", 19, ASSIGN) }
2331 sub pp_subtract { maybe_targmy(@_, \&binop, "-",18, ASSIGN) }
2332 sub pp_divide { maybe_targmy(@_, \&binop, "/", 19, ASSIGN) }
2333 sub pp_modulo { maybe_targmy(@_, \&binop, "%", 19, ASSIGN) }
2334 sub pp_i_add { maybe_targmy(@_, \&binop, "+", 18, ASSIGN) }
2335 sub pp_i_multiply { maybe_targmy(@_, \&binop, "*", 19, ASSIGN) }
2336 sub pp_i_subtract { maybe_targmy(@_, \&binop, "-", 18, ASSIGN) }
2337 sub pp_i_divide { maybe_targmy(@_, \&binop, "/", 19, ASSIGN) }
2338 sub pp_i_modulo { maybe_targmy(@_, \&binop, "%", 19, ASSIGN) }
2339 sub pp_pow { maybe_targmy(@_, \&binop, "**", 22, ASSIGN) }
2341 sub pp_left_shift { maybe_targmy(@_, \&binop, "<<", 17, ASSIGN) }
2342 sub pp_right_shift { maybe_targmy(@_, \&binop, ">>", 17, ASSIGN) }
2343 sub pp_bit_and { maybe_targmy(@_, \&binop, "&", 13, ASSIGN) }
2344 sub pp_bit_or { maybe_targmy(@_, \&binop, "|", 12, ASSIGN) }
2345 sub pp_bit_xor { maybe_targmy(@_, \&binop, "^", 12, ASSIGN) }
2347 sub pp_eq { binop(@_, "==", 14) }
2348 sub pp_ne { binop(@_, "!=", 14) }
2349 sub pp_lt { binop(@_, "<", 15) }
2350 sub pp_gt { binop(@_, ">", 15) }
2351 sub pp_ge { binop(@_, ">=", 15) }
2352 sub pp_le { binop(@_, "<=", 15) }
2353 sub pp_ncmp { binop(@_, "<=>", 14) }
2354 sub pp_i_eq { binop(@_, "==", 14) }
2355 sub pp_i_ne { binop(@_, "!=", 14) }
2356 sub pp_i_lt { binop(@_, "<", 15) }
2357 sub pp_i_gt { binop(@_, ">", 15) }
2358 sub pp_i_ge { binop(@_, ">=", 15) }
2359 sub pp_i_le { binop(@_, "<=", 15) }
2360 sub pp_i_ncmp { binop(@_, "<=>", 14) }
2362 sub pp_seq { binop(@_, "eq", 14) }
2363 sub pp_sne { binop(@_, "ne", 14) }
2364 sub pp_slt { binop(@_, "lt", 15) }
2365 sub pp_sgt { binop(@_, "gt", 15) }
2366 sub pp_sge { binop(@_, "ge", 15) }
2367 sub pp_sle { binop(@_, "le", 15) }
2368 sub pp_scmp { binop(@_, "cmp", 14) }
2370 sub pp_sassign { binop(@_, "=", 7, SWAP_CHILDREN) }
2371 sub pp_aassign { binop(@_, "=", 7, SWAP_CHILDREN | LIST_CONTEXT) }
2374 my ($self, $op, $cx) = @_;
2375 if ($op->flags & OPf_SPECIAL) {
2376 return $self->deparse($op->last, $cx);
2379 binop(@_, "~~", 14);
2383 # '.' is special because concats-of-concats are optimized to save copying
2384 # by making all but the first concat stacked. The effect is as if the
2385 # programmer had written '($a . $b) .= $c', except legal.
2386 sub pp_concat { maybe_targmy(@_, \&real_concat) }
2390 my $left = $op->first;
2391 my $right = $op->last;
2394 if ($op->flags & OPf_STACKED and $op->first->name ne "concat") {
2398 $left = $self->deparse_binop_left($op, $left, $prec);
2399 $right = $self->deparse_binop_right($op, $right, $prec);
2400 return $self->maybe_parens("$left .$eq $right", $cx, $prec);
2403 # 'x' is weird when the left arg is a list
2407 my $left = $op->first;
2408 my $right = $op->last;
2411 if ($op->flags & OPf_STACKED) {
2415 if (null($right)) { # list repeat; count is inside left-side ex-list
2416 my $kid = $left->first->sibling; # skip pushmark
2418 for (; !null($kid->sibling); $kid = $kid->sibling) {
2419 push @exprs, $self->deparse($kid, 6);
2422 $left = "(" . join(", ", @exprs). ")";
2424 $left = $self->deparse_binop_left($op, $left, $prec);
2426 $right = $self->deparse_binop_right($op, $right, $prec);
2427 return $self->maybe_parens("$left x$eq $right", $cx, $prec);
2432 my ($op, $cx, $type) = @_;
2433 my $left = $op->first;
2434 my $right = $left->sibling;
2435 $left = $self->deparse($left, 9);
2436 $right = $self->deparse($right, 9);
2437 return $self->maybe_parens("$left $type $right", $cx, 9);
2443 my $flip = $op->first;
2444 my $type = ($flip->flags & OPf_SPECIAL) ? "..." : "..";
2445 return $self->range($flip->first, $cx, $type);
2448 # one-line while/until is handled in pp_leave
2452 my ($op, $cx, $lowop, $lowprec, $highop, $highprec, $blockname) = @_;
2453 my $left = $op->first;
2454 my $right = $op->first->sibling;
2455 if ($cx < 1 and is_scope($right) and $blockname
2456 and $self->{'expand'} < 7)
2458 $left = $self->deparse($left, 1);
2459 $right = $self->deparse($right, 0);
2460 return "$blockname ($left) {\n\t$right\n\b}\cK";
2461 } elsif ($cx < 1 and $blockname and not $self->{'parens'}
2462 and $self->{'expand'} < 7) { # $b if $a
2463 $right = $self->deparse($right, 1);
2464 $left = $self->deparse($left, 1);
2465 return "$right $blockname $left";
2466 } elsif ($cx > $lowprec and $highop) { # $a && $b
2467 $left = $self->deparse_binop_left($op, $left, $highprec);
2468 $right = $self->deparse_binop_right($op, $right, $highprec);
2469 return $self->maybe_parens("$left $highop $right", $cx, $highprec);
2470 } else { # $a and $b
2471 $left = $self->deparse_binop_left($op, $left, $lowprec);
2472 $right = $self->deparse_binop_right($op, $right, $lowprec);
2473 return $self->maybe_parens("$left $lowop $right", $cx, $lowprec);
2477 sub pp_and { logop(@_, "and", 3, "&&", 11, "if") }
2478 sub pp_or { logop(@_, "or", 2, "||", 10, "unless") }
2479 sub pp_dor { logop(@_, "//", 10) }
2481 # xor is syntactically a logop, but it's really a binop (contrary to
2482 # old versions of opcode.pl). Syntax is what matters here.
2483 sub pp_xor { logop(@_, "xor", 2, "", 0, "") }
2487 my ($op, $cx, $opname) = @_;
2488 my $left = $op->first;
2489 my $right = $op->first->sibling->first; # skip sassign
2490 $left = $self->deparse($left, 7);
2491 $right = $self->deparse($right, 7);
2492 return $self->maybe_parens("$left $opname $right", $cx, 7);
2495 sub pp_andassign { logassignop(@_, "&&=") }
2496 sub pp_orassign { logassignop(@_, "||=") }
2497 sub pp_dorassign { logassignop(@_, "//=") }
2499 sub rv2gv_or_string {
2501 if ($op->name eq "gv") { # could be open("open") or open("###")
2503 $self->stash_variable_name("", $self->gv_or_padgv($op));
2504 $quoted ? $name : "*$name";
2507 $self->deparse($op, 6);
2513 my($op, $cx, $name, $kid, $nollafr) = @_;
2515 my $parens = ($cx >= 5) || $self->{'parens'};
2516 $kid ||= $op->first->sibling;
2517 # If there are no arguments, add final parentheses (or parenthesize the
2518 # whole thing if the llafr does not apply) to account for cases like
2519 # (return)+1 or setpgrp()+1. When the llafr does not apply, we use a
2520 # precedence of 6 (< comma), as "return, 1" does not need parentheses.
2523 ? $self->maybe_parens($self->keyword($name), $cx, 7)
2524 : $self->keyword($name) . '()' x (7 < $cx);
2527 $name = "socketpair" if $name eq "sockpair";
2528 my $fullname = $self->keyword($name);
2529 my $proto = prototype("CORE::$name");
2531 && $proto =~ /^;?\*/
2532 && $kid->name eq "rv2gv" && !($kid->private & OPpLVAL_INTRO)) {
2533 $first = $self->rv2gv_or_string($kid->first);
2536 $first = $self->deparse($kid, 6);
2538 if ($name eq "chmod" && $first =~ /^\d+$/) {
2539 $first = sprintf("%#o", $first);
2542 if not $parens and not $nollafr and substr($first, 0, 1) eq "(";
2543 push @exprs, $first;
2544 $kid = $kid->sibling;
2545 if (defined $proto && $proto =~ /^\*\*/ && $kid->name eq "rv2gv"
2546 && !($kid->private & OPpLVAL_INTRO)) {
2547 push @exprs, $first = $self->rv2gv_or_string($kid->first);
2548 $kid = $kid->sibling;
2550 for (; !null($kid); $kid = $kid->sibling) {
2551 push @exprs, $self->deparse($kid, 6);
2553 if ($name eq "reverse" && ($op->private & OPpREVERSE_INPLACE)) {
2554 return "$exprs[0] = $fullname"
2555 . ($parens ? "($exprs[0])" : " $exprs[0]");
2557 if ($parens && $nollafr) {
2558 return "($fullname " . join(", ", @exprs) . ")";
2560 return "$fullname(" . join(", ", @exprs) . ")";
2562 return "$fullname " . join(", ", @exprs);
2566 sub pp_bless { listop(@_, "bless") }
2567 sub pp_atan2 { maybe_targmy(@_, \&listop, "atan2") }
2569 my ($self,$op,$cx) = @_;
2570 if ($op->private & OPpSUBSTR_REPL_FIRST) {
2572 listop($self, $op, 7, "substr", $op->first->sibling->sibling)
2574 . $self->deparse($op->first->sibling, 7);
2576 maybe_local(@_, listop(@_, "substr"))
2578 sub pp_vec { maybe_local(@_, listop(@_, "vec")) }
2579 sub pp_index { maybe_targmy(@_, \&listop, "index") }
2580 sub pp_rindex { maybe_targmy(@_, \&listop, "rindex") }
2581 sub pp_sprintf { maybe_targmy(@_, \&listop, "sprintf") }
2582 sub pp_formline { listop(@_, "formline") } # see also deparse_format
2583 sub pp_crypt { maybe_targmy(@_, \&listop, "crypt") }
2584 sub pp_unpack { listop(@_, "unpack") }
2585 sub pp_pack { listop(@_, "pack") }
2586 sub pp_join { maybe_targmy(@_, \&listop, "join") }
2587 sub pp_splice { listop(@_, "splice") }
2588 sub pp_push { maybe_targmy(@_, \&listop, "push") }
2589 sub pp_unshift { maybe_targmy(@_, \&listop, "unshift") }
2590 sub pp_reverse { listop(@_, "reverse") }
2591 sub pp_warn { listop(@_, "warn") }
2592 sub pp_die { listop(@_, "die") }
2593 sub pp_return { listop(@_, "return", undef, 1) } # llafr does not apply
2594 sub pp_open { listop(@_, "open") }
2595 sub pp_pipe_op { listop(@_, "pipe") }
2596 sub pp_tie { listop(@_, "tie") }
2597 sub pp_binmode { listop(@_, "binmode") }
2598 sub pp_dbmopen { listop(@_, "dbmopen") }
2599 sub pp_sselect { listop(@_, "select") }
2600 sub pp_select { listop(@_, "select") }
2601 sub pp_read { listop(@_, "read") }
2602 sub pp_sysopen { listop(@_, "sysopen") }
2603 sub pp_sysseek { listop(@_, "sysseek") }
2604 sub pp_sysread { listop(@_, "sysread") }
2605 sub pp_syswrite { listop(@_, "syswrite") }
2606 sub pp_send { listop(@_, "send") }
2607 sub pp_recv { listop(@_, "recv") }
2608 sub pp_seek { listop(@_, "seek") }
2609 sub pp_fcntl { listop(@_, "fcntl") }
2610 sub pp_ioctl { listop(@_, "ioctl") }
2611 sub pp_flock { maybe_targmy(@_, \&listop, "flock") }
2612 sub pp_socket { listop(@_, "socket") }
2613 sub pp_sockpair { listop(@_, "sockpair") }
2614 sub pp_bind { listop(@_, "bind") }
2615 sub pp_connect { listop(@_, "connect") }
2616 sub pp_listen { listop(@_, "listen") }
2617 sub pp_accept { listop(@_, "accept") }
2618 sub pp_shutdown { listop(@_, "shutdown") }
2619 sub pp_gsockopt { listop(@_, "getsockopt") }
2620 sub pp_ssockopt { listop(@_, "setsockopt") }
2621 sub pp_chown { maybe_targmy(@_, \&listop, "chown") }
2622 sub pp_unlink { maybe_targmy(@_, \&listop, "unlink") }
2623 sub pp_chmod { maybe_targmy(@_, \&listop, "chmod") }
2624 sub pp_utime { maybe_targmy(@_, \&listop, "utime") }
2625 sub pp_rename { maybe_targmy(@_, \&listop, "rename") }
2626 sub pp_link { maybe_targmy(@_, \&listop, "link") }
2627 sub pp_symlink { maybe_targmy(@_, \&listop, "symlink") }
2628 sub pp_mkdir { maybe_targmy(@_, \&listop, "mkdir") }
2629 sub pp_open_dir { listop(@_, "opendir") }
2630 sub pp_seekdir { listop(@_, "seekdir") }
2631 sub pp_waitpid { maybe_targmy(@_, \&listop, "waitpid") }
2632 sub pp_system { maybe_targmy(@_, \&listop, "system") }
2633 sub pp_exec { maybe_targmy(@_, \&listop, "exec") }
2634 sub pp_kill { maybe_targmy(@_, \&listop, "kill") }
2635 sub pp_setpgrp { maybe_targmy(@_, \&listop, "setpgrp") }
2636 sub pp_getpriority { maybe_targmy(@_, \&listop, "getpriority") }
2637 sub pp_setpriority { maybe_targmy(@_, \&listop, "setpriority") }
2638 sub pp_shmget { listop(@_, "shmget") }
2639 sub pp_shmctl { listop(@_, "shmctl") }
2640 sub pp_shmread { listop(@_, "shmread") }
2641 sub pp_shmwrite { listop(@_, "shmwrite") }
2642 sub pp_msgget { listop(@_, "msgget") }
2643 sub pp_msgctl { listop(@_, "msgctl") }
2644 sub pp_msgsnd { listop(@_, "msgsnd") }
2645 sub pp_msgrcv { listop(@_, "msgrcv") }
2646 sub pp_semget { listop(@_, "semget") }
2647 sub pp_semctl { listop(@_, "semctl") }
2648 sub pp_semop { listop(@_, "semop") }
2649 sub pp_ghbyaddr { listop(@_, "gethostbyaddr") }
2650 sub pp_gnbyaddr { listop(@_, "getnetbyaddr") }
2651 sub pp_gpbynumber { listop(@_, "getprotobynumber") }
2652 sub pp_gsbyname { listop(@_, "getservbyname") }
2653 sub pp_gsbyport { listop(@_, "getservbyport") }
2654 sub pp_syscall { listop(@_, "syscall") }
2659 my $text = $self->dq($op->first->sibling); # skip pushmark
2661 $op->flags & OPf_SPECIAL ? 'glob' : $self->keyword('glob');
2662 if ($text =~ /^\$?(\w|::|\`)+$/ # could look like a readline
2663 or $keyword =~ /^CORE::/
2664 or $text =~ /[<>]/) {
2665 return "$keyword(" . single_delim('qq', '"', $text) . ')';
2667 return '<' . $text . '>';
2671 # Truncate is special because OPf_SPECIAL makes a bareword first arg
2672 # be a filehandle. This could probably be better fixed in the core
2673 # by moving the GV lookup into ck_truc.
2679 my $parens = ($cx >= 5) || $self->{'parens'};
2680 my $kid = $op->first->sibling;
2682 if ($op->flags & OPf_SPECIAL) {
2683 # $kid is an OP_CONST
2684 $fh = $self->const_sv($kid)->PV;
2686 $fh = $self->deparse($kid, 6);
2687 $fh = "+$fh" if not $parens and substr($fh, 0, 1) eq "(";
2689 my $len = $self->deparse($kid->sibling, 6);
2690 my $name = $self->keyword('truncate');
2692 return "$name($fh, $len)";
2694 return "$name $fh, $len";
2700 my($op, $cx, $name) = @_;
2702 my $firstkid = my $kid = $op->first->sibling;
2704 if ($op->flags & OPf_STACKED) {
2706 $indir = $indir->first; # skip rv2gv
2707 if (is_scope($indir)) {
2708 $indir = "{" . $self->deparse($indir, 0) . "}";
2709 $indir = "{;}" if $indir eq "{}";
2710 } elsif ($indir->name eq "const" && $indir->private & OPpCONST_BARE) {
2711 $indir = $self->const_sv($indir)->PV;
2713 $indir = $self->deparse($indir, 24);
2715 $indir = $indir . " ";
2716 $kid = $kid->sibling;
2718 if ($name eq "sort" && $op->private & (OPpSORT_NUMERIC | OPpSORT_INTEGER)) {
2719 $indir = ($op->private & OPpSORT_DESCEND) ? '{$b <=> $a} '
2722 elsif ($name eq "sort" && $op->private & OPpSORT_DESCEND) {
2723 $indir = '{$b cmp $a} ';
2725 for (; !null($kid); $kid = $kid->sibling) {
2726 $expr = $self->deparse($kid, !$indir && $kid == $firstkid && $name eq "sort" && $firstkid->name eq "entersub" ? 16 : 6);
2730 if ($name eq "sort" && $op->private & OPpSORT_REVERSE) {
2731 $name2 = $self->keyword('reverse') . ' ' . $self->keyword('sort');
2733 else { $name2 = $self->keyword($name) }
2734 if ($name eq "sort" && ($op->private & OPpSORT_INPLACE)) {
2735 return "$exprs[0] = $name2 $indir $exprs[0]";
2738 my $args = $indir . join(", ", @exprs);
2739 if ($indir ne "" && $name eq "sort") {
2740 # We don't want to say "sort(f 1, 2, 3)", since perl -w will
2741 # give bareword warnings in that case. Therefore if context
2742 # requires, we'll put parens around the outside "(sort f 1, 2,
2743 # 3)". Unfortunately, we'll currently think the parens are
2744 # necessary more often that they really are, because we don't
2745 # distinguish which side of an assignment we're on.
2747 return "($name2 $args)";
2749 return "$name2 $args";
2752 !$indir && $name eq "sort"
2753 && $op->first->sibling->name eq 'entersub'
2755 # We cannot say sort foo(bar), as foo will be interpreted as a
2756 # comparison routine. We have to say sort(...) in that case.
2757 return "$name2($args)";
2759 return $self->maybe_parens_func($name2, $args, $cx, 5);
2764 sub pp_prtf { indirop(@_, "printf") }
2765 sub pp_print { indirop(@_, "print") }
2766 sub pp_say { indirop(@_, "say") }
2767 sub pp_sort { indirop(@_, "sort") }
2771 my($op, $cx, $name) = @_;
2773 my $kid = $op->first; # this is the (map|grep)start
2774 $kid = $kid->first->sibling; # skip a pushmark
2775 my $code = $kid->first; # skip a null
2776 if (is_scope $code) {
2777 $code = "{" . $self->deparse($code, 0) . "} ";
2779 $code = $self->deparse($code, 24) . ", ";
2781 $kid = $kid->sibling;
2782 for (; !null($kid); $kid = $kid->sibling) {
2783 $expr = $self->deparse($kid, 6);
2784 push @exprs, $expr if defined $expr;
2786 return $self->maybe_parens_func($name, $code . join(", ", @exprs), $cx, 5);
2789 sub pp_mapwhile { mapop(@_, "map") }
2790 sub pp_grepwhile { mapop(@_, "grep") }
2791 sub pp_mapstart { baseop(@_, "map") }
2792 sub pp_grepstart { baseop(@_, "grep") }
2798 my $kid = $op->first->sibling; # skip pushmark
2799 return '' if class($kid) eq 'NULL';
2801 my $local = "either"; # could be local(...), my(...), state(...) or our(...)
2802 for ($lop = $kid; !null($lop); $lop = $lop->sibling) {
2803 # This assumes that no other private flags equal 128, and that
2804 # OPs that store things other than flags in their op_private,
2805 # like OP_AELEMFAST, won't be immediate children of a list.
2807 # OP_ENTERSUB can break this logic, so check for it.
2808 # I suspect that open and exit can too.
2810 if (!($lop->private & (OPpLVAL_INTRO|OPpOUR_INTRO)
2811 or $lop->name eq "undef")
2812 or $lop->name eq "entersub"
2813 or $lop->name eq "exit"
2814 or $lop->name eq "open")
2816 $local = ""; # or not
2819 if ($lop->name =~ /^pad[ash]v$/) {
2820 if ($lop->private & OPpPAD_STATE) { # state()
2821 ($local = "", last) if $local =~ /^(?:local|our|my)$/;
2824 ($local = "", last) if $local =~ /^(?:local|our|state)$/;
2827 } elsif ($lop->name =~ /^(gv|rv2)[ash]v$/
2828 && $lop->private & OPpOUR_INTRO
2829 or $lop->name eq "null" && $lop->first->name eq "gvsv"
2830 && $lop->first->private & OPpOUR_INTRO) { # our()
2831 ($local = "", last) if $local =~ /^(?:my|local|state)$/;
2833 } elsif ($lop->name ne "undef"
2834 # specifically avoid the "reverse sort" optimisation,
2835 # where "reverse" is nullified
2836 && !($lop->name eq 'sort' && ($lop->flags & OPpSORT_REVERSE)))
2839 ($local = "", last) if $local =~ /^(?:my|our|state)$/;
2843 $local = "" if $local eq "either"; # no point if it's all undefs
2844 return $self->deparse($kid, $cx) if null $kid->sibling and not $local;
2845 for (; !null($kid); $kid = $kid->sibling) {
2847 if (class($kid) eq "UNOP" and $kid->first->name eq "gvsv") {
2852 $self->{'avoid_local'}{$$lop}++;
2853 $expr = $self->deparse($kid, 6);
2854 delete $self->{'avoid_local'}{$$lop};
2856 $expr = $self->deparse($kid, 6);
2861 return "$local(" . join(", ", @exprs) . ")";
2863 return $self->maybe_parens( join(", ", @exprs), $cx, 6);
2867 sub is_ifelse_cont {
2869 return ($op->name eq "null" and class($op) eq "UNOP"
2870 and $op->first->name =~ /^(and|cond_expr)$/
2871 and is_scope($op->first->first->sibling));
2877 my $cond = $op->first;
2878 my $true = $cond->sibling;
2879 my $false = $true->sibling;
2880 my $cuddle = $self->{'cuddle'};
2881 unless ($cx < 1 and (is_scope($true) and $true->name ne "null") and
2882 (is_scope($false) || is_ifelse_cont($false))
2883 and $self->{'expand'} < 7) {
2884 $cond = $self->deparse($cond, 8);
2885 $true = $self->deparse($true, 6);
2886 $false = $self->deparse($false, 8);
2887 return $self->maybe_parens("$cond ? $true : $false", $cx, 8);
2890 $cond = $self->deparse($cond, 1);
2891 $true = $self->deparse($true, 0);
2892 my $head = "if ($cond) {\n\t$true\n\b}";
2894 while (!null($false) and is_ifelse_cont($false)) {
2895 my $newop = $false->first;
2896 my $newcond = $newop->first;
2897 my $newtrue = $newcond->sibling;
2898 $false = $newtrue->sibling; # last in chain is OP_AND => no else
2899 if ($newcond->name eq "lineseq")
2901 # lineseq to ensure correct line numbers in elsif()
2902 # Bug #37302 fixed by change #33710.
2903 $newcond = $newcond->first->sibling;
2905 $newcond = $self->deparse($newcond, 1);
2906 $newtrue = $self->deparse($newtrue, 0);
2907 push @elsifs, "elsif ($newcond) {\n\t$newtrue\n\b}";
2909 if (!null($false)) {
2910 $false = $cuddle . "else {\n\t" .
2911 $self->deparse($false, 0) . "\n\b}\cK";
2915 return $head . join($cuddle, "", @elsifs) . $false;
2919 my ($self, $op, $cx) = @_;
2920 my $cond = $op->first;
2921 my $true = $cond->sibling;
2923 return $self->deparse($true, $cx);
2928 my($op, $cx, $init) = @_;
2929 my $enter = $op->first;
2930 my $kid = $enter->sibling;
2931 local(@$self{qw'curstash warnings hints hinthash'})
2932 = @$self{qw'curstash warnings hints hinthash'};
2937 if ($kid->name eq "lineseq") { # bare or infinite loop
2938 if ($kid->last->name eq "unstack") { # infinite
2939 $head = "while (1) "; # Can't use for(;;) if there's a continue
2945 } elsif ($enter->name eq "enteriter") { # foreach
2946 my $ary = $enter->first->sibling; # first was pushmark
2947 my $var = $ary->sibling;
2948 if ($ary->name eq 'null' and $enter->private & OPpITER_REVERSED) {
2949 # "reverse" was optimised away
2950 $ary = listop($self, $ary->first->sibling, 1, 'reverse');
2951 } elsif ($enter->flags & OPf_STACKED
2952 and not null $ary->first->sibling->sibling)
2954 $ary = $self->deparse($ary->first->sibling, 9) . " .. " .
2955 $self->deparse($ary->first->sibling->sibling, 9);
2957 $ary = $self->deparse($ary, 1);
2960 if (($enter->flags & OPf_SPECIAL) && ($] < 5.009)) {
2961 # thread special var, under 5005threads
2962 $var = $self->pp_threadsv($enter, 1);
2963 } else { # regular my() variable
2964 $var = $self->pp_padsv($enter, 1);
2966 } elsif ($var->name eq "rv2gv") {
2967 $var = $self->pp_rv2sv($var, 1);
2968 if ($enter->private & OPpOUR_INTRO) {
2969 # our declarations don't have package names
2970 $var =~ s/^(.).*::/$1/;
2973 } elsif ($var->name eq "gv") {
2974 $var = "\$" . $self->deparse($var, 1);
2976 $body = $kid->first->first->sibling; # skip OP_AND and OP_ITER
2977 if (!is_state $body->first and $body->first->name !~ /^(?:stub|leave|scope)$/) {
2978 confess unless $var eq '$_';
2979 $body = $body->first;
2980 return $self->deparse($body, 2) . " foreach ($ary)";
2982 $head = "foreach $var ($ary) ";
2983 } elsif ($kid->name eq "null") { # while/until
2985 my $name = {"and" => "while", "or" => "until"}->{$kid->name};
2986 $cond = $self->deparse($kid->first, 1);
2987 $head = "$name ($cond) ";
2988 $body = $kid->first->sibling;
2989 } elsif ($kid->name eq "stub") { # bare and empty
2990 return "{;}"; # {} could be a hashref
2992 # If there isn't a continue block, then the next pointer for the loop
2993 # will point to the unstack, which is kid's last child, except
2994 # in a bare loop, when it will point to the leaveloop. When neither of
2995 # these conditions hold, then the second-to-last child is the continue
2996 # block (or the last in a bare loop).
2997 my $cont_start = $enter->nextop;
2999 if ($$cont_start != $$op && ${$cont_start} != ${$body->last}) {
3001 $cont = $body->last;
3003 $cont = $body->first;
3004 while (!null($cont->sibling->sibling)) {
3005 $cont = $cont->sibling;
3008 my $state = $body->first;
3009 my $cuddle = $self->{'cuddle'};
3011 for (; $$state != $$cont; $state = $state->sibling) {
3012 push @states, $state;
3014 $body = $self->lineseq(undef, @states);
3015 if (defined $cond and not is_scope $cont and $self->{'expand'} < 3) {
3016 $head = "for ($init; $cond; " . $self->deparse($cont, 1) .") ";
3019 $cont = $cuddle . "continue {\n\t" .
3020 $self->deparse($cont, 0) . "\n\b}\cK";
3023 return "" if !defined $body;
3025 $head = "for ($init; $cond;) ";
3028 $body = $self->deparse($body, 0);
3030 $body =~ s/;?$/;\n/;
3032 return $head . "{\n\t" . $body . "\b}" . $cont;
3035 sub pp_leaveloop { shift->loop_common(@_, "") }
3040 my $init = $self->deparse($op, 1);
3041 my $s = $op->sibling;
3042 my $ll = $s->name eq "unstack" ? $s->sibling : $s->first->sibling;
3043 return $self->loop_common($ll, $cx, $init);
3048 return "eval {\n\t" . $self->pp_leave(@_) . "\n\b}";
3051 BEGIN { for (qw[ const stringify rv2sv list glob ]) {
3052 eval "sub OP_\U$_ () { " . opnumber($_) . "}"
3058 if (class($op) eq "OP") {
3060 return $self->{'ex_const'} if $op->targ == OP_CONST;
3061 } elsif ($op->first->name eq "pushmark") {
3062 return $self->pp_list($op, $cx);
3063 } elsif ($op->first->name eq "enter") {
3064 return $self->pp_leave($op, $cx);
3065 } elsif ($op->first->name eq "leave") {
3066 return $self->pp_leave($op->first, $cx);
3067 } elsif ($op->first->name eq "scope") {
3068 return $self->pp_scope($op->first, $cx);
3069 } elsif ($op->targ == OP_STRINGIFY) {
3070 return $self->dquote($op, $cx);
3071 } elsif ($op->targ == OP_GLOB) {
3072 return $self->pp_glob(
3073 $op->first # entersub
3079 } elsif (!null($op->first->sibling) and
3080 $op->first->sibling->name eq "readline" and
3081 $op->first->sibling->flags & OPf_STACKED) {
3082 return $self->maybe_parens($self->deparse($op->first, 7) . " = "
3083 . $self->deparse($op->first->sibling, 7),
3085 } elsif (!null($op->first->sibling) and
3086 $op->first->sibling->name eq "trans" and
3087 $op->first->sibling->flags & OPf_STACKED) {
3088 return $self->maybe_parens($self->deparse($op->first, 20) . " =~ "
3089 . $self->deparse($op->first->sibling, 20),
3091 } elsif ($op->flags & OPf_SPECIAL && $cx < 1 && !$op->targ) {
3092 return "do {\n\t". $self->deparse($op->first, $cx) ."\n\b};";
3093 } elsif (!null($op->first->sibling) and
3094 $op->first->sibling->name eq "null" and
3095 class($op->first->sibling) eq "UNOP" and
3096 $op->first->sibling->first->flags & OPf_STACKED and
3097 $op->first->sibling->first->name eq "rcatline") {
3098 return $self->maybe_parens($self->deparse($op->first, 18) . " .= "
3099 . $self->deparse($op->first->sibling, 18),
3102 return $self->deparse($op->first, $cx);
3109 return $self->padname_sv($targ)->PVX;
3115 return substr($self->padname($op->targ), 1); # skip $/@/%
3121 return $self->maybe_my($op, $cx, $self->padname($op->targ));
3124 sub pp_padav { pp_padsv(@_) }
3125 sub pp_padhv { pp_padsv(@_) }
3127 my @threadsv_names = B::threadsv_names;
3131 return $self->maybe_local($op, $cx, "\$" . $threadsv_names[$op->targ]);
3137 if (class($op) eq "PADOP") {
3138 return $self->padval($op->padix);
3139 } else { # class($op) eq "SVOP"
3147 my $gv = $self->gv_or_padgv($op);
3148 return $self->maybe_local($op, $cx, $self->stash_variable("\$",
3149 $self->gv_name($gv), $cx));
3155 my $gv = $self->gv_or_padgv($op);
3156 return $self->gv_name($gv);
3159 sub pp_aelemfast_lex {
3162 my $name = $self->padname($op->targ);
3164 return $name . "[" . ($op->private + $self->{'arybase'}) . "]";
3170 # optimised PADAV, pre 5.15
3171 return $self->pp_aelemfast_lex(@_) if ($op->flags & OPf_SPECIAL);
3173 my $gv = $self->gv_or_padgv($op);
3174 my($name,$quoted) = $self->stash_variable_name('@',$gv);
3175 $name = $quoted ? "$name->" : '$' . $name;
3176 return $name . "[" . ($op->private + $self->{'arybase'}) . "]";
3181 my($op, $cx, $type) = @_;
3183 if (class($op) eq 'NULL' || !$op->can("first")) {
3184 carp("Unexpected op in pp_rv2x");
3187 my $kid = $op->first;
3188 if ($kid->name eq "gv") {
3189 return $self->stash_variable($type, $self->deparse($kid, 0), $cx);
3190 } elsif (is_scalar $kid) {
3191 my $str = $self->deparse($kid, 0);
3192 if ($str =~ /^\$([^\w\d])\z/) {
3193 # "$$+" isn't a legal way to write the scalar dereference
3194 # of $+, since the lexer can't tell you aren't trying to
3195 # do something like "$$ + 1" to get one more than your
3196 # PID. Either "${$+}" or "$${+}" are workable
3197 # disambiguations, but if the programmer did the former,
3198 # they'd be in the "else" clause below rather than here.
3199 # It's not clear if this should somehow be unified with
3200 # the code in dq and re_dq that also adds lexer
3201 # disambiguation braces.
3202 $str = '$' . "{$1}"; #'
3204 return $type . $str;
3206 return $type . "{" . $self->deparse($kid, 0) . "}";
3210 sub pp_rv2sv { maybe_local(@_, rv2x(@_, "\$")) }
3211 sub pp_rv2hv { maybe_local(@_, rv2x(@_, "%")) }
3212 sub pp_rv2gv { maybe_local(@_, rv2x(@_, "*")) }
3218 if ($op->first->name eq "padav") {
3219 return $self->maybe_local($op, $cx, '$#' . $self->padany($op->first));
3221 return $self->maybe_local($op, $cx,
3222 $self->rv2x($op->first, $cx, '$#'));
3226 # skip down to the old, ex-rv2cv
3228 my ($self, $op, $cx) = @_;
3229 if (!null($op->first) && $op->first->name eq 'null' &&
3230 $op->first->targ eq OP_LIST)
3232 return $self->rv2x($op->first->first->sibling, $cx, "&")
3235 return $self->rv2x($op, $cx, "")
3241 my($cx, @list) = @_;
3242 my @a = map $self->const($_, 6), @list;
3247 } elsif ( @a > 2 and !grep(!/^-?\d+$/, @a)) {
3248 # collapse (-1,0,1,2) into (-1..2)
3249 my ($s, $e) = @a[0,-1];
3251 return $self->maybe_parens("$s..$e", $cx, 9)
3252 unless grep $i++ != $_, @a;
3254 return $self->maybe_parens(join(", ", @a), $cx, 6);
3260 my $kid = $op->first;
3261 if ($kid->name eq "const") { # constant list
3262 my $av = $self->const_sv($kid);
3263 return $self->list_const($cx, $av->ARRAY);
3265 return $self->maybe_local($op, $cx, $self->rv2x($op, $cx, "\@"));
3269 sub is_subscriptable {
3271 if ($op->name =~ /^[ahg]elem/) {
3273 } elsif ($op->name eq "entersub") {
3274 my $kid = $op->first;
3275 return 0 unless null $kid->sibling;
3277 $kid = $kid->sibling until null $kid->sibling;
3278 return 0 if is_scope($kid);
3280 return 0 if $kid->name eq "gv";
3281 return 0 if is_scalar($kid);
3282 return is_subscriptable($kid);
3288 sub elem_or_slice_array_name
3291 my ($array, $left, $padname, $allow_arrow) = @_;
3293 if ($array->name eq $padname) {
3294 return $self->padany($array);
3295 } elsif (is_scope($array)) { # ${expr}[0]
3296 return "{" . $self->deparse($array, 0) . "}";
3297 } elsif ($array->name eq "gv") {
3298 ($array, my $quoted) =
3299 $self->stash_variable_name(
3300 $left eq '[' ? '@' : '%', $self->gv_or_padgv($array)
3302 if (!$allow_arrow && $quoted) {
3303 # This cannot happen.
3304 die "Invalid variable name $array for slice";
3306 return $quoted ? "$array->" : $array;
3307 } elsif (!$allow_arrow || is_scalar $array) { # $x[0], $$x[0], ...
3308 return $self->deparse($array, 24);
3314 sub elem_or_slice_single_index
3319 $idx = $self->deparse($idx, 1);
3321 # Outer parens in an array index will confuse perl
3322 # if we're interpolating in a regular expression, i.e.
3323 # /$x$foo[(-1)]/ is *not* the same as /$x$foo[-1]/
3325 # If $self->{parens}, then an initial '(' will
3326 # definitely be paired with a final ')'. If
3327 # !$self->{parens}, the misleading parens won't
3328 # have been added in the first place.
3330 # [You might think that we could get "(...)...(...)"
3331 # where the initial and final parens do not match
3332 # each other. But we can't, because the above would
3333 # only happen if there's an infix binop between the
3334 # two pairs of parens, and *that* means that the whole
3335 # expression would be parenthesized as well.]
3337 $idx =~ s/^\((.*)\)$/$1/ if $self->{'parens'};
3339 # Hash-element braces will autoquote a bareword inside themselves.
3340 # We need to make sure that C<$hash{warn()}> doesn't come out as
3341 # C<$hash{warn}>, which has a quite different meaning. Currently
3342 # B::Deparse will always quote strings, even if the string was a
3343 # bareword in the original (i.e. the OPpCONST_BARE flag is ignored
3344 # for constant strings.) So we can cheat slightly here - if we see
3345 # a bareword, we know that it is supposed to be a function call.
3347 $idx =~ s/^([A-Za-z_]\w*)$/$1()/;
3354 my ($op, $cx, $left, $right, $padname) = @_;
3355 my($array, $idx) = ($op->first, $op->first->sibling);
3357 $idx = $self->elem_or_slice_single_index($idx);
3359 unless ($array->name eq $padname) { # Maybe this has been fixed
3360 $array = $array->first; # skip rv2av (or ex-rv2av in _53+)
3362 if (my $array_name=$self->elem_or_slice_array_name
3363 ($array, $left, $padname, 1)) {
3364 return ($array_name =~ /->\z/ ? $array_name : "\$" . $array_name)
3365 . $left . $idx . $right;
3367 # $x[20][3]{hi} or expr->[20]
3368 my $arrow = is_subscriptable($array) ? "" : "->";
3369 return $self->deparse($array, 24) . $arrow . $left . $idx . $right;
3374 sub pp_aelem { maybe_local(@_, elem(@_, "[", "]", "padav")) }
3375 sub pp_helem { maybe_local(@_, elem(@_, "{", "}", "padhv")) }
3380 my($glob, $part) = ($op->first, $op->last);
3381 $glob = $glob->first; # skip rv2gv
3382 $glob = $glob->first if $glob->name eq "rv2gv"; # this one's a bug
3383 my $scope = is_scope($glob);
3384 $glob = $self->deparse($glob, 0);
3385 $part = $self->deparse($part, 1);
3386 return "*" . ($scope ? "{$glob}" : $glob) . "{$part}";
3391 my ($op, $cx, $left, $right, $regname, $padname) = @_;
3393 my(@elems, $kid, $array, $list);
3394 if (class($op) eq "LISTOP") {
3396 } else { # ex-hslice inside delete()
3397 for ($kid = $op->first; !null $kid->sibling; $kid = $kid->sibling) {}
3401 $array = $array->first
3402 if $array->name eq $regname or $array->name eq "null";
3403 $array = $self->elem_or_slice_array_name($array,$left,$padname,0);
3404 $kid = $op->first->sibling; # skip pushmark
3405 if ($kid->name eq "list") {
3406 $kid = $kid->first->sibling; # skip list, pushmark
3407 for (; !null $kid; $kid = $kid->sibling) {
3408 push @elems, $self->deparse($kid, 6);
3410 $list = join(", ", @elems);
3412 $list = $self->elem_or_slice_single_index($kid);
3414 return "\@" . $array . $left . $list . $right;
3417 sub pp_aslice { maybe_local(@_, slice(@_, "[", "]", "rv2av", "padav")) }
3418 sub pp_hslice { maybe_local(@_, slice(@_, "{", "}", "rv2hv", "padhv")) }
3423 my $idx = $op->first;
3424 my $list = $op->last;
3426 $list = $self->deparse($list, 1);
3427 $idx = $self->deparse($idx, 1);
3428 return "($list)" . "[$idx]";
3433 return ($op->flags & OPf_WANT) == OPf_WANT_SCALAR;
3438 return ($op->flags & OPf_WANT) == OPf_WANT_LIST;
3444 my $kid = $op->first->sibling; # skip pushmark
3445 my($meth, $obj, @exprs);
3446 if ($kid->name eq "list" and want_list $kid) {
3447 # When an indirect object isn't a bareword but the args are in
3448 # parens, the parens aren't part of the method syntax (the LLAFR
3449 # doesn't apply), but they make a list with OPf_PARENS set that
3450 # doesn't get flattened by the append_elem that adds the method,
3451 # making a (object, arg1, arg2, ...) list where the object
3452 # usually is. This can be distinguished from
3453 # '($obj, $arg1, $arg2)->meth()' (which is legal if $arg2 is an
3454 # object) because in the later the list is in scalar context
3455 # as the left side of -> always is, while in the former
3456 # the list is in list context as method arguments always are.
3457 # (Good thing there aren't method prototypes!)
3458 $meth = $kid->sibling;
3459 $kid = $kid->first->sibling; # skip pushmark
3461 $kid = $kid->sibling;
3462 for (; not null $kid; $kid = $kid->sibling) {
3467 $kid = $kid->sibling;
3468 for (; !null ($kid->sibling) && $kid->name!~/^method(?:_named)?\z/;
3469 $kid = $kid->sibling) {
3475 if ($meth->name eq "method_named") {
3476 $meth = $self->const_sv($meth)->PV;
3478 $meth = $meth->first;
3479 if ($meth->name eq "const") {
3480 # As of 5.005_58, this case is probably obsoleted by the
3481 # method_named case above
3482 $meth = $self->const_sv($meth)->PV; # needs to be bare
3486 return { method => $meth, variable_method => ref($meth),
3487 object => $obj, args => \@exprs },
3491 # compat function only
3494 my $info = $self->_method(@_);
3495 return $self->e_method( $self->_method(@_) );
3499 my ($self, $info, $cx) = @_;
3500 my $obj = $self->deparse($info->{object}, 24);
3502 my $meth = $info->{method};
3503 $meth = $self->deparse($meth, 1) if $info->{variable_method};
3504 my $args = join(", ", map { $self->deparse($_, 6) } @{$info->{args}} );
3505 if ($info->{object}->name eq 'scope' && want_list $info->{object}) {
3506 # method { $object }
3507 # This must be deparsed this way to preserve list context
3509 my $need_paren = $cx >= 6;
3510 return '(' x $need_paren
3511 . $meth . substr($obj,2) # chop off the "do"
3513 . ')' x $need_paren;
3515 my $kid = $obj . "->" . $meth;
3517 return $kid . "(" . $args . ")"; # parens mandatory
3523 # returns "&" if the prototype doesn't match the args,
3524 # or ("", $args_after_prototype_demunging) if it does.
3527 return "&" if $self->{'noproto'};
3528 my($proto, @args) = @_;
3532 # An unbackslashed @ or % gobbles up the rest of the args
3533 1 while $proto =~ s/(?<!\\)([@%])[^\]]+$/$1/;
3535 $proto =~ s/^(\\?[\$\@&%*_]|\\\[[\$\@&%*]+\]|;)//;
3538 return "&" if @args;
3539 } elsif ($chr eq ";") {
3541 } elsif ($chr eq "@" or $chr eq "%") {
3542 push @reals, map($self->deparse($_, 6), @args);
3547 if ($chr eq "\$" || $chr eq "_") {
3548 if (want_scalar $arg) {
3549 push @reals, $self->deparse($arg, 6);
3553 } elsif ($chr eq "&") {
3554 if ($arg->name =~ /^(s?refgen|undef)$/) {
3555 push @reals, $self->deparse($arg, 6);
3559 } elsif ($chr eq "*") {
3560 if ($arg->name =~ /^s?refgen$/
3561 and $arg->first->first->name eq "rv2gv")
3563 $real = $arg->first->first; # skip refgen, null
3564 if ($real->first->name eq "gv") {
3565 push @reals, $self->deparse($real, 6);
3567 push @reals, $self->deparse($real->first, 6);
3572 } elsif (substr($chr, 0, 1) eq "\\") {
3574 if ($arg->name =~ /^s?refgen$/ and
3575 !null($real = $arg->first) and
3576 ($chr =~ /\$/ && is_scalar($real->first)
3578 && class($real->first->sibling) ne 'NULL'
3579 && $real->first->sibling->name
3582 && class($real->first->sibling) ne 'NULL'
3583 && $real->first->sibling->name
3585 #or ($chr =~ /&/ # This doesn't work
3586 # && $real->first->name eq "rv2cv")
3588 && $real->first->name eq "rv2gv")))
3590 push @reals, $self->deparse($real, 6);
3597 return "&" if $proto and !$doneok; # too few args and no ';'
3598 return "&" if @args; # too many args
3599 return ("", join ", ", @reals);
3605 return $self->e_method($self->_method($op, $cx))
3606 unless null $op->first->sibling;
3610 if ($op->flags & OPf_SPECIAL && !($op->flags & OPf_MOD)) {
3612 } elsif ($op->private & OPpENTERSUB_AMPER) {
3616 $kid = $kid->first->sibling; # skip ex-list, pushmark
3617 for (; not null $kid->sibling; $kid = $kid->sibling) {
3622 if (is_scope($kid)) {
3624 $kid = "{" . $self->deparse($kid, 0) . "}";
3625 } elsif ($kid->first->name eq "gv") {
3626 my $gv = $self->gv_or_padgv($kid->first);
3627 if (class($gv->CV) ne "SPECIAL") {
3628 $proto = $gv->CV->PV if $gv->CV->FLAGS & SVf_POK;
3630 $simple = 1; # only calls of named functions can be prototyped
3631 $kid = $self->deparse($kid, 24);
3633 if ($kid eq 'main::') {
3635 } elsif ($kid !~ /^(?:\w|::)(?:[\w\d]|::(?!\z))*\z/) {
3636 $kid = single_delim("q", "'", $kid) . '->';
3639 } elsif (is_scalar ($kid->first) && $kid->first->name ne 'rv2cv') {
3641 $kid = $self->deparse($kid, 24);
3644 my $arrow = is_subscriptable($kid->first) ? "" : "->";
3645 $kid = $self->deparse($kid, 24) . $arrow;
3648 # Doesn't matter how many prototypes there are, if
3649 # they haven't happened yet!
3653 no warnings 'uninitialized';
3654 $declared = exists $self->{'subs_declared'}{$kid}
3656 defined &{ ${$self->{'curstash'}."::"}{$kid} }
3658 $self->{'subs_deparsed'}{$self->{'curstash'}."::".$kid}
3659 && defined prototype $self->{'curstash'}."::".$kid
3661 if (!$declared && defined($proto)) {
3662 # Avoid "too early to check prototype" warning
3663 ($amper, $proto) = ('&');
3668 if ($declared and defined $proto and not $amper) {
3669 ($amper, $args) = $self->check_proto($proto, @exprs);
3670 if ($amper eq "&") {
3671 $args = join(", ", map($self->deparse($_, 6), @exprs));
3674 $args = join(", ", map($self->deparse($_, 6), @exprs));
3676 if ($prefix or $amper) {
3677 if ($kid eq '&') { $kid = "{$kid}" } # &{&} cannot be written as &&
3678 if ($op->flags & OPf_STACKED) {
3679 return $prefix . $amper . $kid . "(" . $args . ")";
3681 return $prefix . $amper. $kid;
3684 # It's a syntax error to call CORE::GLOBAL::foo with a prefix,
3685 # so it must have been translated from a keyword call. Translate
3687 $kid =~ s/^CORE::GLOBAL:://;
3689 my $dproto = defined($proto) ? $proto : "undefined";
3691 return "$kid(" . $args . ")";
3692 } elsif ($dproto eq "") {
3694 } elsif ($dproto eq "\$" and is_scalar($exprs[0])) {
3695 # is_scalar is an excessively conservative test here:
3696 # really, we should be comparing to the precedence of the
3697 # top operator of $exprs[0] (ala unop()), but that would
3698 # take some major code restructuring to do right.
3699 return $self->maybe_parens_func($kid, $args, $cx, 16);
3700 } elsif ($dproto ne '$' and defined($proto) || $simple) { #'
3701 return $self->maybe_parens_func($kid, $args, $cx, 5);
3703 return "$kid(" . $args . ")";
3708 sub pp_enterwrite { unop(@_, "write") }
3710 # escape things that cause interpolation in double quotes,
3711 # but not character escapes
3714 $str =~ s/(^|\G|[^\\])((?:\\\\)*)([\$\@]|\\[uUlLQE])/$1$2\\$3/g;
3722 # Matches any string which is balanced with respect to {braces}
3733 # the same, but treat $|, $), $( and $ at the end of the string differently
3747 (\(\?\??\{$bal\}\)) # $4
3753 /defined($4) && length($4) ? "$1$2$4" : "$1$2\\$3"/xeg;
3758 # This is for regular expressions with the /x modifier
3759 # We have to leave comments unmangled.
3760 sub re_uninterp_extended {
3773 ( \(\?\??\{$bal\}\) # $4 (skip over (?{}) and (??{}) blocks)
3774 | \#[^\n]* # (skip over comments)
3781 /defined($4) && length($4) ? "$1$2$4" : "$1$2\\$3"/xeg;
3787 my %unctrl = # portable to to EBCDIC
3789 "\c@" => '\c@', # unused
3816 "\c[" => '\c[', # unused
3817 "\c\\" => '\c\\', # unused
3818 "\c]" => '\c]', # unused
3819 "\c_" => '\c_', # unused
3822 # character escapes, but not delimiters that might need to be escaped
3823 sub escape_str { # ASCII, UTF8
3825 $str =~ s/(.)/ord($1) > 255 ? sprintf("\\x{%x}", ord($1)) : $1/eg;
3827 # $str =~ s/\cH/\\b/g; # \b means something different in a regex
3833 $str =~ s/([\cA-\cZ])/$unctrl{$1}/ge;
3834 $str =~ s/([[:^print:]])/sprintf("\\%03o", ord($1))/ge;
3838 # For regexes with the /x modifier.
3839 # Leave whitespace unmangled.
3840 sub escape_extended_re {
3842 $str =~ s/(.)/ord($1) > 255 ? sprintf("\\x{%x}", ord($1)) : $1/eg;
3843 $str =~ s/([[:^print:]])/
3844 ($1 =~ y! \t\n!!) ? $1 : sprintf("\\%03o", ord($1))/ge;
3845 $str =~ s/\n/\n\f/g;
3849 # Don't do this for regexen
3852 $str =~ s/\\/\\\\/g;
3856 # Remove backslashes which precede literal control characters,
3857 # to avoid creating ambiguity when we escape the latter.
3861 # the insane complexity here is due to the behaviour of "\c\"
3862 $str =~ s/(^|[^\\]|\\c\\)(?<!\\c)\\(\\\\)*(?=[[:^print:]])/$1$2/g;
3866 sub balanced_delim {
3868 my @str = split //, $str;
3869 my($ar, $open, $close, $fail, $c, $cnt, $last_bs);
3870 for $ar (['[',']'], ['(',')'], ['<','>'], ['{','}']) {
3871 ($open, $close) = @$ar;
3872 $fail = 0; $cnt = 0; $last_bs = 0;
3875 $fail = 1 if $last_bs;
3877 } elsif ($c eq $close) {
3878 $fail = 1 if $last_bs;
3886 $last_bs = $c eq '\\';
3888 $fail = 1 if $cnt != 0;
3889 return ($open, "$open$str$close") if not $fail;
3895 my($q, $default, $str) = @_;
3896 return "$default$str$default" if $default and index($str, $default) == -1;
3898 (my $succeed, $str) = balanced_delim($str);
3899 return "$q$str" if $succeed;
3901 for my $delim ('/', '"', '#') {
3902 return "$q$delim" . $str . $delim if index($str, $delim) == -1;
3905 $str =~ s/$default/\\$default/g;
3906 return "$default$str$default";
3914 BEGIN { $max_prec = int(0.999 + 8*length(pack("F", 42))*log(2)/log(10)); }
3916 # Split a floating point number into an integer mantissa and a binary
3917 # exponent. Assumes you've already made sure the number isn't zero or
3918 # some weird infinity or NaN.
3922 if ($f == int($f)) {
3923 while ($f % 2 == 0) {
3928 while ($f != int($f)) {
3933 my $mantissa = sprintf("%.0f", $f);
3934 return ($mantissa, $exponent);
3940 if ($self->{'use_dumper'}) {
3941 return $self->const_dumper($sv, $cx);
3943 if (class($sv) eq "SPECIAL") {
3944 # sv_undef, sv_yes, sv_no
3945 return ('undef', '1', $self->maybe_parens("!1", $cx, 21))[$$sv-1];
3947 if (class($sv) eq "NULL") {
3950 # convert a version object into the "v1.2.3" string in its V magic
3951 if ($sv->FLAGS & SVs_RMG) {
3952 for (my $mg = $sv->MAGIC; $mg; $mg = $mg->MOREMAGIC) {
3953 return $mg->PTR if $mg->TYPE eq 'V';
3957 if ($sv->FLAGS & SVf_IOK) {
3958 my $str = $sv->int_value;
3959 $str = $self->maybe_parens($str, $cx, 21) if $str < 0;
3961 } elsif ($sv->FLAGS & SVf_NOK) {
3964 if (pack("F", $nv) eq pack("F", 0)) {
3969 return $self->maybe_parens("-.0", $cx, 21);
3971 } elsif (1/$nv == 0) {
3974 return $self->maybe_parens("9**9**9", $cx, 22);
3977 return $self->maybe_parens("-9**9**9", $cx, 21);
3979 } elsif ($nv != $nv) {
3981 if (pack("F", $nv) eq pack("F", sin(9**9**9))) {
3983 return "sin(9**9**9)";
3984 } elsif (pack("F", $nv) eq pack("F", -sin(9**9**9))) {
3986 return $self->maybe_parens("-sin(9**9**9)", $cx, 21);
3989 my $hex = unpack("h*", pack("F", $nv));
3990 return qq'unpack("F", pack("h*", "$hex"))';
3993 # first, try the default stringification
3996 # failing that, try using more precision
3997 $str = sprintf("%.${max_prec}g", $nv);
3998 # if (pack("F", $str) ne pack("F", $nv)) {
4000 # not representable in decimal with whatever sprintf()
4001 # and atof() Perl is using here.
4002 my($mant, $exp) = split_float($nv);
4003 return $self->maybe_parens("$mant * 2**$exp", $cx, 19);
4006 $str = $self->maybe_parens($str, $cx, 21) if $nv < 0;
4008 } elsif ($sv->FLAGS & SVf_ROK && $sv->can("RV")) {
4010 if (class($ref) eq "AV") {
4011 return "[" . $self->list_const(2, $ref->ARRAY) . "]";
4012 } elsif (class($ref) eq "HV") {
4013 my %hash = $ref->ARRAY;
4015 for my $k (sort keys %hash) {
4016 push @elts, "$k => " . $self->const($hash{$k}, 6);
4018 return "{" . join(", ", @elts) . "}";
4019 } elsif (class($ref) eq "CV") {
4021 if ($] > 5.0150051) {
4022 require overloading;
4023 unimport overloading;
4026 if ($] > 5.0150051 && $self->{curcv} &&
4027 $self->{curcv}->object_2svref == $ref->object_2svref) {
4028 return $self->keyword("__SUB__");
4030 return "sub " . $self->deparse_sub($ref);
4032 if ($ref->FLAGS & SVs_SMG) {
4033 for (my $mg = $ref->MAGIC; $mg; $mg = $mg->MOREMAGIC) {
4034 if ($mg->TYPE eq 'r') {
4035 my $re = re_uninterp(escape_str(re_unback($mg->precomp)));
4036 return single_delim("qr", "", $re);
4041 return $self->maybe_parens("\\" . $self->const($ref, 20), $cx, 20);
4042 } elsif ($sv->FLAGS & SVf_POK) {
4044 if ($str =~ /[[:^print:]]/) {
4045 return single_delim("qq", '"', uninterp escape_str unback $str);
4047 return single_delim("q", "'", unback $str);
4057 my $ref = $sv->object_2svref();
4058 my $dumper = Data::Dumper->new([$$ref], ['$v']);
4059 $dumper->Purity(1)->Terse(1)->Deparse(1)->Indent(0)->Useqq(1)->Sortkeys(1);
4060 my $str = $dumper->Dump();
4061 if ($str =~ /^\$v/) {
4062 return '${my ' . $str . ' \$v}';
4072 # the constant could be in the pad (under useithreads)
4073 $sv = $self->padval($op->targ) unless $$sv;
4080 if ($op->private & OPpCONST_ARYBASE) {
4083 # if ($op->private & OPpCONST_BARE) { # trouble with '=>' autoquoting
4084 # return $self->const_sv($op)->PV;
4086 my $sv = $self->const_sv($op);
4087 return $self->const($sv, $cx);
4093 my $type = $op->name;
4094 if ($type eq "const") {
4095 return '$[' if $op->private & OPpCONST_ARYBASE;
4096 return uninterp(escape_str(unback($self->const_sv($op)->as_string)));
4097 } elsif ($type eq "concat") {
4098 my $first = $self->dq($op->first);
4099 my $last = $self->dq($op->last);
4101 # Disambiguate "${foo}bar", "${foo}{bar}", "${foo}[1]", "$foo\::bar"
4102 ($last =~ /^[A-Z\\\^\[\]_?]/ &&
4103 $first =~ s/([\$@])\^$/${1}{^}/) # "${^}W" etc
4104 || ($last =~ /^[:'{\[\w_]/ && #'
4105 $first =~ s/([\$@])([A-Za-z_]\w*)$/${1}{$2}/);
4107 return $first . $last;
4108 } elsif ($type eq "uc") {
4109 return '\U' . $self->dq($op->first->sibling) . '\E';
4110 } elsif ($type eq "lc") {
4111 return '\L' . $self->dq($op->first->sibling) . '\E';
4112 } elsif ($type eq "ucfirst") {
4113 return '\u' . $self->dq($op->first->sibling);
4114 } elsif ($type eq "lcfirst") {
4115 return '\l' . $self->dq($op->first->sibling);
4116 } elsif ($type eq "quotemeta") {
4117 return '\Q' . $self->dq($op->first->sibling) . '\E';
4118 } elsif ($type eq "fc") {
4119 return '\F' . $self->dq($op->first->sibling) . '\E';
4120 } elsif ($type eq "join") {
4121 return $self->deparse($op->last, 26); # was join($", @ary)
4123 return $self->deparse($op, 26);
4130 # skip pushmark if it exists (readpipe() vs ``)
4131 my $child = $op->first->sibling->isa('B::NULL')
4132 ? $op->first : $op->first->sibling;
4133 if ($self->pure_string($child)) {
4134 return single_delim("qx", '`', $self->dq($child, 1));
4136 unop($self, @_, "readpipe");
4142 my $kid = $op->first->sibling; # skip ex-stringify, pushmark
4143 return $self->deparse($kid, $cx) if $self->{'unquote'};
4144 $self->maybe_targmy($kid, $cx,
4145 sub {single_delim("qq", '"', $self->dq($_[1]))});
4148 # OP_STRINGIFY is a listop, but it only ever has one arg
4149 sub pp_stringify { maybe_targmy(@_, \&dquote) }
4151 # tr/// and s/// (and tr[][], tr[]//, tr###, etc)
4152 # note that tr(from)/to/ is OK, but not tr/from/(to)
4154 my($from, $to) = @_;
4155 my($succeed, $delim);
4156 if ($from !~ m[/] and $to !~ m[/]) {
4157 return "/$from/$to/";
4158 } elsif (($succeed, $from) = balanced_delim($from) and $succeed) {
4159 if (($succeed, $to) = balanced_delim($to) and $succeed) {
4162 for $delim ('/', '"', '#') { # note no "'" -- s''' is special
4163 return "$from$delim$to$delim" if index($to, $delim) == -1;
4166 return "$from/$to/";
4169 for $delim ('/', '"', '#') { # note no '
4170 return "$delim$from$delim$to$delim"
4171 if index($to . $from, $delim) == -1;
4173 $from =~ s[/][\\/]g;
4175 return "/$from/$to/";
4179 # Only used by tr///, so backslashes hyphens
4182 if ($n == ord '\\') {
4184 } elsif ($n == ord "-") {
4186 } elsif ($n >= ord(' ') and $n <= ord('~')) {
4188 } elsif ($n == ord "\a") {
4190 } elsif ($n == ord "\b") {
4192 } elsif ($n == ord "\t") {
4194 } elsif ($n == ord "\n") {
4196 } elsif ($n == ord "\e") {
4198 } elsif ($n == ord "\f") {
4200 } elsif ($n == ord "\r") {
4202 } elsif ($n >= ord("\cA") and $n <= ord("\cZ")) {
4203 return '\\c' . chr(ord("@") + $n);
4205 # return '\x' . sprintf("%02x", $n);
4206 return '\\' . sprintf("%03o", $n);
4212 my($str, $c, $tr) = ("");
4213 for ($c = 0; $c < @chars; $c++) {
4216 if ($c <= $#chars - 2 and $chars[$c + 1] == $tr + 1 and
4217 $chars[$c + 2] == $tr + 2)
4219 for (; $c <= $#chars-1 and $chars[$c + 1] == $chars[$c] + 1; $c++)
4222 $str .= pchr($chars[$c]);
4228 sub tr_decode_byte {
4229 my($table, $flags) = @_;
4230 my(@table) = unpack("s*", $table);
4231 splice @table, 0x100, 1; # Number of subsequent elements
4232 my($c, $tr, @from, @to, @delfrom, $delhyphen);
4233 if ($table[ord "-"] != -1 and
4234 $table[ord("-") - 1] == -1 || $table[ord("-") + 1] == -1)
4236 $tr = $table[ord "-"];
4237 $table[ord "-"] = -1;
4241 } else { # -2 ==> delete
4245 for ($c = 0; $c < @table; $c++) {
4248 push @from, $c; push @to, $tr;
4249 } elsif ($tr == -2) {
4253 @from = (@from, @delfrom);
4254 if ($flags & OPpTRANS_COMPLEMENT) {
4257 @from{@from} = (1) x @from;
4258 for ($c = 0; $c < 256; $c++) {
4259 push @newfrom, $c unless $from{$c};
4263 unless ($flags & OPpTRANS_DELETE || !@to) {
4264 pop @to while $#to and $to[$#to] == $to[$#to -1];
4267 $from = collapse(@from);
4268 $to = collapse(@to);
4269 $from .= "-" if $delhyphen;
4270 return ($from, $to);
4275 if ($x == ord "-") {
4277 } elsif ($x == ord "\\") {
4284 # XXX This doesn't yet handle all cases correctly either
4286 sub tr_decode_utf8 {
4287 my($swash_hv, $flags) = @_;
4288 my %swash = $swash_hv->ARRAY;
4290 $final = $swash{'FINAL'}->IV if exists $swash{'FINAL'};
4291 my $none = $swash{"NONE"}->IV;
4292 my $extra = $none + 1;
4293 my(@from, @delfrom, @to);
4295 foreach $line (split /\n/, $swash{'LIST'}->PV) {
4296 my($min, $max, $result) = split(/\t/, $line);
4303 $result = hex $result;
4304 if ($result == $extra) {
4305 push @delfrom, [$min, $max];
4307 push @from, [$min, $max];
4308 push @to, [$result, $result + $max - $min];
4311 for my $i (0 .. $#from) {
4312 if ($from[$i][0] == ord '-') {
4313 unshift @from, splice(@from, $i, 1);
4314 unshift @to, splice(@to, $i, 1);
4316 } elsif ($from[$i][1] == ord '-') {
4319 unshift @from, ord '-';
4320 unshift @to, ord '-';
4324 for my $i (0 .. $#delfrom) {
4325 if ($delfrom[$i][0] == ord '-') {
4326 push @delfrom, splice(@delfrom, $i, 1);
4328 } elsif ($delfrom[$i][1] == ord '-') {
4330 push @delfrom, ord '-';
4334 if (defined $final and $to[$#to][1] != $final) {
4335 push @to, [$final, $final];
4337 push @from, @delfrom;
4338 if ($flags & OPpTRANS_COMPLEMENT) {
4341 for my $i (0 .. $#from) {
4342 push @newfrom, [$next, $from[$i][0] - 1];
4343 $next = $from[$i][1] + 1;
4346 for my $range (@newfrom) {
4347 if ($range->[0] <= $range->[1]) {
4352 my($from, $to, $diff);
4353 for my $chunk (@from) {
4354 $diff = $chunk->[1] - $chunk->[0];
4356 $from .= tr_chr($chunk->[0]) . "-" . tr_chr($chunk->[1]);
4357 } elsif ($diff == 1) {