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/;
29 # List version-specific constants here.
30 # Easiest way to keep this code portable between version looks to
31 # be to fake up a dummy constant that will never actually be true.
32 foreach (qw(OPpSORT_INPLACE OPpSORT_DESCEND OPpITER_REVERSED OPpCONST_NOVER
33 OPpPAD_STATE PMf_SKIPWHITE RXf_SKIPWHITE
34 RXf_PMf_CHARSET RXf_PMf_KEEPCOPY
35 CVf_LOCKED OPpREVERSE_INPLACE OPpSUBSTR_REPL_FIRST
36 PMf_NONDESTRUCT OPpCONST_ARYBASE OPpEVAL_BYTES)) {
39 *{$_} = sub () {0} unless *{$_}{CODE};
43 # Changes between 0.50 and 0.51:
44 # - fixed nulled leave with live enter in sort { }
45 # - fixed reference constants (\"str")
46 # - handle empty programs gracefully
47 # - handle infinite loops (for (;;) {}, while (1) {})
48 # - differentiate between 'for my $x ...' and 'my $x; for $x ...'
49 # - various minor cleanups
50 # - moved globals into an object
51 # - added '-u', like B::C
52 # - package declarations using cop_stash
53 # - subs, formats and code sorted by cop_seq
54 # Changes between 0.51 and 0.52:
55 # - added pp_threadsv (special variables under USE_5005THREADS)
56 # - added documentation
57 # Changes between 0.52 and 0.53:
58 # - many changes adding precedence contexts and associativity
59 # - added '-p' and '-s' output style options
60 # - various other minor fixes
61 # Changes between 0.53 and 0.54:
62 # - added support for new 'for (1..100)' optimization,
64 # Changes between 0.54 and 0.55:
65 # - added support for new qr// construct
66 # - added support for new pp_regcreset OP
67 # Changes between 0.55 and 0.56:
68 # - tested on base/*.t, cmd/*.t, comp/*.t, io/*.t
69 # - fixed $# on non-lexicals broken in last big rewrite
70 # - added temporary fix for change in opcode of OP_STRINGIFY
71 # - fixed problem in 0.54's for() patch in 'for (@ary)'
72 # - fixed precedence in conditional of ?:
73 # - tweaked list paren elimination in 'my($x) = @_'
74 # - made continue-block detection trickier wrt. null ops
75 # - fixed various prototype problems in pp_entersub
76 # - added support for sub prototypes that never get GVs
77 # - added unquoting for special filehandle first arg in truncate
78 # - print doubled rv2gv (a bug) as '*{*GV}' instead of illegal '**GV'
79 # - added semicolons at the ends of blocks
80 # - added -l '#line' declaration option -- fixes cmd/subval.t 27,28
81 # Changes between 0.56 and 0.561:
82 # - fixed multiply-declared my var in pp_truncate (thanks to Sarathy)
83 # - used new B.pm symbolic constants (done by Nick Ing-Simmons)
84 # Changes between 0.561 and 0.57:
85 # - stylistic changes to symbolic constant stuff
86 # - handled scope in s///e replacement code
87 # - added unquote option for expanding "" into concats, etc.
88 # - split method and proto parts of pp_entersub into separate functions
89 # - various minor cleanups
91 # - added parens in \&foo (patch by Albert Dvornik)
92 # Changes between 0.57 and 0.58:
93 # - fixed '0' statements that weren't being printed
94 # - added methods for use from other programs
95 # (based on patches from James Duncan and Hugo van der Sanden)
96 # - added -si and -sT to control indenting (also based on a patch from Hugo)
97 # - added -sv to print something else instead of '???'
98 # - preliminary version of utf8 tr/// handling
100 # - uses of $op->ppaddr changed to new $op->name (done by Sarathy)
101 # - added support for Hugo's new OP_SETSTATE (like nextstate)
102 # Changes between 0.58 and 0.59
103 # - added support for Chip's OP_METHOD_NAMED
104 # - added support for Ilya's OPpTARGET_MY optimization
105 # - elided arrows before '()' subscripts when possible
106 # Changes between 0.59 and 0.60
107 # - support for method attributes was added
108 # - some warnings fixed
109 # - separate recognition of constant subs
110 # - rewrote continue block handling, now recognizing for loops
111 # - added more control of expanding control structures
112 # Changes between 0.60 and 0.61 (mostly by Robin Houston)
114 # - support for pragmas and 'use'
115 # - support for the little-used $[ variable
116 # - support for __DATA__ sections
118 # - BEGIN, CHECK, INIT and END blocks
119 # - scoping of subroutine declarations fixed
120 # - compile-time output from the input program can be suppressed, so that the
121 # output is just the deparsed code. (a change to O.pm in fact)
122 # - our() declarations
123 # - *all* the known bugs are now listed in the BUGS section
124 # - comprehensive test mechanism (TEST -deparse)
125 # Changes between 0.62 and 0.63 (mostly by Rafael Garcia-Suarez)
128 # - support for command-line switches (-l, -0, etc.)
129 # Changes between 0.63 and 0.64
130 # - support for //, CHECK blocks, and assertions
131 # - improved handling of foreach loops and lexicals
132 # - option to use Data::Dumper for constants
134 # - discovered lots more bugs not yet fixed
138 # Changes between 0.72 and 0.73
139 # - support new switch constructs
142 # (See also BUGS section at the end of this file)
144 # - finish tr/// changes
145 # - add option for even more parens (generalize \&foo change)
146 # - left/right context
147 # - copy comments (look at real text with $^P?)
148 # - avoid semis in one-statement blocks
149 # - associativity of &&=, ||=, ?:
150 # - ',' => '=>' (auto-unquote?)
151 # - break long lines ("\r" as discretionary break?)
152 # - configurable syntax highlighting: ANSI color, HTML, TeX, etc.
153 # - more style options: brace style, hex vs. octal, quotes, ...
154 # - print big ints as hex/octal instead of decimal (heuristic?)
155 # - handle 'my $x if 0'?
156 # - version using op_next instead of op_first/sibling?
157 # - avoid string copies (pass arrays, one big join?)
160 # Current test.deparse failures
161 # comp/hints 6 - location of BEGIN blocks wrt. block openings
162 # run/switchI 1 - missing -I switches entirely
163 # perl -Ifoo -e 'print @INC'
164 # op/caller 2 - warning mask propagates backwards before warnings::register
165 # 'use warnings; BEGIN {${^WARNING_BITS} eq "U"x12;} use warnings::register'
166 # op/getpid 2 - can't assign to shared my() declaration (threads only)
167 # 'my $x : shared = 5'
168 # op/override 7 - parens on overridden require change v-string interpretation
169 # 'BEGIN{*CORE::GLOBAL::require=sub {}} require v5.6'
170 # c.f. 'BEGIN { *f = sub {0} }; f 2'
171 # op/pat 774 - losing Unicode-ness of Latin1-only strings
172 # 'use charnames ":short"; $x="\N{latin:a with acute}"'
173 # op/recurse 12 - missing parens on recursive call makes it look like method
175 # op/subst 90 - inconsistent handling of utf8 under "use utf8"
176 # op/taint 29 - "use re 'taint'" deparsed in the wrong place wrt. block open
177 # op/tiehandle compile - "use strict" deparsed in the wrong place
179 # ext/B/t/xref 11 - line numbers when we add newlines to one-line subs
180 # ext/Data/Dumper/t/dumper compile
181 # ext/DB_file/several
183 # ext/Ernno/Errno warnings
184 # ext/IO/lib/IO/t/io_sel 23
185 # ext/PerlIO/t/encoding compile
186 # ext/POSIX/t/posix 6
187 # ext/Socket/Socket 8
188 # ext/Storable/t/croak compile
189 # lib/Attribute/Handlers/t/multi compile
190 # lib/bignum/ several
194 # lib/ExtUtils/t/bytes 4
195 # lib/File/DosGlob compile
196 # lib/Filter/Simple/t/data 1
197 # lib/Math/BigInt/t/constant 1
198 # lib/Net/t/config Deparse-warning
199 # lib/overload compile
200 # lib/Switch/ several
202 # lib/Test/Simple several
204 # lib/Tie/File/t/29_downcopy 5
207 # Object fields (were globals):
210 # (local($a), local($b)) and local($a, $b) have the same internal
211 # representation but the short form looks better. We notice we can
212 # use a large-scale local when checking the list, but need to prevent
213 # individual locals too. This hash holds the addresses of OPs that
214 # have already had their local-ness accounted for. The same thing
218 # CV for current sub (or main program) being deparsed
221 # Cached hash of lexical variables for curcv: keys are
222 # names prefixed with "m" or "o" (representing my/our), and
223 # each value is an array of pairs, indicating the cop_seq of scopes
224 # in which a var of that name is valid.
227 # COP for statement being deparsed
230 # name of the current package for deparsed code
233 # array of [cop_seq, CV, is_format?] for subs and formats we still
237 # as above, but [name, prototype] for subs that never got a GV
239 # subs_done, forms_done:
240 # keys are addresses of GVs for subs and formats we've already
241 # deparsed (or at least put into subs_todo)
244 # keys are names of subs for which we've printed declarations.
245 # That means we can omit parentheses from the arguments. It also means we
246 # need to put CORE:: on core functions of the same name.
249 # Keeps track of fully qualified names of all deparsed subs.
254 # cuddle: ' ' or '\n', depending on -sC
259 # A little explanation of how precedence contexts and associativity
262 # deparse() calls each per-op subroutine with an argument $cx (short
263 # for context, but not the same as the cx* in the perl core), which is
264 # a number describing the op's parents in terms of precedence, whether
265 # they're inside an expression or at statement level, etc. (see
266 # chart below). When ops with children call deparse on them, they pass
267 # along their precedence. Fractional values are used to implement
268 # associativity ('($x + $y) + $z' => '$x + $y + $y') and related
269 # parentheses hacks. The major disadvantage of this scheme is that
270 # it doesn't know about right sides and left sides, so say if you
271 # assign a listop to a variable, it can't tell it's allowed to leave
272 # the parens off the listop.
275 # 26 [TODO] inside interpolation context ("")
276 # 25 left terms and list operators (leftward)
280 # 21 right ! ~ \ and unary + and -
285 # 16 nonassoc named unary operators
286 # 15 nonassoc < > <= >= lt gt le ge
287 # 14 nonassoc == != <=> eq ne cmp
294 # 7 right = += -= *= etc.
296 # 5 nonassoc list operators (rightward)
300 # 1 statement modifiers
301 # 0.5 statements, but still print scopes as do { ... }
304 # Nonprinting characters with special meaning:
305 # \cS - steal parens (see maybe_parens_unop)
306 # \n - newline and indent
307 # \t - increase indent
308 # \b - decrease indent ('outdent')
309 # \f - flush left (no indent)
310 # \cK - kill following semicolon, if any
314 return class($op) eq "NULL";
319 my($cv, $is_form) = @_;
320 return unless ($cv->FILE eq $0 || exists $self->{files}{$cv->FILE});
322 if ($cv->OUTSIDE_SEQ) {
323 $seq = $cv->OUTSIDE_SEQ;
324 } elsif (!null($cv->START) and is_state($cv->START)) {
325 $seq = $cv->START->cop_seq;
329 push @{$self->{'subs_todo'}}, [$seq, $cv, $is_form];
330 unless ($is_form || class($cv->STASH) eq 'SPECIAL') {
331 $self->{'subs_deparsed'}{$cv->STASH->NAME."::".$cv->GV->NAME} = 1;
337 my $ent = shift @{$self->{'subs_todo'}};
340 my $name = $self->gv_name($gv);
342 return "format $name =\n"
343 . $self->deparse_format($ent->[1]). "\n";
345 $self->{'subs_declared'}{$name} = 1;
346 if ($name eq "BEGIN") {
347 my $use_dec = $self->begin_is_use($cv);
348 if (defined ($use_dec) and $self->{'expand'} < 5) {
349 return () if 0 == length($use_dec);
354 if ($self->{'linenums'}) {
355 my $line = $gv->LINE;
356 my $file = $gv->FILE;
357 $l = "\n\f#line $line \"$file\"\n";
360 if (class($cv->STASH) ne "SPECIAL") {
361 my $stash = $cv->STASH->NAME;
362 if ($stash ne $self->{'curstash'}) {
363 $p = "package $stash;\n";
364 $name = "$self->{'curstash'}::$name" unless $name =~ /::/;
365 $self->{'curstash'} = $stash;
367 $name =~ s/^\Q$stash\E::(?!\z|.*::)//;
369 return "${p}${l}sub $name " . $self->deparse_sub($cv);
373 # Return a "use" declaration for this BEGIN block, if appropriate
375 my ($self, $cv) = @_;
376 my $root = $cv->ROOT;
377 local @$self{qw'curcv curcvlex'} = ($cv);
379 #B::walkoptree($cv->ROOT, "debug");
380 my $lineseq = $root->first;
381 return if $lineseq->name ne "lineseq";
383 my $req_op = $lineseq->first->sibling;
384 return if $req_op->name ne "require";
387 if ($req_op->first->private & OPpCONST_BARE) {
388 # Actually it should always be a bareword
389 $module = $self->const_sv($req_op->first)->PV;
390 $module =~ s[/][::]g;
394 $module = $self->const($self->const_sv($req_op->first), 6);
398 my $version_op = $req_op->sibling;
399 return if class($version_op) eq "NULL";
400 if ($version_op->name eq "lineseq") {
401 # We have a version parameter; skip nextstate & pushmark
402 my $constop = $version_op->first->next->next;
404 return unless $self->const_sv($constop)->PV eq $module;
405 $constop = $constop->sibling;
406 $version = $self->const_sv($constop);
407 if (class($version) eq "IV") {
408 $version = $version->int_value;
409 } elsif (class($version) eq "NV") {
410 $version = $version->NV;
411 } elsif (class($version) ne "PVMG") {
412 # Includes PVIV and PVNV
413 $version = $version->PV;
415 # version specified as a v-string
416 $version = 'v'.join '.', map ord, split //, $version->PV;
418 $constop = $constop->sibling;
419 return if $constop->name ne "method_named";
420 return if $self->const_sv($constop)->PV ne "VERSION";
423 $lineseq = $version_op->sibling;
424 return if $lineseq->name ne "lineseq";
425 my $entersub = $lineseq->first->sibling;
426 if ($entersub->name eq "stub") {
427 return "use $module $version ();\n" if defined $version;
428 return "use $module ();\n";
430 return if $entersub->name ne "entersub";
432 # See if there are import arguments
435 my $svop = $entersub->first->sibling; # Skip over pushmark
436 return unless $self->const_sv($svop)->PV eq $module;
438 # Pull out the arguments
439 for ($svop=$svop->sibling; $svop->name ne "method_named";
440 $svop = $svop->sibling) {
441 $args .= ", " if length($args);
442 $args .= $self->deparse($svop, 6);
446 my $method_named = $svop;
447 return if $method_named->name ne "method_named";
448 my $method_name = $self->const_sv($method_named)->PV;
450 if ($method_name eq "unimport") {
454 # Certain pragmas are dealt with using hint bits,
455 # so we ignore them here
456 if ($module eq 'strict' || $module eq 'integer'
457 || $module eq 'bytes' || $module eq 'warnings'
458 || $module eq 'feature') {
462 if (defined $version && length $args) {
463 return "$use $module $version ($args);\n";
464 } elsif (defined $version) {
465 return "$use $module $version;\n";
466 } elsif (length $args) {
467 return "$use $module ($args);\n";
469 return "$use $module;\n";
474 my ($self, $pack, $seen) = @_;
476 if (!defined $pack) {
481 $pack =~ s/(::)?$/::/;
483 $stash = \%{"main::$pack"};
487 $INC{"overload.pm"} ? overload::StrVal($stash) : $stash
489 my %stash = svref_2object($stash)->ARRAY;
490 while (my ($key, $val) = each %stash) {
491 my $class = class($val);
492 if ($class eq "PV") {
493 # Just a prototype. As an ugly but fairly effective way
494 # to find out if it belongs here is to see if the AUTOLOAD
495 # (if any) for the stash was defined in one of our files.
496 my $A = $stash{"AUTOLOAD"};
497 if (defined ($A) && class($A) eq "GV" && defined($A->CV)
498 && class($A->CV) eq "CV") {
500 next unless $AF eq $0 || exists $self->{'files'}{$AF};
502 push @{$self->{'protos_todo'}}, [$pack . $key, $val->PV];
503 } elsif ($class eq "IV" && !($val->FLAGS & SVf_ROK)) {
504 # Just a name. As above.
505 # But skip proxy constant subroutines, as some form of perl-space
506 # visible code must have created them, be it a use statement, or
507 # some direct symbol-table manipulation code that we will Deparse
508 my $A = $stash{"AUTOLOAD"};
509 if (defined ($A) && class($A) eq "GV" && defined($A->CV)
510 && class($A->CV) eq "CV") {
512 next unless $AF eq $0 || exists $self->{'files'}{$AF};
514 push @{$self->{'protos_todo'}}, [$pack . $key, undef];
515 } elsif ($class eq "GV") {
516 if (class(my $cv = $val->CV) ne "SPECIAL") {
517 next if $self->{'subs_done'}{$$val}++;
518 next if $$val != ${$cv->GV}; # Ignore imposters
521 if (class(my $cv = $val->FORM) ne "SPECIAL") {
522 next if $self->{'forms_done'}{$$val}++;
523 next if $$val != ${$cv->GV}; # Ignore imposters
526 if (class($val->HV) ne "SPECIAL" && $key =~ /::$/) {
527 $self->stash_subs($pack . $key, $seen);
537 foreach $ar (@{$self->{'protos_todo'}}) {
538 my $proto = (defined $ar->[1] ? " (". $ar->[1] . ")" : "");
539 push @ret, "sub " . $ar->[0] . "$proto;\n";
541 delete $self->{'protos_todo'};
549 while (length($opt = substr($opts, 0, 1))) {
551 $self->{'cuddle'} = " ";
552 $opts = substr($opts, 1);
553 } elsif ($opt eq "i") {
554 $opts =~ s/^i(\d+)//;
555 $self->{'indent_size'} = $1;
556 } elsif ($opt eq "T") {
557 $self->{'use_tabs'} = 1;
558 $opts = substr($opts, 1);
559 } elsif ($opt eq "v") {
560 $opts =~ s/^v([^.]*)(.|$)//;
561 $self->{'ex_const'} = $1;
568 my $self = bless {}, $class;
569 $self->{'cuddle'} = "\n";
570 $self->{'curcop'} = undef;
571 $self->{'curstash'} = "main";
572 $self->{'ex_const'} = "'???'";
573 $self->{'expand'} = 0;
574 $self->{'files'} = {};
575 $self->{'indent_size'} = 4;
576 $self->{'linenums'} = 0;
577 $self->{'parens'} = 0;
578 $self->{'subs_todo'} = [];
579 $self->{'unquote'} = 0;
580 $self->{'use_dumper'} = 0;
581 $self->{'use_tabs'} = 0;
583 $self->{'ambient_arybase'} = 0;
584 $self->{'ambient_warnings'} = undef; # Assume no lexical warnings
585 $self->{'ambient_hints'} = 0;
586 $self->{'ambient_hinthash'} = undef;
589 while (my $arg = shift @_) {
591 $self->{'use_dumper'} = 1;
592 require Data::Dumper;
593 } elsif ($arg =~ /^-f(.*)/) {
594 $self->{'files'}{$1} = 1;
595 } elsif ($arg eq "-l") {
596 $self->{'linenums'} = 1;
597 } elsif ($arg eq "-p") {
598 $self->{'parens'} = 1;
599 } elsif ($arg eq "-P") {
600 $self->{'noproto'} = 1;
601 } elsif ($arg eq "-q") {
602 $self->{'unquote'} = 1;
603 } elsif (substr($arg, 0, 2) eq "-s") {
604 $self->style_opts(substr $arg, 2);
605 } elsif ($arg =~ /^-x(\d)$/) {
606 $self->{'expand'} = $1;
613 # Mask out the bits that L<warnings::register> uses
616 $WARN_MASK = $warnings::Bits{all} | $warnings::DeadBits{all};
623 # Initialise the contextual information, either from
624 # defaults provided with the ambient_pragmas method,
625 # or from perl's own defaults otherwise.
629 $self->{'arybase'} = $self->{'ambient_arybase'};
630 $self->{'warnings'} = defined ($self->{'ambient_warnings'})
631 ? $self->{'ambient_warnings'} & WARN_MASK
633 $self->{'hints'} = $self->{'ambient_hints'};
634 $self->{'hints'} &= 0xFF if $] < 5.009;
635 $self->{'hinthash'} = $self->{'ambient_hinthash'};
637 # also a convenient place to clear out subs_declared
638 delete $self->{'subs_declared'};
644 my $self = B::Deparse->new(@args);
645 # First deparse command-line args
646 if (defined $^I) { # deparse -i
647 print q(BEGIN { $^I = ).perlstring($^I).qq(; }\n);
649 if ($^W) { # deparse -w
650 print qq(BEGIN { \$^W = $^W; }\n);
652 if ($/ ne "\n" or defined $O::savebackslash) { # deparse -l and -0
653 my $fs = perlstring($/) || 'undef';
654 my $bs = perlstring($O::savebackslash) || 'undef';
655 print qq(BEGIN { \$/ = $fs; \$\\ = $bs; }\n);
657 my @BEGINs = B::begin_av->isa("B::AV") ? B::begin_av->ARRAY : ();
658 my @UNITCHECKs = B::unitcheck_av->isa("B::AV")
659 ? B::unitcheck_av->ARRAY
661 my @CHECKs = B::check_av->isa("B::AV") ? B::check_av->ARRAY : ();
662 my @INITs = B::init_av->isa("B::AV") ? B::init_av->ARRAY : ();
663 my @ENDs = B::end_av->isa("B::AV") ? B::end_av->ARRAY : ();
664 for my $block (@BEGINs, @UNITCHECKs, @CHECKs, @INITs, @ENDs) {
665 $self->todo($block, 0);
668 local($SIG{"__DIE__"}) =
670 if ($self->{'curcop'}) {
671 my $cop = $self->{'curcop'};
672 my($line, $file) = ($cop->line, $cop->file);
673 print STDERR "While deparsing $file near line $line,\n";
676 $self->{'curcv'} = main_cv;
677 $self->{'curcvlex'} = undef;
678 print $self->print_protos;
679 @{$self->{'subs_todo'}} =
680 sort {$a->[0] <=> $b->[0]} @{$self->{'subs_todo'}};
681 print $self->indent($self->deparse_root(main_root)), "\n"
682 unless null main_root;
684 while (scalar(@{$self->{'subs_todo'}})) {
685 push @text, $self->next_todo;
687 print $self->indent(join("", @text)), "\n" if @text;
689 # Print __DATA__ section, if necessary
691 my $laststash = defined $self->{'curcop'}
692 ? $self->{'curcop'}->stash->NAME : $self->{'curstash'};
693 if (defined *{$laststash."::DATA"}{IO}) {
694 print "package $laststash;\n"
695 unless $laststash eq $self->{'curstash'};
697 print readline(*{$laststash."::DATA"});
705 croak "Usage: ->coderef2text(CODEREF)" unless UNIVERSAL::isa($sub, "CODE");
708 return $self->indent($self->deparse_sub(svref_2object($sub)));
711 my %strict_bits = do {
713 map +($_ => strict::bits($_)), qw/refs subs vars/
716 sub ambient_pragmas {
718 my ($arybase, $hint_bits, $warning_bits, $hinthash) = (0, 0);
724 if ($name eq 'strict') {
727 if ($val eq 'none') {
728 $hint_bits &= $strict_bits{$_} for qw/refs subs vars/;
734 @names = qw/refs subs vars/;
740 @names = split' ', $val;
742 $hint_bits |= $strict_bits{$_} for @names;
745 elsif ($name eq '$[') {
746 if (OPpCONST_ARYBASE) {
749 croak "\$[ can't be non-zero on this perl" unless $val == 0;
753 elsif ($name eq 'integer'
755 || $name eq 'utf8') {
758 $hint_bits |= ${$::{"${name}::"}{"hint_bits"}};
761 $hint_bits &= ~${$::{"${name}::"}{"hint_bits"}};
765 elsif ($name eq 're') {
767 if ($val eq 'none') {
768 $hint_bits &= ~re::bits(qw/taint eval/);
774 @names = qw/taint eval/;
780 @names = split' ',$val;
782 $hint_bits |= re::bits(@names);
785 elsif ($name eq 'warnings') {
786 if ($val eq 'none') {
787 $warning_bits = $warnings::NONE;
796 @names = split/\s+/, $val;
799 $warning_bits = $warnings::NONE if !defined ($warning_bits);
800 $warning_bits |= warnings::bits(@names);
803 elsif ($name eq 'warning_bits') {
804 $warning_bits = $val;
807 elsif ($name eq 'hint_bits') {
811 elsif ($name eq '%^H') {
816 croak "Unknown pragma type: $name";
820 croak "The ambient_pragmas method expects an even number of args";
823 $self->{'ambient_arybase'} = $arybase;
824 $self->{'ambient_warnings'} = $warning_bits;
825 $self->{'ambient_hints'} = $hint_bits;
826 $self->{'ambient_hinthash'} = $hinthash;
829 # This method is the inner loop, so try to keep it simple
834 Carp::confess("Null op in deparse") if !defined($op)
835 || class($op) eq "NULL";
836 my $meth = "pp_" . $op->name;
837 return $self->$meth($op, $cx);
843 my @lines = split(/\n/, $txt);
848 my $cmd = substr($line, 0, 1);
849 if ($cmd eq "\t" or $cmd eq "\b") {
850 $level += ($cmd eq "\t" ? 1 : -1) * $self->{'indent_size'};
851 if ($self->{'use_tabs'}) {
852 $leader = "\t" x ($level / 8) . " " x ($level % 8);
854 $leader = " " x $level;
856 $line = substr($line, 1);
858 if (substr($line, 0, 1) eq "\f") {
859 $line = substr($line, 1); # no indent
861 $line = $leader . $line;
865 return join("\n", @lines);
872 Carp::confess("NULL in deparse_sub") if !defined($cv) || $cv->isa("B::NULL");
873 Carp::confess("SPECIAL in deparse_sub") if $cv->isa("B::SPECIAL");
874 local $self->{'curcop'} = $self->{'curcop'};
875 if ($cv->FLAGS & SVf_POK) {
876 $proto = "(". $cv->PV . ") ";
878 if ($cv->CvFLAGS & (CVf_METHOD|CVf_LOCKED|CVf_LVALUE)) {
880 $proto .= "lvalue " if $cv->CvFLAGS & CVf_LVALUE;
881 $proto .= "locked " if $cv->CvFLAGS & CVf_LOCKED;
882 $proto .= "method " if $cv->CvFLAGS & CVf_METHOD;
885 local($self->{'curcv'}) = $cv;
886 local($self->{'curcvlex'});
887 local(@$self{qw'curstash warnings hints hinthash'})
888 = @$self{qw'curstash warnings hints hinthash'};
890 if (not null $cv->ROOT) {
891 my $lineseq = $cv->ROOT->first;
892 if ($lineseq->name eq "lineseq") {
894 for(my$o=$lineseq->first; $$o; $o=$o->sibling) {
897 $body = $self->lineseq(undef, @ops).";";
898 my $scope_en = $self->find_scope_en($lineseq);
899 if (defined $scope_en) {
900 my $subs = join"", $self->seq_subs($scope_en);
901 $body .= ";\n$subs" if length($subs);
905 $body = $self->deparse($cv->ROOT->first, 0);
909 my $sv = $cv->const_sv;
911 # uh-oh. inlinable sub... format it differently
912 return $proto . "{ " . $self->const($sv, 0) . " }\n";
913 } else { # XSUB? (or just a declaration)
917 return $proto ."{\n\t$body\n\b}" ."\n";
924 local($self->{'curcv'}) = $form;
925 local($self->{'curcvlex'});
926 local($self->{'in_format'}) = 1;
927 local(@$self{qw'curstash warnings hints hinthash'})
928 = @$self{qw'curstash warnings hints hinthash'};
929 my $op = $form->ROOT;
931 return "\f." if $op->first->name eq 'stub'
932 || $op->first->name eq 'nextstate';
933 $op = $op->first->first; # skip leavewrite, lineseq
934 while (not null $op) {
935 $op = $op->sibling; # skip nextstate
937 $kid = $op->first->sibling; # skip pushmark
938 push @text, "\f".$self->const_sv($kid)->PV;
939 $kid = $kid->sibling;
940 for (; not null $kid; $kid = $kid->sibling) {
941 push @exprs, $self->deparse($kid, 0);
943 push @text, "\f".join(", ", @exprs)."\n" if @exprs;
946 return join("", @text) . "\f.";
951 return $op->name eq "leave" || $op->name eq "scope"
952 || $op->name eq "lineseq"
953 || ($op->name eq "null" && class($op) eq "UNOP"
954 && (is_scope($op->first) || $op->first->name eq "enter"));
958 my $name = $_[0]->name;
959 return $name eq "nextstate" || $name eq "dbstate" || $name eq "setstate";
962 sub is_miniwhile { # check for one-line loop ('foo() while $y--')
964 return (!null($op) and null($op->sibling)
965 and $op->name eq "null" and class($op) eq "UNOP"
966 and (($op->first->name =~ /^(and|or)$/
967 and $op->first->first->sibling->name eq "lineseq")
968 or ($op->first->name eq "lineseq"
969 and not null $op->first->first->sibling
970 and $op->first->first->sibling->name eq "unstack")
974 # Check if the op and its sibling are the initialization and the rest of a
975 # for (..;..;..) { ... } loop
978 # This OP might be almost anything, though it won't be a
979 # nextstate. (It's the initialization, so in the canonical case it
980 # will be an sassign.) The sibling is (old style) a lineseq whose
981 # first child is a nextstate and whose second is a leaveloop, or
982 # (new style) an unstack whose sibling is a leaveloop.
983 my $lseq = $op->sibling;
984 return 0 unless !is_state($op) and !null($lseq);
985 if ($lseq->name eq "lineseq") {
986 if ($lseq->first && !null($lseq->first) && is_state($lseq->first)
987 && (my $sib = $lseq->first->sibling)) {
988 return (!null($sib) && $sib->name eq "leaveloop");
990 } elsif ($lseq->name eq "unstack" && ($lseq->flags & OPf_SPECIAL)) {
991 my $sib = $lseq->sibling;
992 return $sib && !null($sib) && $sib->name eq "leaveloop";
999 return ($op->name eq "rv2sv" or
1000 $op->name eq "padsv" or
1001 $op->name eq "gv" or # only in array/hash constructs
1002 $op->flags & OPf_KIDS && !null($op->first)
1003 && $op->first->name eq "gvsv");
1008 my($text, $cx, $prec) = @_;
1009 if ($prec < $cx # unary ops nest just fine
1010 or $prec == $cx and $cx != 4 and $cx != 16 and $cx != 21
1011 or $self->{'parens'})
1014 # In a unop, let parent reuse our parens; see maybe_parens_unop
1015 $text = "\cS" . $text if $cx == 16;
1022 # same as above, but get around the 'if it looks like a function' rule
1023 sub maybe_parens_unop {
1025 my($name, $kid, $cx) = @_;
1026 if ($cx > 16 or $self->{'parens'}) {
1027 $kid = $self->deparse($kid, 1);
1028 if ($name eq "umask" && $kid =~ /^\d+$/) {
1029 $kid = sprintf("%#o", $kid);
1031 return $self->keyword($name) . "($kid)";
1033 $kid = $self->deparse($kid, 16);
1034 if ($name eq "umask" && $kid =~ /^\d+$/) {
1035 $kid = sprintf("%#o", $kid);
1037 $name = $self->keyword($name);
1038 if (substr($kid, 0, 1) eq "\cS") {
1040 return $name . substr($kid, 1);
1041 } elsif (substr($kid, 0, 1) eq "(") {
1042 # avoid looks-like-a-function trap with extra parens
1043 # ('+' can lead to ambiguities)
1044 return "$name(" . $kid . ")";
1046 return "$name $kid";
1051 sub maybe_parens_func {
1053 my($func, $text, $cx, $prec) = @_;
1054 if ($prec <= $cx or substr($text, 0, 1) eq "(" or $self->{'parens'}) {
1055 return "$func($text)";
1057 return "$func $text";
1063 my($op, $cx, $text) = @_;
1064 my $our_intro = ($op->name =~ /^(gv|rv2)[ash]v$/) ? OPpOUR_INTRO : 0;
1065 if ($op->private & (OPpLVAL_INTRO|$our_intro)
1066 and not $self->{'avoid_local'}{$$op}) {
1067 my $our_local = ($op->private & OPpLVAL_INTRO) ? "local" : "our";
1068 if( $our_local eq 'our' ) {
1069 if ( $text !~ /^\W(\w+::)*\w+\z/
1070 and !utf8::decode($text) || $text !~ /^\W(\w+::)*\w+\z/
1072 die "Unexpected our($text)\n";
1074 $text =~ s/(\w+::)+//;
1076 if (want_scalar($op)) {
1077 return "$our_local $text";
1079 return $self->maybe_parens_func("$our_local", $text, $cx, 16);
1088 my($op, $cx, $func, @args) = @_;
1089 if ($op->private & OPpTARGET_MY) {
1090 my $var = $self->padname($op->targ);
1091 my $val = $func->($self, $op, 7, @args);
1092 return $self->maybe_parens("$var = $val", $cx, 7);
1094 return $func->($self, $op, $cx, @args);
1101 return $self->{'curcv'}->PADLIST->ARRAYelt(0)->ARRAYelt($targ);
1106 my($op, $cx, $text) = @_;
1107 if ($op->private & OPpLVAL_INTRO and not $self->{'avoid_local'}{$$op}) {
1108 my $my = $op->private & OPpPAD_STATE
1109 ? $self->keyword("state")
1111 if (want_scalar($op)) {
1114 return $self->maybe_parens_func($my, $text, $cx, 16);
1121 # The following OPs don't have functions:
1123 # pp_padany -- does not exist after parsing
1126 if ($AUTOLOAD =~ s/^.*::pp_//) {
1127 warn "unexpected OP_".uc $AUTOLOAD;
1130 die "Undefined subroutine $AUTOLOAD called";
1134 sub DESTROY {} # Do not AUTOLOAD
1136 # $root should be the op which represents the root of whatever
1137 # we're sequencing here. If it's undefined, then we don't append
1138 # any subroutine declarations to the deparsed ops, otherwise we
1139 # append appropriate declarations.
1141 my($self, $root, @ops) = @_;
1144 my $out_cop = $self->{'curcop'};
1145 my $out_seq = defined($out_cop) ? $out_cop->cop_seq : undef;
1147 if (defined $root) {
1148 $limit_seq = $out_seq;
1150 $nseq = $self->find_scope_st($root->sibling) if ${$root->sibling};
1151 $limit_seq = $nseq if !defined($limit_seq)
1152 or defined($nseq) && $nseq < $limit_seq;
1154 $limit_seq = $self->{'limit_seq'}
1155 if defined($self->{'limit_seq'})
1156 && (!defined($limit_seq) || $self->{'limit_seq'} < $limit_seq);
1157 local $self->{'limit_seq'} = $limit_seq;
1159 $self->walk_lineseq($root, \@ops,
1160 sub { push @exprs, $_[0]} );
1162 my $body = join(";\n", grep {length} @exprs);
1164 if (defined $root && defined $limit_seq && !$self->{'in_format'}) {
1165 $subs = join "\n", $self->seq_subs($limit_seq);
1167 return join(";\n", grep {length} $body, $subs);
1171 my($real_block, $self, $op, $cx) = @_;
1175 local(@$self{qw'curstash warnings hints hinthash'})
1176 = @$self{qw'curstash warnings hints hinthash'} if $real_block;
1178 $kid = $op->first->sibling; # skip enter
1179 if (is_miniwhile($kid)) {
1180 my $top = $kid->first;
1181 my $name = $top->name;
1182 if ($name eq "and") {
1184 } elsif ($name eq "or") {
1186 } else { # no conditional -> while 1 or until 0
1187 return $self->deparse($top->first, 1) . " while 1";
1189 my $cond = $top->first;
1190 my $body = $cond->sibling->first; # skip lineseq
1191 $cond = $self->deparse($cond, 1);
1192 $body = $self->deparse($body, 1);
1193 return "$body $name $cond";
1198 for (; !null($kid); $kid = $kid->sibling) {
1201 if ($cx > 0) { # inside an expression, (a do {} while for lineseq)
1202 return "do {\n\t" . $self->lineseq($op, @kids) . "\n\b}";
1204 my $lineseq = $self->lineseq($op, @kids);
1205 return (length ($lineseq) ? "$lineseq;" : "");
1209 sub pp_scope { scopeop(0, @_); }
1210 sub pp_lineseq { scopeop(0, @_); }
1211 sub pp_leave { scopeop(1, @_); }
1213 # This is a special case of scopeop and lineseq, for the case of the
1214 # main_root. The difference is that we print the output statements as
1215 # soon as we get them, for the sake of impatient users.
1219 local(@$self{qw'curstash warnings hints hinthash'})
1220 = @$self{qw'curstash warnings hints hinthash'};
1222 return if null $op->first; # Can happen, e.g., for Bytecode without -k
1223 for (my $kid = $op->first->sibling; !null($kid); $kid = $kid->sibling) {
1226 $self->walk_lineseq($op, \@kids,
1227 sub { print $self->indent($_[0].';');
1228 print "\n" unless $_[1] == $#kids;
1233 my ($self, $op, $kids, $callback) = @_;
1235 for (my $i = 0; $i < @kids; $i++) {
1237 if (is_state $kids[$i]) {
1238 $expr = $self->deparse($kids[$i++], 0);
1240 $callback->($expr, $i);
1244 if (is_for_loop($kids[$i])) {
1245 $callback->($expr . $self->for_loop($kids[$i], 0),
1246 $i += $kids[$i]->sibling->name eq "unstack" ? 2 : 1);
1249 $expr .= $self->deparse($kids[$i], (@kids != 1)/2);
1250 $expr =~ s/;\n?\z//;
1251 $callback->($expr, $i);
1255 # The BEGIN {} is used here because otherwise this code isn't executed
1256 # when you run B::Deparse on itself.
1258 BEGIN { map($globalnames{$_}++, "SIG", "STDIN", "STDOUT", "STDERR", "INC",
1259 "ENV", "ARGV", "ARGVOUT", "_"); }
1265 Carp::confess() unless ref($gv) eq "B::GV";
1266 my $stash = $gv->STASH->NAME;
1267 my $name = $raw ? $gv->NAME : $gv->SAFENAME;
1268 if ($stash eq 'main' && $name =~ /^::/) {
1271 elsif (($stash eq 'main'
1272 && ($globalnames{$name} || $name =~ /^[^A-Za-z_:]/))
1273 or ($stash eq $self->{'curstash'} && !$globalnames{$name}
1274 && ($stash eq 'main' || $name !~ /::/))
1279 $stash = $stash . "::";
1281 if (!$raw and $name =~ /^(\^..|{)/) {
1282 $name = "{$name}"; # ${^WARNING_BITS}, etc and ${
1284 return $stash . $name;
1287 # Return the name to use for a stash variable.
1288 # If a lexical with the same name is in scope, or
1289 # if strictures are enabled, it may need to be
1291 sub stash_variable {
1292 my ($self, $prefix, $name, $cx) = @_;
1294 return "$prefix$name" if $name =~ /::/;
1296 unless ($prefix eq '$' || $prefix eq '@' || #'
1297 $prefix eq '%' || $prefix eq '$#') {
1298 return "$prefix$name";
1301 if ($name =~ /^[^\w+-]$/) {
1302 if (defined $cx && $cx == 26) {
1303 if ($prefix eq '@') {
1304 return "$prefix\{$name}";
1306 elsif ($name eq '#') { return '${#}' } # "${#}a" vs "$#a"
1308 if ($prefix eq '$#') {
1309 return "\$#{$name}";
1313 return $prefix . $self->maybe_qualify($prefix, $name);
1316 # Return just the name, without the prefix. It may be returned as a quoted
1317 # string. The second return value is a boolean indicating that.
1318 sub stash_variable_name {
1319 my($self, $prefix, $gv) = @_;
1320 my $name = $self->gv_name($gv, 1);
1321 $name = $self->maybe_qualify($prefix,$name);
1322 if ($name =~ /^(?:\S|(?!\d)[\ca-\cz]?(?:\w|::)*|\d+)\z/) {
1323 $name =~ s/^([\ca-\cz])/'^'.($1|'@')/e;
1324 $name =~ /^(\^..|{)/ and $name = "{$name}";
1325 return $name, 0; # not quoted
1328 single_delim("q", "'", $name), 1;
1333 my ($self,$prefix,$name) = @_;
1334 my $v = ($prefix eq '$#' ? '@' : $prefix) . $name;
1335 return $name if !$prefix || $name =~ /::/;
1336 return $self->{'curstash'}.'::'. $name
1338 $name =~ /^(?!\d)\w/ # alphabetic
1339 && $v !~ /^\$[ab]\z/ # not $a or $b
1340 && !$globalnames{$name} # not a global name
1341 && $self->{hints} & $strict_bits{vars} # strict vars
1342 && !$self->lex_in_scope($v,1) # no "our"
1343 or $self->lex_in_scope($v); # conflicts with "my" variable
1348 my ($self, $name, $our) = @_;
1349 substr $name, 0, 0, = $our ? 'o' : 'm'; # our/my
1350 $self->populate_curcvlex() if !defined $self->{'curcvlex'};
1352 return 0 if !defined($self->{'curcop'});
1353 my $seq = $self->{'curcop'}->cop_seq;
1354 return 0 if !exists $self->{'curcvlex'}{$name};
1355 for my $a (@{$self->{'curcvlex'}{$name}}) {
1356 my ($st, $en) = @$a;
1357 return 1 if $seq > $st && $seq <= $en;
1362 sub populate_curcvlex {
1364 for (my $cv = $self->{'curcv'}; class($cv) eq "CV"; $cv = $cv->OUTSIDE) {
1365 my $padlist = $cv->PADLIST;
1366 # an undef CV still in lexical chain
1367 next if class($padlist) eq "SPECIAL";
1368 my @padlist = $padlist->ARRAY;
1369 my @ns = $padlist[0]->ARRAY;
1371 for (my $i=0; $i<@ns; ++$i) {
1372 next if class($ns[$i]) eq "SPECIAL";
1373 if (class($ns[$i]) eq "PV") {
1374 # Probably that pesky lexical @_
1377 my $name = $ns[$i]->PVX;
1378 my ($seq_st, $seq_en) =
1379 ($ns[$i]->FLAGS & SVf_FAKE)
1381 : ($ns[$i]->COP_SEQ_RANGE_LOW, $ns[$i]->COP_SEQ_RANGE_HIGH);
1383 push @{$self->{'curcvlex'}{
1384 ($ns[$i]->FLAGS & SVpad_OUR ? 'o' : 'm') . $name
1385 }}, [$seq_st, $seq_en];
1390 sub find_scope_st { ((find_scope(@_))[0]); }
1391 sub find_scope_en { ((find_scope(@_))[1]); }
1393 # Recurses down the tree, looking for pad variable introductions and COPs
1395 my ($self, $op, $scope_st, $scope_en) = @_;
1396 carp("Undefined op in find_scope") if !defined $op;
1397 return ($scope_st, $scope_en) unless $op->flags & OPf_KIDS;
1400 while(my $op = shift @queue ) {
1401 for (my $o=$op->first; $$o; $o=$o->sibling) {
1402 if ($o->name =~ /^pad.v$/ && $o->private & OPpLVAL_INTRO) {
1403 my $s = int($self->padname_sv($o->targ)->COP_SEQ_RANGE_LOW);
1404 my $e = $self->padname_sv($o->targ)->COP_SEQ_RANGE_HIGH;
1405 $scope_st = $s if !defined($scope_st) || $s < $scope_st;
1406 $scope_en = $e if !defined($scope_en) || $e > $scope_en;
1407 return ($scope_st, $scope_en);
1409 elsif (is_state($o)) {
1410 my $c = $o->cop_seq;
1411 $scope_st = $c if !defined($scope_st) || $c < $scope_st;
1412 $scope_en = $c if !defined($scope_en) || $c > $scope_en;
1413 return ($scope_st, $scope_en);
1415 elsif ($o->flags & OPf_KIDS) {
1416 unshift (@queue, $o);
1421 return ($scope_st, $scope_en);
1424 # Returns a list of subs which should be inserted before the COP
1426 my ($self, $op, $out_seq) = @_;
1427 my $seq = $op->cop_seq;
1428 # If we have nephews, then our sequence number indicates
1429 # the cop_seq of the end of some sort of scope.
1430 if (class($op->sibling) ne "NULL" && $op->sibling->flags & OPf_KIDS
1431 and my $nseq = $self->find_scope_st($op->sibling) ) {
1434 $seq = $out_seq if defined($out_seq) && $out_seq < $seq;
1435 return $self->seq_subs($seq);
1439 my ($self, $seq) = @_;
1441 #push @text, "# ($seq)\n";
1443 return "" if !defined $seq;
1444 while (scalar(@{$self->{'subs_todo'}})
1445 and $seq > $self->{'subs_todo'}[0][0]) {
1446 push @text, $self->next_todo;
1451 my $feature_bundle_mask = 0x1c000000;
1453 sub _features_from_bundle {
1454 my ($hints, $hh) = @_;
1457 # Shh! Keep quite about this function. It is not to be
1459 foreach (@{feature::current_bundle()}) {
1460 $hh->{$feature::feature{$_}} = 1;
1465 # Notice how subs and formats are inserted between statements here;
1466 # also $[ assignments and pragmas.
1470 $self->{'curcop'} = $op;
1472 push @text, $self->cop_subs($op);
1473 my $stash = $op->stashpv;
1474 if ($stash ne $self->{'curstash'}) {
1475 push @text, "package $stash;\n";
1476 $self->{'curstash'} = $stash;
1479 if (OPpCONST_ARYBASE && $self->{'arybase'} != $op->arybase) {
1480 push @text, '$[ = '. $op->arybase .";\n";
1481 $self->{'arybase'} = $op->arybase;
1484 my $warnings = $op->warnings;
1486 if ($warnings->isa("B::SPECIAL") && $$warnings == 4) {
1487 $warning_bits = $warnings::Bits{"all"} & WARN_MASK;
1489 elsif ($warnings->isa("B::SPECIAL") && $$warnings == 5) {
1490 $warning_bits = $warnings::NONE;
1492 elsif ($warnings->isa("B::SPECIAL")) {
1493 $warning_bits = undef;
1496 $warning_bits = $warnings->PV & WARN_MASK;
1499 if (defined ($warning_bits) and
1500 !defined($self->{warnings}) || $self->{'warnings'} ne $warning_bits) {
1501 push @text, declare_warnings($self->{'warnings'}, $warning_bits);
1502 $self->{'warnings'} = $warning_bits;
1505 my $hints = $] < 5.008009 ? $op->private : $op->hints;
1506 my $old_hints = $self->{'hints'};
1507 if ($self->{'hints'} != $hints) {
1508 push @text, declare_hints($self->{'hints'}, $hints);
1509 $self->{'hints'} = $hints;
1514 $newhh = $op->hints_hash->HASH;
1517 if ($] >= 5.015006) {
1518 # feature bundle hints
1519 my $from = $old_hints & $feature_bundle_mask;
1520 my $to = $ hints & $feature_bundle_mask;
1523 if ($to == $feature_bundle_mask) {
1524 if ($self->{'hinthash'}) {
1525 delete $self->{'hinthash'}{$_}
1526 for grep /^feature_/, keys %{$self->{'hinthash'}};
1528 else { $self->{'hinthash'} = {} }
1530 = _features_from_bundle($from, $self->{'hinthash'});
1534 $feature::hint_bundles[$to >> $feature::hint_shift];
1535 $bundle =~ s/(\d[13579])\z/$1+1/e; # 5.11 => 5.12
1536 push @text, "no feature;\n",
1537 "use feature ':$bundle';\n";
1543 push @text, declare_hinthash(
1544 $self->{'hinthash'}, $newhh,
1545 $self->{indent_size}, $self->{hints},
1547 $self->{'hinthash'} = $newhh;
1550 # This should go after of any branches that add statements, to
1551 # increase the chances that it refers to the same line it did in
1552 # the original program.
1553 if ($self->{'linenums'}) {
1554 push @text, "\f#line " . $op->line .
1555 ' "' . $op->file, qq'"\n';
1558 push @text, $op->label . ": " if $op->label;
1560 return join("", @text);
1563 sub declare_warnings {
1564 my ($from, $to) = @_;
1565 if (($to & WARN_MASK) eq (warnings::bits("all") & WARN_MASK)) {
1566 return "use warnings;\n";
1568 elsif (($to & WARN_MASK) eq ("\0"x length($to) & WARN_MASK)) {
1569 return "no warnings;\n";
1571 return "BEGIN {\${^WARNING_BITS} = ".perlstring($to)."}\n";
1575 my ($from, $to) = @_;
1576 my $use = $to & ~$from;
1577 my $no = $from & ~$to;
1579 for my $pragma (hint_pragmas($use)) {
1580 $decls .= "use $pragma;\n";
1582 for my $pragma (hint_pragmas($no)) {
1583 $decls .= "no $pragma;\n";
1588 # Internal implementation hints that the core sets automatically, so don't need
1589 # (or want) to be passed back to the user
1590 my %ignored_hints = (
1601 sub declare_hinthash {
1602 my ($from, $to, $indent, $hints) = @_;
1603 my $doing_features =
1604 ($hints & $feature_bundle_mask) == $feature_bundle_mask;
1607 my @unfeatures; # bugs?
1608 for my $key (sort keys %$to) {
1609 next if $ignored_hints{$key};
1610 my $is_feature = $key =~ /^feature_/ && $^V ge 5.15.6;
1611 next if $is_feature and not $doing_features;
1612 if (!exists $from->{$key} or $from->{$key} ne $to->{$key}) {
1613 push(@features, $key), next if $is_feature;
1615 qq(\$^H{) . single_delim("q", "'", $key) . qq(} = )
1618 ? single_delim("q", "'", $to->{$key})
1624 for my $key (sort keys %$from) {
1625 next if $ignored_hints{$key};
1626 my $is_feature = $key =~ /^feature_/ && $^V ge 5.15.6;
1627 next if $is_feature and not $doing_features;
1628 if (!exists $to->{$key}) {
1629 push(@unfeatures, $key), next if $is_feature;
1630 push @decls, qq(delete \$^H{'$key'};);
1634 if (@features || @unfeatures) {
1636 if (!%rev_feature) { %rev_feature = reverse %feature::feature }
1639 push @ret, "use feature "
1640 . join(", ", map "'$rev_feature{$_}'", @features) . ";\n";
1643 push @ret, "no feature "
1644 . join(", ", map "'$rev_feature{$_}'", @unfeatures)
1649 join("\n" . (" " x $indent), "BEGIN {", @decls) . "\n}\n";
1655 my (@pragmas, @strict);
1656 push @pragmas, "integer" if $bits & 0x1;
1657 for (sort keys %strict_bits) {
1658 push @strict, "'$_'" if $bits & $strict_bits{$_};
1660 if (@strict == keys %strict_bits) {
1661 push @pragmas, "strict";
1664 push @pragmas, "strict " . join ', ', @strict;
1666 push @pragmas, "bytes" if $bits & 0x8;
1670 sub pp_dbstate { pp_nextstate(@_) }
1671 sub pp_setstate { pp_nextstate(@_) }
1673 sub pp_unstack { return "" } # see also leaveloop
1675 my %feature_keywords = (
1676 # keyword => 'feature',
1681 default => 'switch',
1683 evalbytes=>'evalbytes',
1684 __SUB__ => '__SUB__',
1691 return $name if $name =~ /^CORE::/; # just in case
1692 if (exists $feature_keywords{$name}) {
1694 my $hints = $self->{hints} & $feature_bundle_mask;
1695 if ($hints && $hints != $feature_bundle_mask) {
1696 $hh = _features_from_bundle($self->{hints});
1698 elsif ($hints) { $hh = $self->{'hinthash'} }
1699 return "CORE::$name"
1701 || !$hh->{"feature_$feature_keywords{$name}"}
1704 $name !~ /^(?:chom?p|do|exec|glob|s(?:elect|ystem))\z/
1705 && !defined eval{prototype "CORE::$name"}
1708 exists $self->{subs_declared}{$name}
1710 exists &{"$self->{curstash}::$name"}
1712 return "CORE::$name"
1719 my($op, $cx, $name) = @_;
1720 return $self->keyword($name);
1725 my($op, $cx, $name) = @_;
1733 sub pp_wantarray { baseop(@_, "wantarray") }
1734 sub pp_fork { baseop(@_, "fork") }
1735 sub pp_wait { maybe_targmy(@_, \&baseop, "wait") }
1736 sub pp_getppid { maybe_targmy(@_, \&baseop, "getppid") }
1737 sub pp_time { maybe_targmy(@_, \&baseop, "time") }
1738 sub pp_tms { baseop(@_, "times") }
1739 sub pp_ghostent { baseop(@_, "gethostent") }
1740 sub pp_gnetent { baseop(@_, "getnetent") }
1741 sub pp_gprotoent { baseop(@_, "getprotoent") }
1742 sub pp_gservent { baseop(@_, "getservent") }
1743 sub pp_ehostent { baseop(@_, "endhostent") }
1744 sub pp_enetent { baseop(@_, "endnetent") }
1745 sub pp_eprotoent { baseop(@_, "endprotoent") }
1746 sub pp_eservent { baseop(@_, "endservent") }
1747 sub pp_gpwent { baseop(@_, "getpwent") }
1748 sub pp_spwent { baseop(@_, "setpwent") }
1749 sub pp_epwent { baseop(@_, "endpwent") }
1750 sub pp_ggrent { baseop(@_, "getgrent") }
1751 sub pp_sgrent { baseop(@_, "setgrent") }
1752 sub pp_egrent { baseop(@_, "endgrent") }
1753 sub pp_getlogin { baseop(@_, "getlogin") }
1755 sub POSTFIX () { 1 }
1757 # I couldn't think of a good short name, but this is the category of
1758 # symbolic unary operators with interesting precedence
1762 my($op, $cx, $name, $prec, $flags) = (@_, 0);
1763 my $kid = $op->first;
1764 $kid = $self->deparse($kid, $prec);
1765 return $self->maybe_parens(($flags & POSTFIX)
1767 # avoid confusion with filetests
1769 && $kid =~ /^[a-zA-Z](?!\w)/
1775 sub pp_preinc { pfixop(@_, "++", 23) }
1776 sub pp_predec { pfixop(@_, "--", 23) }
1777 sub pp_postinc { maybe_targmy(@_, \&pfixop, "++", 23, POSTFIX) }
1778 sub pp_postdec { maybe_targmy(@_, \&pfixop, "--", 23, POSTFIX) }
1779 sub pp_i_preinc { pfixop(@_, "++", 23) }
1780 sub pp_i_predec { pfixop(@_, "--", 23) }
1781 sub pp_i_postinc { maybe_targmy(@_, \&pfixop, "++", 23, POSTFIX) }
1782 sub pp_i_postdec { maybe_targmy(@_, \&pfixop, "--", 23, POSTFIX) }
1783 sub pp_complement { maybe_targmy(@_, \&pfixop, "~", 21) }
1785 sub pp_negate { maybe_targmy(@_, \&real_negate) }
1789 if ($op->first->name =~ /^(i_)?negate$/) {
1791 $self->pfixop($op, $cx, "-", 21.5);
1793 $self->pfixop($op, $cx, "-", 21);
1796 sub pp_i_negate { pp_negate(@_) }
1802 $self->listop($op, $cx, "not", $op->first);
1804 $self->pfixop($op, $cx, "!", 21);
1810 my($op, $cx, $name, $nollafr) = @_;
1812 if ($op->flags & OPf_KIDS) {
1815 # this deals with 'boolkeys' right now
1816 return $self->deparse($kid,$cx);
1818 my $builtinname = $name;
1819 $builtinname =~ /^CORE::/ or $builtinname = "CORE::$name";
1820 if (defined prototype($builtinname)
1821 && prototype($builtinname) =~ /^;?\*/
1822 && $kid->name eq "rv2gv") {
1827 ($kid = $self->deparse($kid, 16)) =~ s/^\cS//;
1828 return $self->maybe_parens(
1829 $self->keyword($name) . " $kid", $cx, 16
1832 return $self->maybe_parens_unop($name, $kid, $cx);
1834 return $self->maybe_parens(
1835 $self->keyword($name) . ($op->flags & OPf_SPECIAL ? "()" : ""),
1841 sub pp_chop { maybe_targmy(@_, \&unop, "chop") }
1842 sub pp_chomp { maybe_targmy(@_, \&unop, "chomp") }
1843 sub pp_schop { maybe_targmy(@_, \&unop, "chop") }
1844 sub pp_schomp { maybe_targmy(@_, \&unop, "chomp") }
1845 sub pp_defined { unop(@_, "defined") }
1846 sub pp_undef { unop(@_, "undef") }
1847 sub pp_study { unop(@_, "study") }
1848 sub pp_ref { unop(@_, "ref") }
1849 sub pp_pos { maybe_local(@_, unop(@_, "pos")) }
1851 sub pp_sin { maybe_targmy(@_, \&unop, "sin") }
1852 sub pp_cos { maybe_targmy(@_, \&unop, "cos") }
1853 sub pp_rand { maybe_targmy(@_, \&unop, "rand") }
1854 sub pp_srand { unop(@_, "srand") }
1855 sub pp_exp { maybe_targmy(@_, \&unop, "exp") }
1856 sub pp_log { maybe_targmy(@_, \&unop, "log") }
1857 sub pp_sqrt { maybe_targmy(@_, \&unop, "sqrt") }
1858 sub pp_int { maybe_targmy(@_, \&unop, "int") }
1859 sub pp_hex { maybe_targmy(@_, \&unop, "hex") }
1860 sub pp_oct { maybe_targmy(@_, \&unop, "oct") }
1861 sub pp_abs { maybe_targmy(@_, \&unop, "abs") }
1863 sub pp_length { maybe_targmy(@_, \&unop, "length") }
1864 sub pp_ord { maybe_targmy(@_, \&unop, "ord") }
1865 sub pp_chr { maybe_targmy(@_, \&unop, "chr") }
1867 sub pp_each { unop(@_, "each") }
1868 sub pp_values { unop(@_, "values") }
1869 sub pp_keys { unop(@_, "keys") }
1870 { no strict 'refs'; *{"pp_r$_"} = *{"pp_$_"} for qw< keys each values >; }
1872 # no name because its an optimisation op that has no keyword
1875 sub pp_aeach { unop(@_, "each") }
1876 sub pp_avalues { unop(@_, "values") }
1877 sub pp_akeys { unop(@_, "keys") }
1878 sub pp_pop { unop(@_, "pop") }
1879 sub pp_shift { unop(@_, "shift") }
1881 sub pp_caller { unop(@_, "caller") }
1882 sub pp_reset { unop(@_, "reset") }
1883 sub pp_exit { unop(@_, "exit") }
1884 sub pp_prototype { unop(@_, "prototype") }
1886 sub pp_close { unop(@_, "close") }
1887 sub pp_fileno { unop(@_, "fileno") }
1888 sub pp_umask { unop(@_, "umask") }
1889 sub pp_untie { unop(@_, "untie") }
1890 sub pp_tied { unop(@_, "tied") }
1891 sub pp_dbmclose { unop(@_, "dbmclose") }
1892 sub pp_getc { unop(@_, "getc") }
1893 sub pp_eof { unop(@_, "eof") }
1894 sub pp_tell { unop(@_, "tell") }
1895 sub pp_getsockname { unop(@_, "getsockname") }
1896 sub pp_getpeername { unop(@_, "getpeername") }
1898 sub pp_chdir { maybe_targmy(@_, \&unop, "chdir") }
1899 sub pp_chroot { maybe_targmy(@_, \&unop, "chroot") }
1900 sub pp_readlink { unop(@_, "readlink") }
1901 sub pp_rmdir { maybe_targmy(@_, \&unop, "rmdir") }
1902 sub pp_readdir { unop(@_, "readdir") }
1903 sub pp_telldir { unop(@_, "telldir") }
1904 sub pp_rewinddir { unop(@_, "rewinddir") }
1905 sub pp_closedir { unop(@_, "closedir") }
1906 sub pp_getpgrp { maybe_targmy(@_, \&unop, "getpgrp") }
1907 sub pp_localtime { unop(@_, "localtime") }
1908 sub pp_gmtime { unop(@_, "gmtime") }
1909 sub pp_alarm { unop(@_, "alarm") }
1910 sub pp_sleep { maybe_targmy(@_, \&unop, "sleep") }
1913 my $code = unop(@_, "do", 1); # llafr does not apply
1914 if ($code =~ s/^((?:CORE::)?do) \{/$1({/) { $code .= ')' }
1920 $_[1]->private & OPpEVAL_BYTES ? $_[0]->keyword('evalbytes') : "eval"
1924 sub pp_ghbyname { unop(@_, "gethostbyname") }
1925 sub pp_gnbyname { unop(@_, "getnetbyname") }
1926 sub pp_gpbyname { unop(@_, "getprotobyname") }
1927 sub pp_shostent { unop(@_, "sethostent") }
1928 sub pp_snetent { unop(@_, "setnetent") }
1929 sub pp_sprotoent { unop(@_, "setprotoent") }
1930 sub pp_sservent { unop(@_, "setservent") }
1931 sub pp_gpwnam { unop(@_, "getpwnam") }
1932 sub pp_gpwuid { unop(@_, "getpwuid") }
1933 sub pp_ggrnam { unop(@_, "getgrnam") }
1934 sub pp_ggrgid { unop(@_, "getgrgid") }
1936 sub pp_lock { unop(@_, "lock") }
1938 sub pp_continue { unop(@_, "continue"); }
1939 sub pp_break { unop(@_, "break"); }
1943 my($op, $cx, $givwhen) = @_;
1945 my $enterop = $op->first;
1947 if ($enterop->flags & OPf_SPECIAL) {
1948 $head = $self->keyword("default");
1949 $block = $self->deparse($enterop->first, 0);
1952 my $cond = $enterop->first;
1953 my $cond_str = $self->deparse($cond, 1);
1954 $head = "$givwhen ($cond_str)";
1955 $block = $self->deparse($cond->sibling, 0);
1963 sub pp_leavegiven { givwhen(@_, $_[0]->keyword("given")); }
1964 sub pp_leavewhen { givwhen(@_, $_[0]->keyword("when")); }
1970 if ($op->private & OPpEXISTS_SUB) {
1971 # Checking for the existence of a subroutine
1972 return $self->maybe_parens_func("exists",
1973 $self->pp_rv2cv($op->first, 16), $cx, 16);
1975 if ($op->flags & OPf_SPECIAL) {
1976 # Array element, not hash element
1977 return $self->maybe_parens_func("exists",
1978 $self->pp_aelem($op->first, 16), $cx, 16);
1980 return $self->maybe_parens_func("exists", $self->pp_helem($op->first, 16),
1988 if ($op->private & OPpSLICE) {
1989 if ($op->flags & OPf_SPECIAL) {
1990 # Deleting from an array, not a hash
1991 return $self->maybe_parens_func("delete",
1992 $self->pp_aslice($op->first, 16),
1995 return $self->maybe_parens_func("delete",
1996 $self->pp_hslice($op->first, 16),
1999 if ($op->flags & OPf_SPECIAL) {
2000 # Deleting from an array, not a hash
2001 return $self->maybe_parens_func("delete",
2002 $self->pp_aelem($op->first, 16),
2005 return $self->maybe_parens_func("delete",
2006 $self->pp_helem($op->first, 16),
2014 my $opname = $op->flags & OPf_SPECIAL ? 'CORE::require' : 'require';
2015 if (class($op) eq "UNOP" and $op->first->name eq "const"
2016 and $op->first->private & OPpCONST_BARE)
2018 my $name = $self->const_sv($op->first)->PV;
2021 return $self->maybe_parens("$opname $name", $cx, 16);
2025 $op->first->name eq 'const'
2026 && $op->first->private & OPpCONST_NOVER
2029 1, # llafr does not apply
2037 my $kid = $op->first;
2038 if (not null $kid->sibling) {
2039 # XXX Was a here-doc
2040 return $self->dquote($op);
2042 $self->unop(@_, "scalar");
2049 return $self->{'curcv'}->PADLIST->ARRAYelt(1)->ARRAYelt($targ);
2052 sub anon_hash_or_list {
2056 my($pre, $post) = @{{"anonlist" => ["[","]"],
2057 "anonhash" => ["{","}"]}->{$op->name}};
2059 $op = $op->first->sibling; # skip pushmark
2060 for (; !null($op); $op = $op->sibling) {
2061 $expr = $self->deparse($op, 6);
2064 if ($pre eq "{" and $cx < 1) {
2065 # Disambiguate that it's not a block
2068 return $pre . join(", ", @exprs) . $post;
2074 if ($op->flags & OPf_SPECIAL) {
2075 return $self->anon_hash_or_list($op, $cx);
2077 warn "Unexpected op pp_" . $op->name() . " without OPf_SPECIAL";
2081 *pp_anonhash = \&pp_anonlist;
2086 my $kid = $op->first;
2087 if ($kid->name eq "null") {
2089 if (!null($kid->sibling) and
2090 $kid->sibling->name eq "anoncode") {
2091 return $self->e_anoncode({ code => $self->padval($kid->sibling->targ) });
2092 } elsif ($kid->name eq "pushmark") {
2093 my $sib_name = $kid->sibling->name;
2094 if ($sib_name =~ /^(pad|rv2)[ah]v$/
2095 and not $kid->sibling->flags & OPf_REF)
2097 # The @a in \(@a) isn't in ref context, but only when the
2099 return "\\(" . $self->pp_list($op->first) . ")";
2100 } elsif ($sib_name eq 'entersub') {
2101 my $text = $self->deparse($kid->sibling, 1);
2102 # Always show parens for \(&func()), but only with -p otherwise
2103 $text = "($text)" if $self->{'parens'}
2104 or $kid->sibling->private & OPpENTERSUB_AMPER;
2109 $self->pfixop($op, $cx, "\\", 20);
2113 my ($self, $info) = @_;
2114 my $text = $self->deparse_sub($info->{code});
2115 return "sub " . $text;
2118 sub pp_srefgen { pp_refgen(@_) }
2123 my $kid = $op->first;
2124 $kid = $kid->first if $kid->name eq "rv2gv"; # <$fh>
2125 return "<" . $self->deparse($kid, 1) . ">" if is_scalar($kid);
2126 return $self->unop($op, $cx, "readline");
2132 return "<" . $self->gv_name($self->gv_or_padgv($op)) . ">";
2135 # Unary operators that can occur as pseudo-listops inside double quotes
2138 my($op, $cx, $name, $prec, $flags) = (@_, 0, 0);
2140 if ($op->flags & OPf_KIDS) {
2142 # If there's more than one kid, the first is an ex-pushmark.
2143 $kid = $kid->sibling if not null $kid->sibling;
2144 return $self->maybe_parens_unop($name, $kid, $cx);
2146 return $name . ($op->flags & OPf_SPECIAL ? "()" : "");
2150 sub pp_ucfirst { dq_unop(@_, "ucfirst") }
2151 sub pp_lcfirst { dq_unop(@_, "lcfirst") }
2152 sub pp_uc { dq_unop(@_, "uc") }
2153 sub pp_lc { dq_unop(@_, "lc") }
2154 sub pp_quotemeta { maybe_targmy(@_, \&dq_unop, "quotemeta") }
2155 sub pp_fc { dq_unop(@_, "fc") }
2159 my ($op, $cx, $name) = @_;
2160 if (class($op) eq "PVOP") {
2161 $name .= " " . $op->pv;
2162 } elsif (class($op) eq "OP") {
2164 } elsif (class($op) eq "UNOP") {
2165 (my $kid = $self->deparse($op->first, 16)) =~ s/^\cS//;
2168 return $self->maybe_parens($name, $cx, 16);
2171 sub pp_last { loopex(@_, "last") }
2172 sub pp_next { loopex(@_, "next") }
2173 sub pp_redo { loopex(@_, "redo") }
2174 sub pp_goto { loopex(@_, "goto") }
2175 sub pp_dump { loopex(@_, "CORE::dump") }
2179 my($op, $cx, $name) = @_;
2180 if (class($op) eq "UNOP") {
2181 # Genuine '-X' filetests are exempt from the LLAFR, but not
2183 if ($name =~ /^-/) {
2184 (my $kid = $self->deparse($op->first, 16)) =~ s/^\cS//;
2185 return $self->maybe_parens("$name $kid", $cx, 16);
2187 return $self->maybe_parens_unop($name, $op->first, $cx);
2188 } elsif (class($op) =~ /^(SV|PAD)OP$/) {
2189 return $self->maybe_parens_func($name, $self->pp_gv($op, 1), $cx, 16);
2190 } else { # I don't think baseop filetests ever survive ck_ftst, but...
2195 sub pp_lstat { ftst(@_, "lstat") }
2196 sub pp_stat { ftst(@_, "stat") }
2197 sub pp_ftrread { ftst(@_, "-R") }
2198 sub pp_ftrwrite { ftst(@_, "-W") }
2199 sub pp_ftrexec { ftst(@_, "-X") }
2200 sub pp_fteread { ftst(@_, "-r") }
2201 sub pp_ftewrite { ftst(@_, "-w") }
2202 sub pp_fteexec { ftst(@_, "-x") }
2203 sub pp_ftis { ftst(@_, "-e") }
2204 sub pp_fteowned { ftst(@_, "-O") }
2205 sub pp_ftrowned { ftst(@_, "-o") }
2206 sub pp_ftzero { ftst(@_, "-z") }
2207 sub pp_ftsize { ftst(@_, "-s") }
2208 sub pp_ftmtime { ftst(@_, "-M") }
2209 sub pp_ftatime { ftst(@_, "-A") }
2210 sub pp_ftctime { ftst(@_, "-C") }
2211 sub pp_ftsock { ftst(@_, "-S") }
2212 sub pp_ftchr { ftst(@_, "-c") }
2213 sub pp_ftblk { ftst(@_, "-b") }
2214 sub pp_ftfile { ftst(@_, "-f") }
2215 sub pp_ftdir { ftst(@_, "-d") }
2216 sub pp_ftpipe { ftst(@_, "-p") }
2217 sub pp_ftlink { ftst(@_, "-l") }
2218 sub pp_ftsuid { ftst(@_, "-u") }
2219 sub pp_ftsgid { ftst(@_, "-g") }
2220 sub pp_ftsvtx { ftst(@_, "-k") }
2221 sub pp_fttty { ftst(@_, "-t") }
2222 sub pp_fttext { ftst(@_, "-T") }
2223 sub pp_ftbinary { ftst(@_, "-B") }
2225 sub SWAP_CHILDREN () { 1 }
2226 sub ASSIGN () { 2 } # has OP= variant
2227 sub LIST_CONTEXT () { 4 } # Assignment is in list context
2233 my $name = $op->name;
2234 if ($name eq "concat" and $op->first->name eq "concat") {
2235 # avoid spurious '=' -- see comment in pp_concat
2238 if ($name eq "null" and class($op) eq "UNOP"
2239 and $op->first->name =~ /^(and|x?or)$/
2240 and null $op->first->sibling)
2242 # Like all conditional constructs, OP_ANDs and OP_ORs are topped
2243 # with a null that's used as the common end point of the two
2244 # flows of control. For precedence purposes, ignore it.
2245 # (COND_EXPRs have these too, but we don't bother with
2246 # their associativity).
2247 return assoc_class($op->first);
2249 return $name . ($op->flags & OPf_STACKED ? "=" : "");
2252 # Left associative operators, like '+', for which
2253 # $a + $b + $c is equivalent to ($a + $b) + $c
2256 %left = ('multiply' => 19, 'i_multiply' => 19,
2257 'divide' => 19, 'i_divide' => 19,
2258 'modulo' => 19, 'i_modulo' => 19,
2260 'add' => 18, 'i_add' => 18,
2261 'subtract' => 18, 'i_subtract' => 18,
2263 'left_shift' => 17, 'right_shift' => 17,
2265 'bit_or' => 12, 'bit_xor' => 12,
2267 'or' => 2, 'xor' => 2,
2271 sub deparse_binop_left {
2273 my($op, $left, $prec) = @_;
2274 if ($left{assoc_class($op)} && $left{assoc_class($left)}
2275 and $left{assoc_class($op)} == $left{assoc_class($left)})
2277 return $self->deparse($left, $prec - .00001);
2279 return $self->deparse($left, $prec);
2283 # Right associative operators, like '=', for which
2284 # $a = $b = $c is equivalent to $a = ($b = $c)
2287 %right = ('pow' => 22,
2288 'sassign=' => 7, 'aassign=' => 7,
2289 'multiply=' => 7, 'i_multiply=' => 7,
2290 'divide=' => 7, 'i_divide=' => 7,
2291 'modulo=' => 7, 'i_modulo=' => 7,
2293 'add=' => 7, 'i_add=' => 7,
2294 'subtract=' => 7, 'i_subtract=' => 7,
2296 'left_shift=' => 7, 'right_shift=' => 7,
2298 'bit_or=' => 7, 'bit_xor=' => 7,
2304 sub deparse_binop_right {
2306 my($op, $right, $prec) = @_;
2307 if ($right{assoc_class($op)} && $right{assoc_class($right)}
2308 and $right{assoc_class($op)} == $right{assoc_class($right)})
2310 return $self->deparse($right, $prec - .00001);
2312 return $self->deparse($right, $prec);
2318 my ($op, $cx, $opname, $prec, $flags) = (@_, 0);
2319 my $left = $op->first;
2320 my $right = $op->last;
2322 if ($op->flags & OPf_STACKED && $flags & ASSIGN) {
2326 if ($flags & SWAP_CHILDREN) {
2327 ($left, $right) = ($right, $left);
2329 $left = $self->deparse_binop_left($op, $left, $prec);
2330 $left = "($left)" if $flags & LIST_CONTEXT
2331 && $left !~ /^(my|our|local|)[\@\(]/;
2332 $right = $self->deparse_binop_right($op, $right, $prec);
2333 return $self->maybe_parens("$left $opname$eq $right", $cx, $prec);
2336 sub pp_add { maybe_targmy(@_, \&binop, "+", 18, ASSIGN) }
2337 sub pp_multiply { maybe_targmy(@_, \&binop, "*", 19, ASSIGN) }
2338 sub pp_subtract { maybe_targmy(@_, \&binop, "-",18, ASSIGN) }
2339 sub pp_divide { maybe_targmy(@_, \&binop, "/", 19, ASSIGN) }
2340 sub pp_modulo { maybe_targmy(@_, \&binop, "%", 19, ASSIGN) }
2341 sub pp_i_add { maybe_targmy(@_, \&binop, "+", 18, ASSIGN) }
2342 sub pp_i_multiply { maybe_targmy(@_, \&binop, "*", 19, ASSIGN) }
2343 sub pp_i_subtract { maybe_targmy(@_, \&binop, "-", 18, ASSIGN) }
2344 sub pp_i_divide { maybe_targmy(@_, \&binop, "/", 19, ASSIGN) }
2345 sub pp_i_modulo { maybe_targmy(@_, \&binop, "%", 19, ASSIGN) }
2346 sub pp_pow { maybe_targmy(@_, \&binop, "**", 22, ASSIGN) }
2348 sub pp_left_shift { maybe_targmy(@_, \&binop, "<<", 17, ASSIGN) }
2349 sub pp_right_shift { maybe_targmy(@_, \&binop, ">>", 17, ASSIGN) }
2350 sub pp_bit_and { maybe_targmy(@_, \&binop, "&", 13, ASSIGN) }
2351 sub pp_bit_or { maybe_targmy(@_, \&binop, "|", 12, ASSIGN) }
2352 sub pp_bit_xor { maybe_targmy(@_, \&binop, "^", 12, ASSIGN) }
2354 sub pp_eq { binop(@_, "==", 14) }
2355 sub pp_ne { binop(@_, "!=", 14) }
2356 sub pp_lt { binop(@_, "<", 15) }
2357 sub pp_gt { binop(@_, ">", 15) }
2358 sub pp_ge { binop(@_, ">=", 15) }
2359 sub pp_le { binop(@_, "<=", 15) }
2360 sub pp_ncmp { binop(@_, "<=>", 14) }
2361 sub pp_i_eq { binop(@_, "==", 14) }
2362 sub pp_i_ne { binop(@_, "!=", 14) }
2363 sub pp_i_lt { binop(@_, "<", 15) }
2364 sub pp_i_gt { binop(@_, ">", 15) }
2365 sub pp_i_ge { binop(@_, ">=", 15) }
2366 sub pp_i_le { binop(@_, "<=", 15) }
2367 sub pp_i_ncmp { binop(@_, "<=>", 14) }
2369 sub pp_seq { binop(@_, "eq", 14) }
2370 sub pp_sne { binop(@_, "ne", 14) }
2371 sub pp_slt { binop(@_, "lt", 15) }
2372 sub pp_sgt { binop(@_, "gt", 15) }
2373 sub pp_sge { binop(@_, "ge", 15) }
2374 sub pp_sle { binop(@_, "le", 15) }
2375 sub pp_scmp { binop(@_, "cmp", 14) }
2377 sub pp_sassign { binop(@_, "=", 7, SWAP_CHILDREN) }
2378 sub pp_aassign { binop(@_, "=", 7, SWAP_CHILDREN | LIST_CONTEXT) }
2381 my ($self, $op, $cx) = @_;
2382 if ($op->flags & OPf_SPECIAL) {
2383 return $self->deparse($op->last, $cx);
2386 binop(@_, "~~", 14);
2390 # '.' is special because concats-of-concats are optimized to save copying
2391 # by making all but the first concat stacked. The effect is as if the
2392 # programmer had written '($a . $b) .= $c', except legal.
2393 sub pp_concat { maybe_targmy(@_, \&real_concat) }
2397 my $left = $op->first;
2398 my $right = $op->last;
2401 if ($op->flags & OPf_STACKED and $op->first->name ne "concat") {
2405 $left = $self->deparse_binop_left($op, $left, $prec);
2406 $right = $self->deparse_binop_right($op, $right, $prec);
2407 return $self->maybe_parens("$left .$eq $right", $cx, $prec);
2410 # 'x' is weird when the left arg is a list
2414 my $left = $op->first;
2415 my $right = $op->last;
2418 if ($op->flags & OPf_STACKED) {
2422 if (null($right)) { # list repeat; count is inside left-side ex-list
2423 my $kid = $left->first->sibling; # skip pushmark
2425 for (; !null($kid->sibling); $kid = $kid->sibling) {
2426 push @exprs, $self->deparse($kid, 6);
2429 $left = "(" . join(", ", @exprs). ")";
2431 $left = $self->deparse_binop_left($op, $left, $prec);
2433 $right = $self->deparse_binop_right($op, $right, $prec);
2434 return $self->maybe_parens("$left x$eq $right", $cx, $prec);
2439 my ($op, $cx, $type) = @_;
2440 my $left = $op->first;
2441 my $right = $left->sibling;
2442 $left = $self->deparse($left, 9);
2443 $right = $self->deparse($right, 9);
2444 return $self->maybe_parens("$left $type $right", $cx, 9);
2450 my $flip = $op->first;
2451 my $type = ($flip->flags & OPf_SPECIAL) ? "..." : "..";
2452 return $self->range($flip->first, $cx, $type);
2455 # one-line while/until is handled in pp_leave
2459 my ($op, $cx, $lowop, $lowprec, $highop, $highprec, $blockname) = @_;
2460 my $left = $op->first;
2461 my $right = $op->first->sibling;
2462 if ($cx < 1 and is_scope($right) and $blockname
2463 and $self->{'expand'} < 7)
2465 $left = $self->deparse($left, 1);
2466 $right = $self->deparse($right, 0);
2467 return "$blockname ($left) {\n\t$right\n\b}\cK";
2468 } elsif ($cx < 1 and $blockname and not $self->{'parens'}
2469 and $self->{'expand'} < 7) { # $b if $a
2470 $right = $self->deparse($right, 1);
2471 $left = $self->deparse($left, 1);
2472 return "$right $blockname $left";
2473 } elsif ($cx > $lowprec and $highop) { # $a && $b
2474 $left = $self->deparse_binop_left($op, $left, $highprec);
2475 $right = $self->deparse_binop_right($op, $right, $highprec);
2476 return $self->maybe_parens("$left $highop $right", $cx, $highprec);
2477 } else { # $a and $b
2478 $left = $self->deparse_binop_left($op, $left, $lowprec);
2479 $right = $self->deparse_binop_right($op, $right, $lowprec);
2480 return $self->maybe_parens("$left $lowop $right", $cx, $lowprec);
2484 sub pp_and { logop(@_, "and", 3, "&&", 11, "if") }
2485 sub pp_or { logop(@_, "or", 2, "||", 10, "unless") }
2486 sub pp_dor { logop(@_, "//", 10) }
2488 # xor is syntactically a logop, but it's really a binop (contrary to
2489 # old versions of opcode.pl). Syntax is what matters here.
2490 sub pp_xor { logop(@_, "xor", 2, "", 0, "") }
2494 my ($op, $cx, $opname) = @_;
2495 my $left = $op->first;
2496 my $right = $op->first->sibling->first; # skip sassign
2497 $left = $self->deparse($left, 7);
2498 $right = $self->deparse($right, 7);
2499 return $self->maybe_parens("$left $opname $right", $cx, 7);
2502 sub pp_andassign { logassignop(@_, "&&=") }
2503 sub pp_orassign { logassignop(@_, "||=") }
2504 sub pp_dorassign { logassignop(@_, "//=") }
2506 sub rv2gv_or_string {
2508 if ($op->name eq "gv") { # could be open("open") or open("###")
2510 $self->stash_variable_name(undef,$self->gv_or_padgv($op));
2511 $quoted ? $name : "*$name";
2514 $self->deparse($op, 6);
2520 my($op, $cx, $name, $kid, $nollafr) = @_;
2522 my $parens = ($cx >= 5) || $self->{'parens'};
2523 $kid ||= $op->first->sibling;
2524 # If there are no arguments, add final parentheses (or parenthesize the
2525 # whole thing if the llafr does not apply) to account for cases like
2526 # (return)+1 or setpgrp()+1. When the llafr does not apply, we use a
2527 # precedence of 6 (< comma), as "return, 1" does not need parentheses.
2530 ? $self->maybe_parens($self->keyword($name), $cx, 7)
2531 : $self->keyword($name) . '()' x (7 < $cx);
2534 $name = "socketpair" if $name eq "sockpair";
2535 my $fullname = $self->keyword($name);
2536 my $proto = prototype("CORE::$name");
2538 && $proto =~ /^;?\*/
2539 && $kid->name eq "rv2gv" && !($kid->private & OPpLVAL_INTRO)) {
2540 $first = $self->rv2gv_or_string($kid->first);
2543 $first = $self->deparse($kid, 6);
2545 if ($name eq "chmod" && $first =~ /^\d+$/) {
2546 $first = sprintf("%#o", $first);
2549 if not $parens and not $nollafr and substr($first, 0, 1) eq "(";
2550 push @exprs, $first;
2551 $kid = $kid->sibling;
2552 if (defined $proto && $proto =~ /^\*\*/ && $kid->name eq "rv2gv"
2553 && !($kid->private & OPpLVAL_INTRO)) {
2554 push @exprs, $first = $self->rv2gv_or_string($kid->first);
2555 $kid = $kid->sibling;
2557 for (; !null($kid); $kid = $kid->sibling) {
2558 push @exprs, $self->deparse($kid, 6);
2560 if ($name eq "reverse" && ($op->private & OPpREVERSE_INPLACE)) {
2561 return "$exprs[0] = $fullname"
2562 . ($parens ? "($exprs[0])" : " $exprs[0]");
2564 if ($parens && $nollafr) {
2565 return "($fullname " . join(", ", @exprs) . ")";
2567 return "$fullname(" . join(", ", @exprs) . ")";
2569 return "$fullname " . join(", ", @exprs);
2573 sub pp_bless { listop(@_, "bless") }
2574 sub pp_atan2 { maybe_targmy(@_, \&listop, "atan2") }
2576 my ($self,$op,$cx) = @_;
2577 if ($op->private & OPpSUBSTR_REPL_FIRST) {
2579 listop($self, $op, 7, "substr", $op->first->sibling->sibling)
2581 . $self->deparse($op->first->sibling, 7);
2583 maybe_local(@_, listop(@_, "substr"))
2585 sub pp_vec { maybe_local(@_, listop(@_, "vec")) }
2586 sub pp_index { maybe_targmy(@_, \&listop, "index") }
2587 sub pp_rindex { maybe_targmy(@_, \&listop, "rindex") }
2588 sub pp_sprintf { maybe_targmy(@_, \&listop, "sprintf") }
2589 sub pp_formline { listop(@_, "formline") } # see also deparse_format
2590 sub pp_crypt { maybe_targmy(@_, \&listop, "crypt") }
2591 sub pp_unpack { listop(@_, "unpack") }
2592 sub pp_pack { listop(@_, "pack") }
2593 sub pp_join { maybe_targmy(@_, \&listop, "join") }
2594 sub pp_splice { listop(@_, "splice") }
2595 sub pp_push { maybe_targmy(@_, \&listop, "push") }
2596 sub pp_unshift { maybe_targmy(@_, \&listop, "unshift") }
2597 sub pp_reverse { listop(@_, "reverse") }
2598 sub pp_warn { listop(@_, "warn") }
2599 sub pp_die { listop(@_, "die") }
2600 sub pp_return { listop(@_, "return", undef, 1) } # llafr does not apply
2601 sub pp_open { listop(@_, "open") }
2602 sub pp_pipe_op { listop(@_, "pipe") }
2603 sub pp_tie { listop(@_, "tie") }
2604 sub pp_binmode { listop(@_, "binmode") }
2605 sub pp_dbmopen { listop(@_, "dbmopen") }
2606 sub pp_sselect { listop(@_, "select") }
2607 sub pp_select { listop(@_, "select") }
2608 sub pp_read { listop(@_, "read") }
2609 sub pp_sysopen { listop(@_, "sysopen") }
2610 sub pp_sysseek { listop(@_, "sysseek") }
2611 sub pp_sysread { listop(@_, "sysread") }
2612 sub pp_syswrite { listop(@_, "syswrite") }
2613 sub pp_send { listop(@_, "send") }
2614 sub pp_recv { listop(@_, "recv") }
2615 sub pp_seek { listop(@_, "seek") }
2616 sub pp_fcntl { listop(@_, "fcntl") }
2617 sub pp_ioctl { listop(@_, "ioctl") }
2618 sub pp_flock { maybe_targmy(@_, \&listop, "flock") }
2619 sub pp_socket { listop(@_, "socket") }
2620 sub pp_sockpair { listop(@_, "sockpair") }
2621 sub pp_bind { listop(@_, "bind") }
2622 sub pp_connect { listop(@_, "connect") }
2623 sub pp_listen { listop(@_, "listen") }
2624 sub pp_accept { listop(@_, "accept") }
2625 sub pp_shutdown { listop(@_, "shutdown") }
2626 sub pp_gsockopt { listop(@_, "getsockopt") }
2627 sub pp_ssockopt { listop(@_, "setsockopt") }
2628 sub pp_chown { maybe_targmy(@_, \&listop, "chown") }
2629 sub pp_unlink { maybe_targmy(@_, \&listop, "unlink") }
2630 sub pp_chmod { maybe_targmy(@_, \&listop, "chmod") }
2631 sub pp_utime { maybe_targmy(@_, \&listop, "utime") }
2632 sub pp_rename { maybe_targmy(@_, \&listop, "rename") }
2633 sub pp_link { maybe_targmy(@_, \&listop, "link") }
2634 sub pp_symlink { maybe_targmy(@_, \&listop, "symlink") }
2635 sub pp_mkdir { maybe_targmy(@_, \&listop, "mkdir") }
2636 sub pp_open_dir { listop(@_, "opendir") }
2637 sub pp_seekdir { listop(@_, "seekdir") }
2638 sub pp_waitpid { maybe_targmy(@_, \&listop, "waitpid") }
2639 sub pp_system { maybe_targmy(@_, \&listop, "system") }
2640 sub pp_exec { maybe_targmy(@_, \&listop, "exec") }
2641 sub pp_kill { maybe_targmy(@_, \&listop, "kill") }
2642 sub pp_setpgrp { maybe_targmy(@_, \&listop, "setpgrp") }
2643 sub pp_getpriority { maybe_targmy(@_, \&listop, "getpriority") }
2644 sub pp_setpriority { maybe_targmy(@_, \&listop, "setpriority") }
2645 sub pp_shmget { listop(@_, "shmget") }
2646 sub pp_shmctl { listop(@_, "shmctl") }
2647 sub pp_shmread { listop(@_, "shmread") }
2648 sub pp_shmwrite { listop(@_, "shmwrite") }
2649 sub pp_msgget { listop(@_, "msgget") }
2650 sub pp_msgctl { listop(@_, "msgctl") }
2651 sub pp_msgsnd { listop(@_, "msgsnd") }
2652 sub pp_msgrcv { listop(@_, "msgrcv") }
2653 sub pp_semget { listop(@_, "semget") }
2654 sub pp_semctl { listop(@_, "semctl") }
2655 sub pp_semop { listop(@_, "semop") }
2656 sub pp_ghbyaddr { listop(@_, "gethostbyaddr") }
2657 sub pp_gnbyaddr { listop(@_, "getnetbyaddr") }
2658 sub pp_gpbynumber { listop(@_, "getprotobynumber") }
2659 sub pp_gsbyname { listop(@_, "getservbyname") }
2660 sub pp_gsbyport { listop(@_, "getservbyport") }
2661 sub pp_syscall { listop(@_, "syscall") }
2666 my $text = $self->dq($op->first->sibling); # skip pushmark
2668 $op->flags & OPf_SPECIAL ? 'glob' : $self->keyword('glob');
2669 if ($text =~ /^\$?(\w|::|\`)+$/ # could look like a readline
2670 or $keyword =~ /^CORE::/
2671 or $text =~ /[<>]/) {
2672 return "$keyword(" . single_delim('qq', '"', $text) . ')';
2674 return '<' . $text . '>';
2678 # Truncate is special because OPf_SPECIAL makes a bareword first arg
2679 # be a filehandle. This could probably be better fixed in the core
2680 # by moving the GV lookup into ck_truc.
2686 my $parens = ($cx >= 5) || $self->{'parens'};
2687 my $kid = $op->first->sibling;
2689 if ($op->flags & OPf_SPECIAL) {
2690 # $kid is an OP_CONST
2691 $fh = $self->const_sv($kid)->PV;
2693 $fh = $self->deparse($kid, 6);
2694 $fh = "+$fh" if not $parens and substr($fh, 0, 1) eq "(";
2696 my $len = $self->deparse($kid->sibling, 6);
2697 my $name = $self->keyword('truncate');
2699 return "$name($fh, $len)";
2701 return "$name $fh, $len";
2707 my($op, $cx, $name) = @_;
2709 my $firstkid = my $kid = $op->first->sibling;
2711 if ($op->flags & OPf_STACKED) {
2713 $indir = $indir->first; # skip rv2gv
2714 if (is_scope($indir)) {
2715 $indir = "{" . $self->deparse($indir, 0) . "}";
2716 $indir = "{;}" if $indir eq "{}";
2717 } elsif ($indir->name eq "const" && $indir->private & OPpCONST_BARE) {
2718 $indir = $self->const_sv($indir)->PV;
2720 $indir = $self->deparse($indir, 24);
2722 $indir = $indir . " ";
2723 $kid = $kid->sibling;
2725 if ($name eq "sort" && $op->private & (OPpSORT_NUMERIC | OPpSORT_INTEGER)) {
2726 $indir = ($op->private & OPpSORT_DESCEND) ? '{$b <=> $a} '
2729 elsif ($name eq "sort" && $op->private & OPpSORT_DESCEND) {
2730 $indir = '{$b cmp $a} ';
2732 for (; !null($kid); $kid = $kid->sibling) {
2733 $expr = $self->deparse($kid, !$indir && $kid == $firstkid && $name eq "sort" && $firstkid->name eq "entersub" ? 16 : 6);
2737 if ($name eq "sort" && $op->private & OPpSORT_REVERSE) {
2738 $name2 = $self->keyword('reverse') . ' ' . $self->keyword('sort');
2740 else { $name2 = $self->keyword($name) }
2741 if ($name eq "sort" && ($op->private & OPpSORT_INPLACE)) {
2742 return "$exprs[0] = $name2 $indir $exprs[0]";
2745 my $args = $indir . join(", ", @exprs);
2746 if ($indir ne "" && $name eq "sort") {
2747 # We don't want to say "sort(f 1, 2, 3)", since perl -w will
2748 # give bareword warnings in that case. Therefore if context
2749 # requires, we'll put parens around the outside "(sort f 1, 2,
2750 # 3)". Unfortunately, we'll currently think the parens are
2751 # necessary more often that they really are, because we don't
2752 # distinguish which side of an assignment we're on.
2754 return "($name2 $args)";
2756 return "$name2 $args";
2759 !$indir && $name eq "sort"
2760 && $op->first->sibling->name eq 'entersub'
2762 # We cannot say sort foo(bar), as foo will be interpreted as a
2763 # comparison routine. We have to say sort(...) in that case.
2764 return "$name2($args)";
2766 return $self->maybe_parens_func($name2, $args, $cx, 5);
2771 sub pp_prtf { indirop(@_, "printf") }
2772 sub pp_print { indirop(@_, "print") }
2773 sub pp_say { indirop(@_, "say") }
2774 sub pp_sort { indirop(@_, "sort") }
2778 my($op, $cx, $name) = @_;
2780 my $kid = $op->first; # this is the (map|grep)start
2781 $kid = $kid->first->sibling; # skip a pushmark
2782 my $code = $kid->first; # skip a null
2783 if (is_scope $code) {
2784 $code = "{" . $self->deparse($code, 0) . "} ";
2786 $code = $self->deparse($code, 24) . ", ";
2788 $kid = $kid->sibling;
2789 for (; !null($kid); $kid = $kid->sibling) {
2790 $expr = $self->deparse($kid, 6);
2791 push @exprs, $expr if defined $expr;
2793 return $self->maybe_parens_func($name, $code . join(", ", @exprs), $cx, 5);
2796 sub pp_mapwhile { mapop(@_, "map") }
2797 sub pp_grepwhile { mapop(@_, "grep") }
2798 sub pp_mapstart { baseop(@_, "map") }
2799 sub pp_grepstart { baseop(@_, "grep") }
2805 my $kid = $op->first->sibling; # skip pushmark
2806 return '' if class($kid) eq 'NULL';
2808 my $local = "either"; # could be local(...), my(...), state(...) or our(...)
2809 for ($lop = $kid; !null($lop); $lop = $lop->sibling) {
2810 # This assumes that no other private flags equal 128, and that
2811 # OPs that store things other than flags in their op_private,
2812 # like OP_AELEMFAST, won't be immediate children of a list.
2814 # OP_ENTERSUB can break this logic, so check for it.
2815 # I suspect that open and exit can too.
2817 if (!($lop->private & (OPpLVAL_INTRO|OPpOUR_INTRO)
2818 or $lop->name eq "undef")
2819 or $lop->name eq "entersub"
2820 or $lop->name eq "exit"
2821 or $lop->name eq "open")
2823 $local = ""; # or not
2826 if ($lop->name =~ /^pad[ash]v$/) {
2827 if ($lop->private & OPpPAD_STATE) { # state()
2828 ($local = "", last) if $local =~ /^(?:local|our|my)$/;
2831 ($local = "", last) if $local =~ /^(?:local|our|state)$/;
2834 } elsif ($lop->name =~ /^(gv|rv2)[ash]v$/
2835 && $lop->private & OPpOUR_INTRO
2836 or $lop->name eq "null" && $lop->first->name eq "gvsv"
2837 && $lop->first->private & OPpOUR_INTRO) { # our()
2838 ($local = "", last) if $local =~ /^(?:my|local|state)$/;
2840 } elsif ($lop->name ne "undef"
2841 # specifically avoid the "reverse sort" optimisation,
2842 # where "reverse" is nullified
2843 && !($lop->name eq 'sort' && ($lop->flags & OPpSORT_REVERSE)))
2846 ($local = "", last) if $local =~ /^(?:my|our|state)$/;
2850 $local = "" if $local eq "either"; # no point if it's all undefs
2851 return $self->deparse($kid, $cx) if null $kid->sibling and not $local;
2852 for (; !null($kid); $kid = $kid->sibling) {
2854 if (class($kid) eq "UNOP" and $kid->first->name eq "gvsv") {
2859 $self->{'avoid_local'}{$$lop}++;
2860 $expr = $self->deparse($kid, 6);
2861 delete $self->{'avoid_local'}{$$lop};
2863 $expr = $self->deparse($kid, 6);
2868 return "$local(" . join(", ", @exprs) . ")";
2870 return $self->maybe_parens( join(", ", @exprs), $cx, 6);
2874 sub is_ifelse_cont {
2876 return ($op->name eq "null" and class($op) eq "UNOP"
2877 and $op->first->name =~ /^(and|cond_expr)$/
2878 and is_scope($op->first->first->sibling));
2884 my $cond = $op->first;
2885 my $true = $cond->sibling;
2886 my $false = $true->sibling;
2887 my $cuddle = $self->{'cuddle'};
2888 unless ($cx < 1 and (is_scope($true) and $true->name ne "null") and
2889 (is_scope($false) || is_ifelse_cont($false))
2890 and $self->{'expand'} < 7) {
2891 $cond = $self->deparse($cond, 8);
2892 $true = $self->deparse($true, 6);
2893 $false = $self->deparse($false, 8);
2894 return $self->maybe_parens("$cond ? $true : $false", $cx, 8);
2897 $cond = $self->deparse($cond, 1);
2898 $true = $self->deparse($true, 0);
2899 my $head = "if ($cond) {\n\t$true\n\b}";
2901 while (!null($false) and is_ifelse_cont($false)) {
2902 my $newop = $false->first;
2903 my $newcond = $newop->first;
2904 my $newtrue = $newcond->sibling;
2905 $false = $newtrue->sibling; # last in chain is OP_AND => no else
2906 if ($newcond->name eq "lineseq")
2908 # lineseq to ensure correct line numbers in elsif()
2909 # Bug #37302 fixed by change #33710.
2910 $newcond = $newcond->first->sibling;
2912 $newcond = $self->deparse($newcond, 1);
2913 $newtrue = $self->deparse($newtrue, 0);
2914 push @elsifs, "elsif ($newcond) {\n\t$newtrue\n\b}";
2916 if (!null($false)) {
2917 $false = $cuddle . "else {\n\t" .
2918 $self->deparse($false, 0) . "\n\b}\cK";
2922 return $head . join($cuddle, "", @elsifs) . $false;
2926 my ($self, $op, $cx) = @_;
2927 my $cond = $op->first;
2928 my $true = $cond->sibling;
2930 return $self->deparse($true, $cx);
2935 my($op, $cx, $init) = @_;
2936 my $enter = $op->first;
2937 my $kid = $enter->sibling;
2938 local(@$self{qw'curstash warnings hints hinthash'})
2939 = @$self{qw'curstash warnings hints hinthash'};
2944 if ($kid->name eq "lineseq") { # bare or infinite loop
2945 if ($kid->last->name eq "unstack") { # infinite
2946 $head = "while (1) "; # Can't use for(;;) if there's a continue
2952 } elsif ($enter->name eq "enteriter") { # foreach
2953 my $ary = $enter->first->sibling; # first was pushmark
2954 my $var = $ary->sibling;
2955 if ($ary->name eq 'null' and $enter->private & OPpITER_REVERSED) {
2956 # "reverse" was optimised away
2957 $ary = listop($self, $ary->first->sibling, 1, 'reverse');
2958 } elsif ($enter->flags & OPf_STACKED
2959 and not null $ary->first->sibling->sibling)
2961 $ary = $self->deparse($ary->first->sibling, 9) . " .. " .
2962 $self->deparse($ary->first->sibling->sibling, 9);
2964 $ary = $self->deparse($ary, 1);
2967 if (($enter->flags & OPf_SPECIAL) && ($] < 5.009)) {
2968 # thread special var, under 5005threads
2969 $var = $self->pp_threadsv($enter, 1);
2970 } else { # regular my() variable
2971 $var = $self->pp_padsv($enter, 1);
2973 } elsif ($var->name eq "rv2gv") {
2974 $var = $self->pp_rv2sv($var, 1);
2975 if ($enter->private & OPpOUR_INTRO) {
2976 # our declarations don't have package names
2977 $var =~ s/^(.).*::/$1/;
2980 } elsif ($var->name eq "gv") {
2981 $var = "\$" . $self->deparse($var, 1);
2983 $body = $kid->first->first->sibling; # skip OP_AND and OP_ITER
2984 if (!is_state $body->first and $body->first->name !~ /^(?:stub|leave|scope)$/) {
2985 confess unless $var eq '$_';
2986 $body = $body->first;
2987 return $self->deparse($body, 2) . " foreach ($ary)";
2989 $head = "foreach $var ($ary) ";
2990 } elsif ($kid->name eq "null") { # while/until
2992 my $name = {"and" => "while", "or" => "until"}->{$kid->name};
2993 $cond = $self->deparse($kid->first, 1);
2994 $head = "$name ($cond) ";
2995 $body = $kid->first->sibling;
2996 } elsif ($kid->name eq "stub") { # bare and empty
2997 return "{;}"; # {} could be a hashref
2999 # If there isn't a continue block, then the next pointer for the loop
3000 # will point to the unstack, which is kid's last child, except
3001 # in a bare loop, when it will point to the leaveloop. When neither of
3002 # these conditions hold, then the second-to-last child is the continue
3003 # block (or the last in a bare loop).
3004 my $cont_start = $enter->nextop;
3006 if ($$cont_start != $$op && ${$cont_start} != ${$body->last}) {
3008 $cont = $body->last;
3010 $cont = $body->first;
3011 while (!null($cont->sibling->sibling)) {
3012 $cont = $cont->sibling;
3015 my $state = $body->first;
3016 my $cuddle = $self->{'cuddle'};
3018 for (; $$state != $$cont; $state = $state->sibling) {
3019 push @states, $state;
3021 $body = $self->lineseq(undef, @states);
3022 if (defined $cond and not is_scope $cont and $self->{'expand'} < 3) {
3023 $head = "for ($init; $cond; " . $self->deparse($cont, 1) .") ";
3026 $cont = $cuddle . "continue {\n\t" .
3027 $self->deparse($cont, 0) . "\n\b}\cK";
3030 return "" if !defined $body;
3032 $head = "for ($init; $cond;) ";
3035 $body = $self->deparse($body, 0);
3037 $body =~ s/;?$/;\n/;
3039 return $head . "{\n\t" . $body . "\b}" . $cont;
3042 sub pp_leaveloop { shift->loop_common(@_, "") }
3047 my $init = $self->deparse($op, 1);
3048 my $s = $op->sibling;
3049 my $ll = $s->name eq "unstack" ? $s->sibling : $s->first->sibling;
3050 return $self->loop_common($ll, $cx, $init);
3055 return "eval {\n\t" . $self->pp_leave(@_) . "\n\b}";
3058 BEGIN { for (qw[ const stringify rv2sv list glob ]) {
3059 eval "sub OP_\U$_ () { " . opnumber($_) . "}"
3065 if (class($op) eq "OP") {
3067 return $self->{'ex_const'} if $op->targ == OP_CONST;
3068 } elsif ($op->first->name eq "pushmark") {
3069 return $self->pp_list($op, $cx);
3070 } elsif ($op->first->name eq "enter") {
3071 return $self->pp_leave($op, $cx);
3072 } elsif ($op->first->name eq "leave") {
3073 return $self->pp_leave($op->first, $cx);
3074 } elsif ($op->first->name eq "scope") {
3075 return $self->pp_scope($op->first, $cx);
3076 } elsif ($op->targ == OP_STRINGIFY) {
3077 return $self->dquote($op, $cx);
3078 } elsif ($op->targ == OP_GLOB) {
3079 return $self->pp_glob(
3080 $op->first # entersub
3086 } elsif (!null($op->first->sibling) and
3087 $op->first->sibling->name eq "readline" and
3088 $op->first->sibling->flags & OPf_STACKED) {
3089 return $self->maybe_parens($self->deparse($op->first, 7) . " = "
3090 . $self->deparse($op->first->sibling, 7),
3092 } elsif (!null($op->first->sibling) and
3093 $op->first->sibling->name eq "trans" and
3094 $op->first->sibling->flags & OPf_STACKED) {
3095 return $self->maybe_parens($self->deparse($op->first, 20) . " =~ "
3096 . $self->deparse($op->first->sibling, 20),
3098 } elsif ($op->flags & OPf_SPECIAL && $cx < 1 && !$op->targ) {
3099 return "do {\n\t". $self->deparse($op->first, $cx) ."\n\b};";
3100 } elsif (!null($op->first->sibling) and
3101 $op->first->sibling->name eq "null" and
3102 class($op->first->sibling) eq "UNOP" and
3103 $op->first->sibling->first->flags & OPf_STACKED and
3104 $op->first->sibling->first->name eq "rcatline") {
3105 return $self->maybe_parens($self->deparse($op->first, 18) . " .= "
3106 . $self->deparse($op->first->sibling, 18),
3109 return $self->deparse($op->first, $cx);
3116 return $self->padname_sv($targ)->PVX;
3122 return substr($self->padname($op->targ), 1); # skip $/@/%
3128 return $self->maybe_my($op, $cx, $self->padname($op->targ));
3131 sub pp_padav { pp_padsv(@_) }
3132 sub pp_padhv { pp_padsv(@_) }
3134 my @threadsv_names = B::threadsv_names;
3138 return $self->maybe_local($op, $cx, "\$" . $threadsv_names[$op->targ]);
3144 if (class($op) eq "PADOP") {
3145 return $self->padval($op->padix);
3146 } else { # class($op) eq "SVOP"
3154 my $gv = $self->gv_or_padgv($op);
3155 return $self->maybe_local($op, $cx, $self->stash_variable("\$",
3156 $self->gv_name($gv), $cx));
3162 my $gv = $self->gv_or_padgv($op);
3163 return $self->gv_name($gv);
3166 sub pp_aelemfast_lex {
3169 my $name = $self->padname($op->targ);
3171 return $name . "[" . ($op->private + $self->{'arybase'}) . "]";
3177 # optimised PADAV, pre 5.15
3178 return $self->pp_aelemfast_lex(@_) if ($op->flags & OPf_SPECIAL);
3180 my $gv = $self->gv_or_padgv($op);
3181 my($name,$quoted) = $self->stash_variable_name('@',$gv);
3182 $name = $quoted ? "$name->" : '$' . $name;
3183 return $name . "[" . ($op->private + $self->{'arybase'}) . "]";
3188 my($op, $cx, $type) = @_;
3190 if (class($op) eq 'NULL' || !$op->can("first")) {
3191 carp("Unexpected op in pp_rv2x");
3194 my $kid = $op->first;
3195 if ($kid->name eq "gv") {
3196 return $self->stash_variable($type, $self->deparse($kid, 0), $cx);
3197 } elsif (is_scalar $kid) {
3198 my $str = $self->deparse($kid, 0);
3199 if ($str =~ /^\$([^\w\d])\z/) {
3200 # "$$+" isn't a legal way to write the scalar dereference
3201 # of $+, since the lexer can't tell you aren't trying to
3202 # do something like "$$ + 1" to get one more than your
3203 # PID. Either "${$+}" or "$${+}" are workable
3204 # disambiguations, but if the programmer did the former,
3205 # they'd be in the "else" clause below rather than here.
3206 # It's not clear if this should somehow be unified with
3207 # the code in dq and re_dq that also adds lexer
3208 # disambiguation braces.
3209 $str = '$' . "{$1}"; #'
3211 return $type . $str;
3213 return $type . "{" . $self->deparse($kid, 0) . "}";
3217 sub pp_rv2sv { maybe_local(@_, rv2x(@_, "\$")) }
3218 sub pp_rv2hv { maybe_local(@_, rv2x(@_, "%")) }
3219 sub pp_rv2gv { maybe_local(@_, rv2x(@_, "*")) }
3225 if ($op->first->name eq "padav") {
3226 return $self->maybe_local($op, $cx, '$#' . $self->padany($op->first));
3228 return $self->maybe_local($op, $cx,
3229 $self->rv2x($op->first, $cx, '$#'));
3233 # skip down to the old, ex-rv2cv
3235 my ($self, $op, $cx) = @_;
3236 if (!null($op->first) && $op->first->name eq 'null' &&
3237 $op->first->targ eq OP_LIST)
3239 return $self->rv2x($op->first->first->sibling, $cx, "&")
3242 return $self->rv2x($op, $cx, "")
3248 my($cx, @list) = @_;
3249 my @a = map $self->const($_, 6), @list;
3254 } elsif ( @a > 2 and !grep(!/^-?\d+$/, @a)) {
3255 # collapse (-1,0,1,2) into (-1..2)
3256 my ($s, $e) = @a[0,-1];
3258 return $self->maybe_parens("$s..$e", $cx, 9)
3259 unless grep $i++ != $_, @a;
3261 return $self->maybe_parens(join(", ", @a), $cx, 6);
3267 my $kid = $op->first;
3268 if ($kid->name eq "const") { # constant list
3269 my $av = $self->const_sv($kid);
3270 return $self->list_const($cx, $av->ARRAY);
3272 return $self->maybe_local($op, $cx, $self->rv2x($op, $cx, "\@"));
3276 sub is_subscriptable {
3278 if ($op->name =~ /^[ahg]elem/) {
3280 } elsif ($op->name eq "entersub") {
3281 my $kid = $op->first;
3282 return 0 unless null $kid->sibling;
3284 $kid = $kid->sibling until null $kid->sibling;
3285 return 0 if is_scope($kid);
3287 return 0 if $kid->name eq "gv";
3288 return 0 if is_scalar($kid);
3289 return is_subscriptable($kid);
3295 sub elem_or_slice_array_name
3298 my ($array, $left, $padname, $allow_arrow) = @_;
3300 if ($array->name eq $padname) {
3301 return $self->padany($array);
3302 } elsif (is_scope($array)) { # ${expr}[0]
3303 return "{" . $self->deparse($array, 0) . "}";
3304 } elsif ($array->name eq "gv") {
3305 ($array, my $quoted) =
3306 $self->stash_variable_name(
3307 $left eq '[' ? '@' : '%', $self->gv_or_padgv($array)
3309 if (!$allow_arrow && $quoted) {
3310 # This cannot happen.
3311 die "Invalid variable name $array for slice";
3313 return $quoted ? "$array->" : $array;
3314 } elsif (!$allow_arrow || is_scalar $array) { # $x[0], $$x[0], ...
3315 return $self->deparse($array, 24);
3321 sub elem_or_slice_single_index
3326 $idx = $self->deparse($idx, 1);
3328 # Outer parens in an array index will confuse perl
3329 # if we're interpolating in a regular expression, i.e.
3330 # /$x$foo[(-1)]/ is *not* the same as /$x$foo[-1]/
3332 # If $self->{parens}, then an initial '(' will
3333 # definitely be paired with a final ')'. If
3334 # !$self->{parens}, the misleading parens won't
3335 # have been added in the first place.
3337 # [You might think that we could get "(...)...(...)"
3338 # where the initial and final parens do not match
3339 # each other. But we can't, because the above would
3340 # only happen if there's an infix binop between the
3341 # two pairs of parens, and *that* means that the whole
3342 # expression would be parenthesized as well.]
3344 $idx =~ s/^\((.*)\)$/$1/ if $self->{'parens'};
3346 # Hash-element braces will autoquote a bareword inside themselves.
3347 # We need to make sure that C<$hash{warn()}> doesn't come out as
3348 # C<$hash{warn}>, which has a quite different meaning. Currently
3349 # B::Deparse will always quote strings, even if the string was a
3350 # bareword in the original (i.e. the OPpCONST_BARE flag is ignored
3351 # for constant strings.) So we can cheat slightly here - if we see
3352 # a bareword, we know that it is supposed to be a function call.
3354 $idx =~ s/^([A-Za-z_]\w*)$/$1()/;
3361 my ($op, $cx, $left, $right, $padname) = @_;
3362 my($array, $idx) = ($op->first, $op->first->sibling);
3364 $idx = $self->elem_or_slice_single_index($idx);
3366 unless ($array->name eq $padname) { # Maybe this has been fixed
3367 $array = $array->first; # skip rv2av (or ex-rv2av in _53+)
3369 if (my $array_name=$self->elem_or_slice_array_name
3370 ($array, $left, $padname, 1)) {
3371 return ($array_name =~ /->\z/ ? $array_name : "\$" . $array_name)
3372 . $left . $idx . $right;
3374 # $x[20][3]{hi} or expr->[20]
3375 my $arrow = is_subscriptable($array) ? "" : "->";
3376 return $self->deparse($array, 24) . $arrow . $left . $idx . $right;
3381 sub pp_aelem { maybe_local(@_, elem(@_, "[", "]", "padav")) }
3382 sub pp_helem { maybe_local(@_, elem(@_, "{", "}", "padhv")) }
3387 my($glob, $part) = ($op->first, $op->last);
3388 $glob = $glob->first; # skip rv2gv
3389 $glob = $glob->first if $glob->name eq "rv2gv"; # this one's a bug
3390 my $scope = is_scope($glob);
3391 $glob = $self->deparse($glob, 0);
3392 $part = $self->deparse($part, 1);
3393 return "*" . ($scope ? "{$glob}" : $glob) . "{$part}";
3398 my ($op, $cx, $left, $right, $regname, $padname) = @_;
3400 my(@elems, $kid, $array, $list);
3401 if (class($op) eq "LISTOP") {
3403 } else { # ex-hslice inside delete()
3404 for ($kid = $op->first; !null $kid->sibling; $kid = $kid->sibling) {}
3408 $array = $array->first
3409 if $array->name eq $regname or $array->name eq "null";
3410 $array = $self->elem_or_slice_array_name($array,$left,$padname,0);
3411 $kid = $op->first->sibling; # skip pushmark
3412 if ($kid->name eq "list") {
3413 $kid = $kid->first->sibling; # skip list, pushmark
3414 for (; !null $kid; $kid = $kid->sibling) {
3415 push @elems, $self->deparse($kid, 6);
3417 $list = join(", ", @elems);
3419 $list = $self->elem_or_slice_single_index($kid);
3421 return "\@" . $array . $left . $list . $right;
3424 sub pp_aslice { maybe_local(@_, slice(@_, "[", "]", "rv2av", "padav")) }
3425 sub pp_hslice { maybe_local(@_, slice(@_, "{", "}", "rv2hv", "padhv")) }
3430 my $idx = $op->first;
3431 my $list = $op->last;
3433 $list = $self->deparse($list, 1);
3434 $idx = $self->deparse($idx, 1);
3435 return "($list)" . "[$idx]";
3440 return ($op->flags & OPf_WANT) == OPf_WANT_SCALAR;
3445 return ($op->flags & OPf_WANT) == OPf_WANT_LIST;
3451 my $kid = $op->first->sibling; # skip pushmark
3452 my($meth, $obj, @exprs);
3453 if ($kid->name eq "list" and want_list $kid) {
3454 # When an indirect object isn't a bareword but the args are in
3455 # parens, the parens aren't part of the method syntax (the LLAFR
3456 # doesn't apply), but they make a list with OPf_PARENS set that
3457 # doesn't get flattened by the append_elem that adds the method,
3458 # making a (object, arg1, arg2, ...) list where the object
3459 # usually is. This can be distinguished from
3460 # '($obj, $arg1, $arg2)->meth()' (which is legal if $arg2 is an
3461 # object) because in the later the list is in scalar context
3462 # as the left side of -> always is, while in the former
3463 # the list is in list context as method arguments always are.
3464 # (Good thing there aren't method prototypes!)
3465 $meth = $kid->sibling;
3466 $kid = $kid->first->sibling; # skip pushmark
3468 $kid = $kid->sibling;
3469 for (; not null $kid; $kid = $kid->sibling) {
3474 $kid = $kid->sibling;
3475 for (; !null ($kid->sibling) && $kid->name!~/^method(?:_named)?\z/;
3476 $kid = $kid->sibling) {
3482 if ($meth->name eq "method_named") {
3483 $meth = $self->const_sv($meth)->PV;
3485 $meth = $meth->first;
3486 if ($meth->name eq "const") {
3487 # As of 5.005_58, this case is probably obsoleted by the
3488 # method_named case above
3489 $meth = $self->const_sv($meth)->PV; # needs to be bare
3493 return { method => $meth, variable_method => ref($meth),
3494 object => $obj, args => \@exprs },
3498 # compat function only
3501 my $info = $self->_method(@_);
3502 return $self->e_method( $self->_method(@_) );
3506 my ($self, $info, $cx) = @_;
3507 my $obj = $self->deparse($info->{object}, 24);
3509 my $meth = $info->{method};
3510 $meth = $self->deparse($meth, 1) if $info->{variable_method};
3511 my $args = join(", ", map { $self->deparse($_, 6) } @{$info->{args}} );
3512 if ($info->{object}->name eq 'scope' && want_list $info->{object}) {
3513 # method { $object }
3514 # This must be deparsed this way to preserve list context
3516 my $need_paren = $cx >= 6;
3517 return '(' x $need_paren
3518 . $meth . substr($obj,2) # chop off the "do"
3520 . ')' x $need_paren;
3522 my $kid = $obj . "->" . $meth;
3524 return $kid . "(" . $args . ")"; # parens mandatory
3530 # returns "&" if the prototype doesn't match the args,
3531 # or ("", $args_after_prototype_demunging) if it does.
3534 return "&" if $self->{'noproto'};
3535 my($proto, @args) = @_;
3539 # An unbackslashed @ or % gobbles up the rest of the args
3540 1 while $proto =~ s/(?<!\\)([@%])[^\]]+$/$1/;
3542 $proto =~ s/^(\\?[\$\@&%*_]|\\\[[\$\@&%*]+\]|;)//;
3545 return "&" if @args;
3546 } elsif ($chr eq ";") {
3548 } elsif ($chr eq "@" or $chr eq "%") {
3549 push @reals, map($self->deparse($_, 6), @args);
3554 if ($chr eq "\$" || $chr eq "_") {
3555 if (want_scalar $arg) {
3556 push @reals, $self->deparse($arg, 6);
3560 } elsif ($chr eq "&") {
3561 if ($arg->name =~ /^(s?refgen|undef)$/) {
3562 push @reals, $self->deparse($arg, 6);
3566 } elsif ($chr eq "*") {
3567 if ($arg->name =~ /^s?refgen$/
3568 and $arg->first->first->name eq "rv2gv")
3570 $real = $arg->first->first; # skip refgen, null
3571 if ($real->first->name eq "gv") {
3572 push @reals, $self->deparse($real, 6);
3574 push @reals, $self->deparse($real->first, 6);
3579 } elsif (substr($chr, 0, 1) eq "\\") {
3581 if ($arg->name =~ /^s?refgen$/ and
3582 !null($real = $arg->first) and
3583 ($chr =~ /\$/ && is_scalar($real->first)
3585 && class($real->first->sibling) ne 'NULL'
3586 && $real->first->sibling->name
3589 && class($real->first->sibling) ne 'NULL'
3590 && $real->first->sibling->name
3592 #or ($chr =~ /&/ # This doesn't work
3593 # && $real->first->name eq "rv2cv")
3595 && $real->first->name eq "rv2gv")))
3597 push @reals, $self->deparse($real, 6);
3604 return "&" if $proto and !$doneok; # too few args and no ';'
3605 return "&" if @args; # too many args
3606 return ("", join ", ", @reals);
3612 return $self->e_method($self->_method($op, $cx))
3613 unless null $op->first->sibling;
3617 if ($op->flags & OPf_SPECIAL && !($op->flags & OPf_MOD)) {
3619 } elsif ($op->private & OPpENTERSUB_AMPER) {
3623 $kid = $kid->first->sibling; # skip ex-list, pushmark
3624 for (; not null $kid->sibling; $kid = $kid->sibling) {
3629 if (is_scope($kid)) {
3631 $kid = "{" . $self->deparse($kid, 0) . "}";
3632 } elsif ($kid->first->name eq "gv") {
3633 my $gv = $self->gv_or_padgv($kid->first);
3634 if (class($gv->CV) ne "SPECIAL") {
3635 $proto = $gv->CV->PV if $gv->CV->FLAGS & SVf_POK;
3637 $simple = 1; # only calls of named functions can be prototyped
3638 $kid = $self->deparse($kid, 24);
3640 if ($kid eq 'main::') {
3642 } elsif ($kid !~ /^(?:\w|::)(?:[\w\d]|::(?!\z))*\z/) {
3643 $kid = single_delim("q", "'", $kid) . '->';
3646 } elsif (is_scalar ($kid->first) && $kid->first->name ne 'rv2cv') {
3648 $kid = $self->deparse($kid, 24);
3651 my $arrow = is_subscriptable($kid->first) ? "" : "->";
3652 $kid = $self->deparse($kid, 24) . $arrow;
3655 # Doesn't matter how many prototypes there are, if
3656 # they haven't happened yet!
3660 no warnings 'uninitialized';
3661 $declared = exists $self->{'subs_declared'}{$kid}
3663 defined &{ ${$self->{'curstash'}."::"}{$kid} }
3665 $self->{'subs_deparsed'}{$self->{'curstash'}."::".$kid}
3666 && defined prototype $self->{'curstash'}."::".$kid
3668 if (!$declared && defined($proto)) {
3669 # Avoid "too early to check prototype" warning
3670 ($amper, $proto) = ('&');
3675 if ($declared and defined $proto and not $amper) {
3676 ($amper, $args) = $self->check_proto($proto, @exprs);
3677 if ($amper eq "&") {
3678 $args = join(", ", map($self->deparse($_, 6), @exprs));
3681 $args = join(", ", map($self->deparse($_, 6), @exprs));
3683 if ($prefix or $amper) {
3684 if ($kid eq '&') { $kid = "{$kid}" } # &{&} cannot be written as &&
3685 if ($op->flags & OPf_STACKED) {
3686 return $prefix . $amper . $kid . "(" . $args . ")";
3688 return $prefix . $amper. $kid;
3691 # It's a syntax error to call CORE::GLOBAL::foo with a prefix,
3692 # so it must have been translated from a keyword call. Translate
3694 $kid =~ s/^CORE::GLOBAL:://;
3696 my $dproto = defined($proto) ? $proto : "undefined";
3698 return "$kid(" . $args . ")";
3699 } elsif ($dproto eq "") {
3701 } elsif ($dproto eq "\$" and is_scalar($exprs[0])) {
3702 # is_scalar is an excessively conservative test here:
3703 # really, we should be comparing to the precedence of the
3704 # top operator of $exprs[0] (ala unop()), but that would
3705 # take some major code restructuring to do right.
3706 return $self->maybe_parens_func($kid, $args, $cx, 16);
3707 } elsif ($dproto ne '$' and defined($proto) || $simple) { #'
3708 return $self->maybe_parens_func($kid, $args, $cx, 5);
3710 return "$kid(" . $args . ")";
3715 sub pp_enterwrite { unop(@_, "write") }
3717 # escape things that cause interpolation in double quotes,
3718 # but not character escapes
3721 $str =~ s/(^|\G|[^\\])((?:\\\\)*)([\$\@]|\\[uUlLQE])/$1$2\\$3/g;
3729 # Matches any string which is balanced with respect to {braces}
3740 # the same, but treat $|, $), $( and $ at the end of the string differently
3754 (\(\?\??\{$bal\}\)) # $4
3760 /defined($4) && length($4) ? "$1$2$4" : "$1$2\\$3"/xeg;
3765 # This is for regular expressions with the /x modifier
3766 # We have to leave comments unmangled.
3767 sub re_uninterp_extended {
3780 ( \(\?\??\{$bal\}\) # $4 (skip over (?{}) and (??{}) blocks)
3781 | \#[^\n]* # (skip over comments)
3788 /defined($4) && length($4) ? "$1$2$4" : "$1$2\\$3"/xeg;
3794 my %unctrl = # portable to to EBCDIC
3796 "\c@" => '\c@', # unused
3823 "\c[" => '\c[', # unused
3824 "\c\\" => '\c\\', # unused
3825 "\c]" => '\c]', # unused
3826 "\c_" => '\c_', # unused
3829 # character escapes, but not delimiters that might need to be escaped
3830 sub escape_str { # ASCII, UTF8
3832 $str =~ s/(.)/ord($1) > 255 ? sprintf("\\x{%x}", ord($1)) : $1/eg;
3834 # $str =~ s/\cH/\\b/g; # \b means something different in a regex
3840 $str =~ s/([\cA-\cZ])/$unctrl{$1}/ge;
3841 $str =~ s/([[:^print:]])/sprintf("\\%03o", ord($1))/ge;
3845 # For regexes with the /x modifier.
3846 # Leave whitespace unmangled.
3847 sub escape_extended_re {
3849 $str =~ s/(.)/ord($1) > 255 ? sprintf("\\x{%x}", ord($1)) : $1/eg;
3850 $str =~ s/([[:^print:]])/
3851 ($1 =~ y! \t\n!!) ? $1 : sprintf("\\%03o", ord($1))/ge;
3852 $str =~ s/\n/\n\f/g;
3856 # Don't do this for regexen
3859 $str =~ s/\\/\\\\/g;
3863 # Remove backslashes which precede literal control characters,
3864 # to avoid creating ambiguity when we escape the latter.
3868 # the insane complexity here is due to the behaviour of "\c\"
3869 $str =~ s/(^|[^\\]|\\c\\)(?<!\\c)\\(\\\\)*(?=[[:^print:]])/$1$2/g;
3873 sub balanced_delim {
3875 my @str = split //, $str;
3876 my($ar, $open, $close, $fail, $c, $cnt, $last_bs);
3877 for $ar (['[',']'], ['(',')'], ['<','>'], ['{','}']) {
3878 ($open, $close) = @$ar;
3879 $fail = 0; $cnt = 0; $last_bs = 0;
3882 $fail = 1 if $last_bs;
3884 } elsif ($c eq $close) {
3885 $fail = 1 if $last_bs;
3893 $last_bs = $c eq '\\';
3895 $fail = 1 if $cnt != 0;
3896 return ($open, "$open$str$close") if not $fail;
3902 my($q, $default, $str) = @_;
3903 return "$default$str$default" if $default and index($str, $default) == -1;
3905 (my $succeed, $str) = balanced_delim($str);
3906 return "$q$str" if $succeed;
3908 for my $delim ('/', '"', '#') {
3909 return "$q$delim" . $str . $delim if index($str, $delim) == -1;
3912 $str =~ s/$default/\\$default/g;
3913 return "$default$str$default";
3921 BEGIN { $max_prec = int(0.999 + 8*length(pack("F", 42))*log(2)/log(10)); }
3923 # Split a floating point number into an integer mantissa and a binary
3924 # exponent. Assumes you've already made sure the number isn't zero or
3925 # some weird infinity or NaN.
3929 if ($f == int($f)) {
3930 while ($f % 2 == 0) {
3935 while ($f != int($f)) {
3940 my $mantissa = sprintf("%.0f", $f);
3941 return ($mantissa, $exponent);
3947 if ($self->{'use_dumper'}) {
3948 return $self->const_dumper($sv, $cx);
3950 if (class($sv) eq "SPECIAL") {
3951 # sv_undef, sv_yes, sv_no
3952 return ('undef', '1', $self->maybe_parens("!1", $cx, 21))[$$sv-1];
3954 if (class($sv) eq "NULL") {
3957 # convert a version object into the "v1.2.3" string in its V magic
3958 if ($sv->FLAGS & SVs_RMG) {
3959 for (my $mg = $sv->MAGIC; $mg; $mg = $mg->MOREMAGIC) {
3960 return $mg->PTR if $mg->TYPE eq 'V';
3964 if ($sv->FLAGS & SVf_IOK) {
3965 my $str = $sv->int_value;
3966 $str = $self->maybe_parens($str, $cx, 21) if $str < 0;
3968 } elsif ($sv->FLAGS & SVf_NOK) {
3971 if (pack("F", $nv) eq pack("F", 0)) {
3976 return $self->maybe_parens("-.0", $cx, 21);
3978 } elsif (1/$nv == 0) {
3981 return $self->maybe_parens("9**9**9", $cx, 22);
3984 return $self->maybe_parens("-9**9**9", $cx, 21);
3986 } elsif ($nv != $nv) {
3988 if (pack("F", $nv) eq pack("F", sin(9**9**9))) {
3990 return "sin(9**9**9)";
3991 } elsif (pack("F", $nv) eq pack("F", -sin(9**9**9))) {
3993 return $self->maybe_parens("-sin(9**9**9)", $cx, 21);
3996 my $hex = unpack("h*", pack("F", $nv));
3997 return qq'unpack("F", pack("h*", "$hex"))';
4000 # first, try the default stringification
4003 # failing that, try using more precision
4004 $str = sprintf("%.${max_prec}g", $nv);
4005 # if (pack("F", $str) ne pack("F", $nv)) {
4007 # not representable in decimal with whatever sprintf()
4008 # and atof() Perl is using here.
4009 my($mant, $exp) = split_float($nv);
4010 return $self->maybe_parens("$mant * 2**$exp", $cx, 19);
4013 $str = $self->maybe_parens($str, $cx, 21) if $nv < 0;
4015 } elsif ($sv->FLAGS & SVf_ROK && $sv->can("RV")) {
4017 if (class($ref) eq "AV") {
4018 return "[" . $self->list_const(2, $ref->ARRAY) . "]";
4019 } elsif (class($ref) eq "HV") {
4020 my %hash = $ref->ARRAY;
4022 for my $k (sort keys %hash) {
4023 push @elts, "$k => " . $self->const($hash{$k}, 6);
4025 return "{" . join(", ", @elts) . "}";
4026 } elsif (class($ref) eq "CV") {
4028 if ($] > 5.0150051) {
4029 require overloading;
4030 unimport overloading;
4033 if ($] > 5.0150051 && $self->{curcv} &&
4034 $self->{curcv}->object_2svref == $ref->object_2svref) {
4035 return $self->keyword("__SUB__");
4037 return "sub " . $self->deparse_sub($ref);
4039 if ($ref->FLAGS & SVs_SMG) {
4040 for (my $mg = $ref->MAGIC; $mg; $mg = $mg->MOREMAGIC) {
4041 if ($mg->TYPE eq 'r') {
4042 my $re = re_uninterp(escape_str(re_unback($mg->precomp)));
4043 return single_delim("qr", "", $re);
4048 return $self->maybe_parens("\\" . $self->const($ref, 20), $cx, 20);
4049 } elsif ($sv->FLAGS & SVf_POK) {
4051 if ($str =~ /[[:^print:]]/) {
4052 return single_delim("qq", '"', uninterp escape_str unback $str);
4054 return single_delim("q", "'", unback $str);
4064 my $ref = $sv->object_2svref();
4065 my $dumper = Data::Dumper->new([$$ref], ['$v']);
4066 $dumper->Purity(1)->Terse(1)->Deparse(1)->Indent(0)->Useqq(1)->Sortkeys(1);
4067 my $str = $dumper->Dump();
4068 if ($str =~ /^\$v/) {
4069 return '${my ' . $str . ' \$v}';
4079 # the constant could be in the pad (under useithreads)
4080 $sv = $self->padval($op->targ) unless $$sv;
4087 if ($op->private & OPpCONST_ARYBASE) {
4090 # if ($op->private & OPpCONST_BARE) { # trouble with '=>' autoquoting
4091 # return $self->const_sv($op)->PV;
4093 my $sv = $self->const_sv($op);
4094 return $self->const($sv, $cx);
4100 my $type = $op->name;
4101 if ($type eq "const") {
4102 return '$[' if $op->private & OPpCONST_ARYBASE;
4103 return uninterp(escape_str(unback($self->const_sv($op)->as_string)));
4104 } elsif ($type eq "concat") {
4105 my $first = $self->dq($op->first);
4106 my $last = $self->dq($op->last);
4108 # Disambiguate "${foo}bar", "${foo}{bar}", "${foo}[1]", "$foo\::bar"
4109 ($last =~ /^[A-Z\\\^\[\]_?]/ &&
4110 $first =~ s/([\$@])\^$/${1}{^}/) # "${^}W" etc
4111 || ($last =~ /^[:'{\[\w_]/ && #'
4112 $first =~ s/([\$@])([A-Za-z_]\w*)$/${1}{$2}/);
4114 return $first . $last;
4115 } elsif ($type eq "uc") {
4116 return '\U' . $self->dq($op->first->sibling) . '\E';
4117 } elsif ($type eq "lc") {
4118 return '\L' . $self->dq($op->first->sibling) . '\E';
4119 } elsif ($type eq "ucfirst") {
4120 return '\u' . $self->dq($op->first->sibling);
4121 } elsif ($type eq "lcfirst") {
4122 return '\l' . $self->dq($op->first->sibling);
4123 } elsif ($type eq "quotemeta") {
4124 return '\Q' . $self->dq($op->first->sibling) . '\E';
4125 } elsif ($type eq "fc") {
4126 return '\F' . $self->dq($op->first->sibling) . '\E';
4127 } elsif ($type eq "join") {
4128 return $self->deparse($op->last, 26); # was join($", @ary)
4130 return $self->deparse($op, 26);
4137 # skip pushmark if it exists (readpipe() vs ``)
4138 my $child = $op->first->sibling->isa('B::NULL')
4139 ? $op->first : $op->first->sibling;
4140 if ($self->pure_string($child)) {
4141 return single_delim("qx", '`', $self->dq($child, 1));
4143 unop($self, @_, "readpipe");
4149 my $kid = $op->first->sibling; # skip ex-stringify, pushmark
4150 return $self->deparse($kid, $cx) if $self->{'unquote'};
4151 $self->maybe_targmy($kid, $cx,
4152 sub {single_delim("qq", '"', $self->dq($_[1]))});
4155 # OP_STRINGIFY is a listop, but it only ever has one arg
4156 sub pp_stringify { maybe_targmy(@_, \&dquote) }
4158 # tr/// and s/// (and tr[][], tr[]//, tr###, etc)
4159 # note that tr(from)/to/ is OK, but not tr/from/(to)
4161 my($from, $to) = @_;
4162 my($succeed, $delim);
4163 if ($from !~ m[/] and $to !~ m[/]) {
4164 return "/$from/$to/";
4165 } elsif (($succeed, $from) = balanced_delim($from) and $succeed) {
4166 if (($succeed, $to) = balanced_delim($to) and $succeed) {
4169 for $delim ('/', '"', '#') { # note no "'" -- s''' is special
4170 return "$from$delim$to$delim" if index($to, $delim) == -1;
4173 return "$from/$to/";
4176 for $delim ('/', '"', '#') { # note no '
4177 return "$delim$from$delim$to$delim"
4178 if index($to . $from, $delim) == -1;
4180 $from =~ s[/][\\/]g;
4182 return "/$from/$to/";
4186 # Only used by tr///, so backslashes hyphens
4189 if ($n == ord '\\') {
4191 } elsif ($n == ord "-") {
4193 } elsif ($n >= ord(' ') and $n <= ord('~')) {
4195 } elsif ($n == ord "\a") {
4197 } elsif ($n == ord "\b") {
4199 } elsif ($n == ord "\t") {
4201 } elsif ($n == ord "\n") {
4203 } elsif ($n == ord "\e") {
4205 } elsif ($n == ord "\f") {
4207 } elsif ($n == ord "\r") {
4209 } elsif ($n >= ord("\cA") and $n <= ord("\cZ")) {
4210 return '\\c' . chr(ord("@") + $n);
4212 # return '\x' . sprintf("%02x", $n);
4213 return '\\' . sprintf("%03o", $n);
4219 my($str, $c, $tr) = ("");
4220 for ($c = 0; $c < @chars; $c++) {
4223 if ($c <= $#chars - 2 and $chars[$c + 1] == $tr + 1 and
4224 $chars[$c + 2] == $tr + 2)
4226 for (; $c <= $#chars-1 and $chars[$c + 1] == $chars[$c] + 1; $c++)
4229 $str .= pchr($chars[$c]);
4235 sub tr_decode_byte {
4236 my($table, $flags) = @_;
4237 my(@table) = unpack("s*", $table);
4238 splice @table, 0x100, 1; # Number of subsequent elements
4239 my($c, $tr, @from, @to, @delfrom, $delhyphen);
4240 if ($table[ord "-"] != -1 and
4241 $table[ord("-") - 1] == -1 || $table[ord("-") + 1] == -1)
4243 $tr = $table[ord "-"];
4244 $table[ord "-"] = -1;
4248 } else { # -2 ==> delete
4252 for ($c = 0; $c < @table; $c++) {
4255 push @from, $c; push @to, $tr;
4256 } elsif ($tr == -2) {
4260 @from = (@from, @delfrom);
4261 if ($flags & OPpTRANS_COMPLEMENT) {
4264 @from{@from} = (1) x @from;
4265 for ($c = 0; $c < 256; $c++) {
4266 push @newfrom, $c unless $from{$c};
4270 unless ($flags & OPpTRANS_DELETE || !@to) {
4271 pop @to while $#to and $to[$#to] == $to[$#to -1];
4274 $from = collapse(@from);
4275 $to = collapse(@to);
4276 $from .= "-" if $delhyphen;
4277 return ($from, $to);
4282 if ($x == ord "-") {
4284 } elsif ($x == ord "\\") {
4291 # XXX This doesn't yet handle all cases correctly either
4293 sub tr_decode_utf8 {
4294 my($swash_hv, $flags) = @_;
4295 my %swash = $swash_hv->ARRAY;
4297 $final = $swash{'FINAL'}->IV if exists $swash{'FINAL'};
4298 my $none = $swash{"NONE"}->IV;
4299 my $extra = $none + 1;
4300 my(@from, @delfrom, @to);
4302 foreach $line (split /\n/, $swash{'LIST'}->PV) {
4303 my($min, $max, $result) = split(/\t/, $line);
4310 $result = hex $result;
4311 if ($result == $extra) {
4312 push @delfrom, [$min, $max];
4314 push @from, [$min, $max];
4315 push @to, [$result, $result + $max - $min];
4318 for my $i (0 .. $#from) {
4319 if ($from[$i][0] == ord '-') {
4320 unshift @from, splice(@from, $i, 1);
4321 unshift @to, splice(@to, $i, 1);
4323 } elsif ($from[$i][1] == ord '-') {
4326 unshift @from, ord '-';
4327 unshift @to, ord '-';
4331 for my $i (0 .. $#delfrom) {
4332 if ($delfrom[$i][0] == ord '-') {
4333 push @delfrom, splice(@delfrom, $i, 1);
4335 } elsif ($delfrom[$i][1] == ord '-') {
4337 push @delfrom, ord '-';
4341 if (defined $final and $to[$#to][1] != $final) {
4342 push @to, [$final, $final];
4344 push @from, @delfrom;
4345 if ($flags & OPpTRANS_COMPLEMENT) {
4348 for my $i (0 .. $#from) {
4349 push @newfrom, [$next, $from[$i][0] - 1];
4350 $next = $from[$i][1] + 1;
4353 for my $range (@newfrom) {
4354 if ($range->[0] <= $range->[1]) {