2 # Copyright (c) 1998-2000, 2002, 2003, 2004, 2005, 2006 Stephen McCamant.
4 # This module is free software; you can redistribute and/or modify
5 # it under the same terms as Perl itself.
7 # This is based on the module of the same name by Malcolm Beattie,
8 # but essentially none of his code remains.
12 use B qw(class main_root main_start main_cv svref_2object opnumber perlstring
13 OPf_WANT OPf_WANT_VOID OPf_WANT_SCALAR OPf_WANT_LIST
14 OPf_KIDS OPf_REF OPf_STACKED OPf_SPECIAL OPf_MOD
15 OPpLVAL_INTRO OPpOUR_INTRO OPpENTERSUB_AMPER OPpSLICE OPpCONST_BARE
16 OPpTRANS_SQUASH OPpTRANS_DELETE OPpTRANS_COMPLEMENT OPpTARGET_MY
17 OPpEXISTS_SUB OPpSORT_NUMERIC OPpSORT_INTEGER
19 SVf_IOK SVf_NOK SVf_ROK SVf_POK SVpad_OUR SVf_FAKE SVs_RMG SVs_SMG
21 PMf_KEEP PMf_GLOBAL PMf_CONTINUE PMf_EVAL PMf_ONCE
22 PMf_MULTILINE PMf_SINGLELINE PMf_FOLD PMf_EXTENDED);
25 use vars qw/$AUTOLOAD/;
30 # List version-specific constants here.
31 # Easiest way to keep this code portable between version looks to
32 # be to fake up a dummy constant that will never actually be true.
33 foreach (qw(OPpSORT_INPLACE OPpSORT_DESCEND OPpITER_REVERSED OPpCONST_NOVER
34 OPpPAD_STATE PMf_SKIPWHITE RXf_SKIPWHITE
35 RXf_PMf_CHARSET RXf_PMf_KEEPCOPY
36 CVf_LOCKED OPpREVERSE_INPLACE OPpSUBSTR_REPL_FIRST
37 PMf_NONDESTRUCT OPpCONST_ARYBASE OPpEVAL_BYTES)) {
40 *{$_} = sub () {0} unless *{$_}{CODE};
44 # Changes between 0.50 and 0.51:
45 # - fixed nulled leave with live enter in sort { }
46 # - fixed reference constants (\"str")
47 # - handle empty programs gracefully
48 # - handle infinite loops (for (;;) {}, while (1) {})
49 # - differentiate between 'for my $x ...' and 'my $x; for $x ...'
50 # - various minor cleanups
51 # - moved globals into an object
52 # - added '-u', like B::C
53 # - package declarations using cop_stash
54 # - subs, formats and code sorted by cop_seq
55 # Changes between 0.51 and 0.52:
56 # - added pp_threadsv (special variables under USE_5005THREADS)
57 # - added documentation
58 # Changes between 0.52 and 0.53:
59 # - many changes adding precedence contexts and associativity
60 # - added '-p' and '-s' output style options
61 # - various other minor fixes
62 # Changes between 0.53 and 0.54:
63 # - added support for new 'for (1..100)' optimization,
65 # Changes between 0.54 and 0.55:
66 # - added support for new qr// construct
67 # - added support for new pp_regcreset OP
68 # Changes between 0.55 and 0.56:
69 # - tested on base/*.t, cmd/*.t, comp/*.t, io/*.t
70 # - fixed $# on non-lexicals broken in last big rewrite
71 # - added temporary fix for change in opcode of OP_STRINGIFY
72 # - fixed problem in 0.54's for() patch in 'for (@ary)'
73 # - fixed precedence in conditional of ?:
74 # - tweaked list paren elimination in 'my($x) = @_'
75 # - made continue-block detection trickier wrt. null ops
76 # - fixed various prototype problems in pp_entersub
77 # - added support for sub prototypes that never get GVs
78 # - added unquoting for special filehandle first arg in truncate
79 # - print doubled rv2gv (a bug) as '*{*GV}' instead of illegal '**GV'
80 # - added semicolons at the ends of blocks
81 # - added -l '#line' declaration option -- fixes cmd/subval.t 27,28
82 # Changes between 0.56 and 0.561:
83 # - fixed multiply-declared my var in pp_truncate (thanks to Sarathy)
84 # - used new B.pm symbolic constants (done by Nick Ing-Simmons)
85 # Changes between 0.561 and 0.57:
86 # - stylistic changes to symbolic constant stuff
87 # - handled scope in s///e replacement code
88 # - added unquote option for expanding "" into concats, etc.
89 # - split method and proto parts of pp_entersub into separate functions
90 # - various minor cleanups
92 # - added parens in \&foo (patch by Albert Dvornik)
93 # Changes between 0.57 and 0.58:
94 # - fixed '0' statements that weren't being printed
95 # - added methods for use from other programs
96 # (based on patches from James Duncan and Hugo van der Sanden)
97 # - added -si and -sT to control indenting (also based on a patch from Hugo)
98 # - added -sv to print something else instead of '???'
99 # - preliminary version of utf8 tr/// handling
100 # Changes after 0.58:
101 # - uses of $op->ppaddr changed to new $op->name (done by Sarathy)
102 # - added support for Hugo's new OP_SETSTATE (like nextstate)
103 # Changes between 0.58 and 0.59
104 # - added support for Chip's OP_METHOD_NAMED
105 # - added support for Ilya's OPpTARGET_MY optimization
106 # - elided arrows before '()' subscripts when possible
107 # Changes between 0.59 and 0.60
108 # - support for method attributes was added
109 # - some warnings fixed
110 # - separate recognition of constant subs
111 # - rewrote continue block handling, now recognizing for loops
112 # - added more control of expanding control structures
113 # Changes between 0.60 and 0.61 (mostly by Robin Houston)
115 # - support for pragmas and 'use'
116 # - support for the little-used $[ variable
117 # - support for __DATA__ sections
119 # - BEGIN, CHECK, INIT and END blocks
120 # - scoping of subroutine declarations fixed
121 # - compile-time output from the input program can be suppressed, so that the
122 # output is just the deparsed code. (a change to O.pm in fact)
123 # - our() declarations
124 # - *all* the known bugs are now listed in the BUGS section
125 # - comprehensive test mechanism (TEST -deparse)
126 # Changes between 0.62 and 0.63 (mostly by Rafael Garcia-Suarez)
129 # - support for command-line switches (-l, -0, etc.)
130 # Changes between 0.63 and 0.64
131 # - support for //, CHECK blocks, and assertions
132 # - improved handling of foreach loops and lexicals
133 # - option to use Data::Dumper for constants
135 # - discovered lots more bugs not yet fixed
139 # Changes between 0.72 and 0.73
140 # - support new switch constructs
143 # (See also BUGS section at the end of this file)
145 # - finish tr/// changes
146 # - add option for even more parens (generalize \&foo change)
147 # - left/right context
148 # - copy comments (look at real text with $^P?)
149 # - avoid semis in one-statement blocks
150 # - associativity of &&=, ||=, ?:
151 # - ',' => '=>' (auto-unquote?)
152 # - break long lines ("\r" as discretionary break?)
153 # - configurable syntax highlighting: ANSI color, HTML, TeX, etc.
154 # - more style options: brace style, hex vs. octal, quotes, ...
155 # - print big ints as hex/octal instead of decimal (heuristic?)
156 # - handle 'my $x if 0'?
157 # - version using op_next instead of op_first/sibling?
158 # - avoid string copies (pass arrays, one big join?)
161 # Current test.deparse failures
162 # comp/hints 6 - location of BEGIN blocks wrt. block openings
163 # run/switchI 1 - missing -I switches entirely
164 # perl -Ifoo -e 'print @INC'
165 # op/caller 2 - warning mask propagates backwards before warnings::register
166 # 'use warnings; BEGIN {${^WARNING_BITS} eq "U"x12;} use warnings::register'
167 # op/getpid 2 - can't assign to shared my() declaration (threads only)
168 # 'my $x : shared = 5'
169 # op/override 7 - parens on overridden require change v-string interpretation
170 # 'BEGIN{*CORE::GLOBAL::require=sub {}} require v5.6'
171 # c.f. 'BEGIN { *f = sub {0} }; f 2'
172 # op/pat 774 - losing Unicode-ness of Latin1-only strings
173 # 'use charnames ":short"; $x="\N{latin:a with acute}"'
174 # op/recurse 12 - missing parens on recursive call makes it look like method
176 # op/subst 90 - inconsistent handling of utf8 under "use utf8"
177 # op/taint 29 - "use re 'taint'" deparsed in the wrong place wrt. block open
178 # op/tiehandle compile - "use strict" deparsed in the wrong place
180 # ext/B/t/xref 11 - line numbers when we add newlines to one-line subs
181 # ext/Data/Dumper/t/dumper compile
182 # ext/DB_file/several
184 # ext/Ernno/Errno warnings
185 # ext/IO/lib/IO/t/io_sel 23
186 # ext/PerlIO/t/encoding compile
187 # ext/POSIX/t/posix 6
188 # ext/Socket/Socket 8
189 # ext/Storable/t/croak compile
190 # lib/Attribute/Handlers/t/multi compile
191 # lib/bignum/ several
195 # lib/ExtUtils/t/bytes 4
196 # lib/File/DosGlob compile
197 # lib/Filter/Simple/t/data 1
198 # lib/Math/BigInt/t/constant 1
199 # lib/Net/t/config Deparse-warning
200 # lib/overload compile
201 # lib/Switch/ several
203 # lib/Test/Simple several
205 # lib/Tie/File/t/29_downcopy 5
208 # Object fields (were globals):
211 # (local($a), local($b)) and local($a, $b) have the same internal
212 # representation but the short form looks better. We notice we can
213 # use a large-scale local when checking the list, but need to prevent
214 # individual locals too. This hash holds the addresses of OPs that
215 # have already had their local-ness accounted for. The same thing
219 # CV for current sub (or main program) being deparsed
222 # Cached hash of lexical variables for curcv: keys are
223 # names prefixed with "m" or "o" (representing my/our), and
224 # each value is an array of pairs, indicating the cop_seq of scopes
225 # in which a var of that name is valid.
228 # COP for statement being deparsed
231 # name of the current package for deparsed code
234 # array of [cop_seq, CV, is_format?] for subs and formats we still
238 # as above, but [name, prototype] for subs that never got a GV
240 # subs_done, forms_done:
241 # keys are addresses of GVs for subs and formats we've already
242 # deparsed (or at least put into subs_todo)
245 # keys are names of subs for which we've printed declarations.
246 # That means we can omit parentheses from the arguments. It also means we
247 # need to put CORE:: on core functions of the same name.
250 # Keeps track of fully qualified names of all deparsed subs.
255 # cuddle: ' ' or '\n', depending on -sC
260 # A little explanation of how precedence contexts and associativity
263 # deparse() calls each per-op subroutine with an argument $cx (short
264 # for context, but not the same as the cx* in the perl core), which is
265 # a number describing the op's parents in terms of precedence, whether
266 # they're inside an expression or at statement level, etc. (see
267 # chart below). When ops with children call deparse on them, they pass
268 # along their precedence. Fractional values are used to implement
269 # associativity ('($x + $y) + $z' => '$x + $y + $y') and related
270 # parentheses hacks. The major disadvantage of this scheme is that
271 # it doesn't know about right sides and left sides, so say if you
272 # assign a listop to a variable, it can't tell it's allowed to leave
273 # the parens off the listop.
276 # 26 [TODO] inside interpolation context ("")
277 # 25 left terms and list operators (leftward)
281 # 21 right ! ~ \ and unary + and -
286 # 16 nonassoc named unary operators
287 # 15 nonassoc < > <= >= lt gt le ge
288 # 14 nonassoc == != <=> eq ne cmp
295 # 7 right = += -= *= etc.
297 # 5 nonassoc list operators (rightward)
301 # 1 statement modifiers
302 # 0.5 statements, but still print scopes as do { ... }
306 # Nonprinting characters with special meaning:
307 # \cS - steal parens (see maybe_parens_unop)
308 # \n - newline and indent
309 # \t - increase indent
310 # \b - decrease indent ('outdent')
311 # \f - flush left (no indent)
312 # \cK - kill following semicolon, if any
316 return class($op) eq "NULL";
321 my($cv, $is_form) = @_;
322 return unless ($cv->FILE eq $0 || exists $self->{files}{$cv->FILE});
324 if ($cv->OUTSIDE_SEQ) {
325 $seq = $cv->OUTSIDE_SEQ;
326 } elsif (!null($cv->START) and is_state($cv->START)) {
327 $seq = $cv->START->cop_seq;
331 push @{$self->{'subs_todo'}}, [$seq, $cv, $is_form];
332 unless ($is_form || class($cv->STASH) eq 'SPECIAL') {
333 $self->{'subs_deparsed'}{$cv->STASH->NAME."::".$cv->GV->NAME} = 1;
339 my $ent = shift @{$self->{'subs_todo'}};
342 my $name = $self->gv_name($gv);
344 return "format $name =\n"
345 . $self->deparse_format($ent->[1]). "\n";
347 $self->{'subs_declared'}{$name} = 1;
348 if ($name eq "BEGIN") {
349 my $use_dec = $self->begin_is_use($cv);
350 if (defined ($use_dec) and $self->{'expand'} < 5) {
351 return () if 0 == length($use_dec);
356 if ($self->{'linenums'}) {
357 my $line = $gv->LINE;
358 my $file = $gv->FILE;
359 $l = "\n\f#line $line \"$file\"\n";
362 if (class($cv->STASH) ne "SPECIAL") {
363 my $stash = $cv->STASH->NAME;
364 if ($stash ne $self->{'curstash'}) {
365 $p = "package $stash;\n";
366 $name = "$self->{'curstash'}::$name" unless $name =~ /::/;
367 $self->{'curstash'} = $stash;
369 $name =~ s/^\Q$stash\E::(?!\z|.*::)//;
371 return "${p}${l}sub $name " . $self->deparse_sub($cv);
375 # Return a "use" declaration for this BEGIN block, if appropriate
377 my ($self, $cv) = @_;
378 my $root = $cv->ROOT;
379 local @$self{qw'curcv curcvlex'} = ($cv);
381 #B::walkoptree($cv->ROOT, "debug");
382 my $lineseq = $root->first;
383 return if $lineseq->name ne "lineseq";
385 my $req_op = $lineseq->first->sibling;
386 return if $req_op->name ne "require";
389 if ($req_op->first->private & OPpCONST_BARE) {
390 # Actually it should always be a bareword
391 $module = $self->const_sv($req_op->first)->PV;
392 $module =~ s[/][::]g;
396 $module = $self->const($self->const_sv($req_op->first), 6);
400 my $version_op = $req_op->sibling;
401 return if class($version_op) eq "NULL";
402 if ($version_op->name eq "lineseq") {
403 # We have a version parameter; skip nextstate & pushmark
404 my $constop = $version_op->first->next->next;
406 return unless $self->const_sv($constop)->PV eq $module;
407 $constop = $constop->sibling;
408 $version = $self->const_sv($constop);
409 if (class($version) eq "IV") {
410 $version = $version->int_value;
411 } elsif (class($version) eq "NV") {
412 $version = $version->NV;
413 } elsif (class($version) ne "PVMG") {
414 # Includes PVIV and PVNV
415 $version = $version->PV;
417 # version specified as a v-string
418 $version = 'v'.join '.', map ord, split //, $version->PV;
420 $constop = $constop->sibling;
421 return if $constop->name ne "method_named";
422 return if $self->const_sv($constop)->PV ne "VERSION";
425 $lineseq = $version_op->sibling;
426 return if $lineseq->name ne "lineseq";
427 my $entersub = $lineseq->first->sibling;
428 if ($entersub->name eq "stub") {
429 return "use $module $version ();\n" if defined $version;
430 return "use $module ();\n";
432 return if $entersub->name ne "entersub";
434 # See if there are import arguments
437 my $svop = $entersub->first->sibling; # Skip over pushmark
438 return unless $self->const_sv($svop)->PV eq $module;
440 # Pull out the arguments
441 for ($svop=$svop->sibling; $svop->name ne "method_named";
442 $svop = $svop->sibling) {
443 $args .= ", " if length($args);
444 $args .= $self->deparse($svop, 6);
448 my $method_named = $svop;
449 return if $method_named->name ne "method_named";
450 my $method_name = $self->const_sv($method_named)->PV;
452 if ($method_name eq "unimport") {
456 # Certain pragmas are dealt with using hint bits,
457 # so we ignore them here
458 if ($module eq 'strict' || $module eq 'integer'
459 || $module eq 'bytes' || $module eq 'warnings'
460 || $module eq 'feature') {
464 if (defined $version && length $args) {
465 return "$use $module $version ($args);\n";
466 } elsif (defined $version) {
467 return "$use $module $version;\n";
468 } elsif (length $args) {
469 return "$use $module ($args);\n";
471 return "$use $module;\n";
476 my ($self, $pack, $seen) = @_;
478 if (!defined $pack) {
483 $pack =~ s/(::)?$/::/;
485 $stash = \%{"main::$pack"};
489 $INC{"overload.pm"} ? overload::StrVal($stash) : $stash
491 my %stash = svref_2object($stash)->ARRAY;
492 while (my ($key, $val) = each %stash) {
493 my $class = class($val);
494 if ($class eq "PV") {
495 # Just a prototype. As an ugly but fairly effective way
496 # to find out if it belongs here is to see if the AUTOLOAD
497 # (if any) for the stash was defined in one of our files.
498 my $A = $stash{"AUTOLOAD"};
499 if (defined ($A) && class($A) eq "GV" && defined($A->CV)
500 && class($A->CV) eq "CV") {
502 next unless $AF eq $0 || exists $self->{'files'}{$AF};
504 push @{$self->{'protos_todo'}}, [$pack . $key, $val->PV];
505 } elsif ($class eq "IV" && !($val->FLAGS & SVf_ROK)) {
506 # Just a name. As above.
507 # But skip proxy constant subroutines, as some form of perl-space
508 # visible code must have created them, be it a use statement, or
509 # some direct symbol-table manipulation code that we will Deparse
510 my $A = $stash{"AUTOLOAD"};
511 if (defined ($A) && class($A) eq "GV" && defined($A->CV)
512 && class($A->CV) eq "CV") {
514 next unless $AF eq $0 || exists $self->{'files'}{$AF};
516 push @{$self->{'protos_todo'}}, [$pack . $key, undef];
517 } elsif ($class eq "GV") {
518 if (class(my $cv = $val->CV) ne "SPECIAL") {
519 next if $self->{'subs_done'}{$$val}++;
520 next if $$val != ${$cv->GV}; # Ignore imposters
523 if (class(my $cv = $val->FORM) ne "SPECIAL") {
524 next if $self->{'forms_done'}{$$val}++;
525 next if $$val != ${$cv->GV}; # Ignore imposters
528 if (class($val->HV) ne "SPECIAL" && $key =~ /::$/) {
529 $self->stash_subs($pack . $key, $seen);
539 foreach $ar (@{$self->{'protos_todo'}}) {
540 my $proto = (defined $ar->[1] ? " (". $ar->[1] . ")" : "");
541 push @ret, "sub " . $ar->[0] . "$proto;\n";
543 delete $self->{'protos_todo'};
551 while (length($opt = substr($opts, 0, 1))) {
553 $self->{'cuddle'} = " ";
554 $opts = substr($opts, 1);
555 } elsif ($opt eq "i") {
556 $opts =~ s/^i(\d+)//;
557 $self->{'indent_size'} = $1;
558 } elsif ($opt eq "T") {
559 $self->{'use_tabs'} = 1;
560 $opts = substr($opts, 1);
561 } elsif ($opt eq "v") {
562 $opts =~ s/^v([^.]*)(.|$)//;
563 $self->{'ex_const'} = $1;
570 my $self = bless {}, $class;
571 $self->{'cuddle'} = "\n";
572 $self->{'curcop'} = undef;
573 $self->{'curstash'} = "main";
574 $self->{'ex_const'} = "'???'";
575 $self->{'expand'} = 0;
576 $self->{'files'} = {};
577 $self->{'indent_size'} = 4;
578 $self->{'linenums'} = 0;
579 $self->{'parens'} = 0;
580 $self->{'subs_todo'} = [];
581 $self->{'unquote'} = 0;
582 $self->{'use_dumper'} = 0;
583 $self->{'use_tabs'} = 0;
585 $self->{'ambient_arybase'} = 0;
586 $self->{'ambient_warnings'} = undef; # Assume no lexical warnings
587 $self->{'ambient_hints'} = 0;
588 $self->{'ambient_hinthash'} = undef;
591 while (my $arg = shift @_) {
593 $self->{'use_dumper'} = 1;
594 require Data::Dumper;
595 } elsif ($arg =~ /^-f(.*)/) {
596 $self->{'files'}{$1} = 1;
597 } elsif ($arg eq "-l") {
598 $self->{'linenums'} = 1;
599 } elsif ($arg eq "-p") {
600 $self->{'parens'} = 1;
601 } elsif ($arg eq "-P") {
602 $self->{'noproto'} = 1;
603 } elsif ($arg eq "-q") {
604 $self->{'unquote'} = 1;
605 } elsif (substr($arg, 0, 2) eq "-s") {
606 $self->style_opts(substr $arg, 2);
607 } elsif ($arg =~ /^-x(\d)$/) {
608 $self->{'expand'} = $1;
615 # Mask out the bits that L<warnings::register> uses
618 $WARN_MASK = $warnings::Bits{all} | $warnings::DeadBits{all};
625 # Initialise the contextual information, either from
626 # defaults provided with the ambient_pragmas method,
627 # or from perl's own defaults otherwise.
631 $self->{'arybase'} = $self->{'ambient_arybase'};
632 $self->{'warnings'} = defined ($self->{'ambient_warnings'})
633 ? $self->{'ambient_warnings'} & WARN_MASK
635 $self->{'hints'} = $self->{'ambient_hints'};
636 $self->{'hints'} &= 0xFF if $] < 5.009;
637 $self->{'hinthash'} = $self->{'ambient_hinthash'};
639 # also a convenient place to clear out subs_declared
640 delete $self->{'subs_declared'};
646 my $self = B::Deparse->new(@args);
647 # First deparse command-line args
648 if (defined $^I) { # deparse -i
649 print q(BEGIN { $^I = ).perlstring($^I).qq(; }\n);
651 if ($^W) { # deparse -w
652 print qq(BEGIN { \$^W = $^W; }\n);
654 if ($/ ne "\n" or defined $O::savebackslash) { # deparse -l and -0
655 my $fs = perlstring($/) || 'undef';
656 my $bs = perlstring($O::savebackslash) || 'undef';
657 print qq(BEGIN { \$/ = $fs; \$\\ = $bs; }\n);
659 my @BEGINs = B::begin_av->isa("B::AV") ? B::begin_av->ARRAY : ();
660 my @UNITCHECKs = B::unitcheck_av->isa("B::AV")
661 ? B::unitcheck_av->ARRAY
663 my @CHECKs = B::check_av->isa("B::AV") ? B::check_av->ARRAY : ();
664 my @INITs = B::init_av->isa("B::AV") ? B::init_av->ARRAY : ();
665 my @ENDs = B::end_av->isa("B::AV") ? B::end_av->ARRAY : ();
666 for my $block (@BEGINs, @UNITCHECKs, @CHECKs, @INITs, @ENDs) {
667 $self->todo($block, 0);
670 local($SIG{"__DIE__"}) =
672 if ($self->{'curcop'}) {
673 my $cop = $self->{'curcop'};
674 my($line, $file) = ($cop->line, $cop->file);
675 print STDERR "While deparsing $file near line $line,\n";
678 $self->{'curcv'} = main_cv;
679 $self->{'curcvlex'} = undef;
680 print $self->print_protos;
681 @{$self->{'subs_todo'}} =
682 sort {$a->[0] <=> $b->[0]} @{$self->{'subs_todo'}};
683 print $self->indent($self->deparse_root(main_root)), "\n"
684 unless null main_root;
686 while (scalar(@{$self->{'subs_todo'}})) {
687 push @text, $self->next_todo;
689 print $self->indent(join("", @text)), "\n" if @text;
691 # Print __DATA__ section, if necessary
693 my $laststash = defined $self->{'curcop'}
694 ? $self->{'curcop'}->stash->NAME : $self->{'curstash'};
695 if (defined *{$laststash."::DATA"}{IO}) {
696 print "package $laststash;\n"
697 unless $laststash eq $self->{'curstash'};
699 print readline(*{$laststash."::DATA"});
707 croak "Usage: ->coderef2text(CODEREF)" unless UNIVERSAL::isa($sub, "CODE");
710 return $self->indent($self->deparse_sub(svref_2object($sub)));
713 my %strict_bits = do {
715 map +($_ => strict::bits($_)), qw/refs subs vars/
718 sub ambient_pragmas {
720 my ($arybase, $hint_bits, $warning_bits, $hinthash) = (0, 0);
726 if ($name eq 'strict') {
729 if ($val eq 'none') {
730 $hint_bits &= $strict_bits{$_} for qw/refs subs vars/;
736 @names = qw/refs subs vars/;
742 @names = split' ', $val;
744 $hint_bits |= $strict_bits{$_} for @names;
747 elsif ($name eq '$[') {
748 if (OPpCONST_ARYBASE) {
751 croak "\$[ can't be non-zero on this perl" unless $val == 0;
755 elsif ($name eq 'integer'
757 || $name eq 'utf8') {
760 $hint_bits |= ${$::{"${name}::"}{"hint_bits"}};
763 $hint_bits &= ~${$::{"${name}::"}{"hint_bits"}};
767 elsif ($name eq 're') {
769 if ($val eq 'none') {
770 $hint_bits &= ~re::bits(qw/taint eval/);
776 @names = qw/taint eval/;
782 @names = split' ',$val;
784 $hint_bits |= re::bits(@names);
787 elsif ($name eq 'warnings') {
788 if ($val eq 'none') {
789 $warning_bits = $warnings::NONE;
798 @names = split/\s+/, $val;
801 $warning_bits = $warnings::NONE if !defined ($warning_bits);
802 $warning_bits |= warnings::bits(@names);
805 elsif ($name eq 'warning_bits') {
806 $warning_bits = $val;
809 elsif ($name eq 'hint_bits') {
813 elsif ($name eq '%^H') {
818 croak "Unknown pragma type: $name";
822 croak "The ambient_pragmas method expects an even number of args";
825 $self->{'ambient_arybase'} = $arybase;
826 $self->{'ambient_warnings'} = $warning_bits;
827 $self->{'ambient_hints'} = $hint_bits;
828 $self->{'ambient_hinthash'} = $hinthash;
831 # This method is the inner loop, so try to keep it simple
836 Carp::confess("Null op in deparse") if !defined($op)
837 || class($op) eq "NULL";
838 my $meth = "pp_" . $op->name;
839 return $self->$meth($op, $cx);
845 my @lines = split(/\n/, $txt);
850 my $cmd = substr($line, 0, 1);
851 if ($cmd eq "\t" or $cmd eq "\b") {
852 $level += ($cmd eq "\t" ? 1 : -1) * $self->{'indent_size'};
853 if ($self->{'use_tabs'}) {
854 $leader = "\t" x ($level / 8) . " " x ($level % 8);
856 $leader = " " x $level;
858 $line = substr($line, 1);
860 if (substr($line, 0, 1) eq "\f") {
861 $line = substr($line, 1); # no indent
863 $line = $leader . $line;
867 return join("\n", @lines);
874 Carp::confess("NULL in deparse_sub") if !defined($cv) || $cv->isa("B::NULL");
875 Carp::confess("SPECIAL in deparse_sub") if $cv->isa("B::SPECIAL");
876 local $self->{'curcop'} = $self->{'curcop'};
877 if ($cv->FLAGS & SVf_POK) {
878 $proto = "(". $cv->PV . ") ";
880 if ($cv->CvFLAGS & (CVf_METHOD|CVf_LOCKED|CVf_LVALUE)) {
882 $proto .= "lvalue " if $cv->CvFLAGS & CVf_LVALUE;
883 $proto .= "locked " if $cv->CvFLAGS & CVf_LOCKED;
884 $proto .= "method " if $cv->CvFLAGS & CVf_METHOD;
887 local($self->{'curcv'}) = $cv;
888 local($self->{'curcvlex'});
889 local(@$self{qw'curstash warnings hints hinthash'})
890 = @$self{qw'curstash warnings hints hinthash'};
892 if (not null $cv->ROOT) {
893 my $lineseq = $cv->ROOT->first;
894 if ($lineseq->name eq "lineseq") {
896 for(my$o=$lineseq->first; $$o; $o=$o->sibling) {
899 $body = $self->lineseq(undef, 0, @ops).";";
900 my $scope_en = $self->find_scope_en($lineseq);
901 if (defined $scope_en) {
902 my $subs = join"", $self->seq_subs($scope_en);
903 $body .= ";\n$subs" if length($subs);
907 $body = $self->deparse($cv->ROOT->first, 0);
911 my $sv = $cv->const_sv;
913 # uh-oh. inlinable sub... format it differently
914 return $proto . "{ " . $self->const($sv, 0) . " }\n";
915 } else { # XSUB? (or just a declaration)
919 return $proto ."{\n\t$body\n\b}" ."\n";
926 local($self->{'curcv'}) = $form;
927 local($self->{'curcvlex'});
928 local($self->{'in_format'}) = 1;
929 local(@$self{qw'curstash warnings hints hinthash'})
930 = @$self{qw'curstash warnings hints hinthash'};
931 my $op = $form->ROOT;
933 return "\f." if $op->first->name eq 'stub'
934 || $op->first->name eq 'nextstate';
935 $op = $op->first->first; # skip leavewrite, lineseq
936 while (not null $op) {
937 $op = $op->sibling; # skip nextstate
939 $kid = $op->first->sibling; # skip pushmark
940 push @text, "\f".$self->const_sv($kid)->PV;
941 $kid = $kid->sibling;
942 for (; not null $kid; $kid = $kid->sibling) {
943 push @exprs, $self->deparse($kid, -1);
944 $exprs[-1] =~ s/;\z//;
946 push @text, "\f".join(", ", @exprs)."\n" if @exprs;
949 return join("", @text) . "\f.";
954 return $op->name eq "leave" || $op->name eq "scope"
955 || $op->name eq "lineseq"
956 || ($op->name eq "null" && class($op) eq "UNOP"
957 && (is_scope($op->first) || $op->first->name eq "enter"));
961 my $name = $_[0]->name;
962 return $name eq "nextstate" || $name eq "dbstate" || $name eq "setstate";
965 sub is_miniwhile { # check for one-line loop ('foo() while $y--')
967 return (!null($op) and null($op->sibling)
968 and $op->name eq "null" and class($op) eq "UNOP"
969 and (($op->first->name =~ /^(and|or)$/
970 and $op->first->first->sibling->name eq "lineseq")
971 or ($op->first->name eq "lineseq"
972 and not null $op->first->first->sibling
973 and $op->first->first->sibling->name eq "unstack")
977 # Check if the op and its sibling are the initialization and the rest of a
978 # for (..;..;..) { ... } loop
981 # This OP might be almost anything, though it won't be a
982 # nextstate. (It's the initialization, so in the canonical case it
983 # will be an sassign.) The sibling is (old style) a lineseq whose
984 # first child is a nextstate and whose second is a leaveloop, or
985 # (new style) an unstack whose sibling is a leaveloop.
986 my $lseq = $op->sibling;
987 return 0 unless !is_state($op) and !null($lseq);
988 if ($lseq->name eq "lineseq") {
989 if ($lseq->first && !null($lseq->first) && is_state($lseq->first)
990 && (my $sib = $lseq->first->sibling)) {
991 return (!null($sib) && $sib->name eq "leaveloop");
993 } elsif ($lseq->name eq "unstack" && ($lseq->flags & OPf_SPECIAL)) {
994 my $sib = $lseq->sibling;
995 return $sib && !null($sib) && $sib->name eq "leaveloop";
1002 return ($op->name eq "rv2sv" or
1003 $op->name eq "padsv" or
1004 $op->name eq "gv" or # only in array/hash constructs
1005 $op->flags & OPf_KIDS && !null($op->first)
1006 && $op->first->name eq "gvsv");
1011 my($text, $cx, $prec) = @_;
1012 if ($prec < $cx # unary ops nest just fine
1013 or $prec == $cx and $cx != 4 and $cx != 16 and $cx != 21
1014 or $self->{'parens'})
1017 # In a unop, let parent reuse our parens; see maybe_parens_unop
1018 $text = "\cS" . $text if $cx == 16;
1025 # same as above, but get around the 'if it looks like a function' rule
1026 sub maybe_parens_unop {
1028 my($name, $kid, $cx) = @_;
1029 if ($cx > 16 or $self->{'parens'}) {
1030 $kid = $self->deparse($kid, 1);
1031 if ($name eq "umask" && $kid =~ /^\d+$/) {
1032 $kid = sprintf("%#o", $kid);
1034 return $self->keyword($name) . "($kid)";
1036 $kid = $self->deparse($kid, 16);
1037 if ($name eq "umask" && $kid =~ /^\d+$/) {
1038 $kid = sprintf("%#o", $kid);
1040 $name = $self->keyword($name);
1041 if (substr($kid, 0, 1) eq "\cS") {
1043 return $name . substr($kid, 1);
1044 } elsif (substr($kid, 0, 1) eq "(") {
1045 # avoid looks-like-a-function trap with extra parens
1046 # ('+' can lead to ambiguities)
1047 return "$name(" . $kid . ")";
1049 return "$name $kid";
1054 sub maybe_parens_func {
1056 my($func, $text, $cx, $prec) = @_;
1057 if ($prec <= $cx or substr($text, 0, 1) eq "(" or $self->{'parens'}) {
1058 return "$func($text)";
1060 return "$func $text";
1066 my($op, $cx, $text) = @_;
1067 my $our_intro = ($op->name =~ /^(gv|rv2)[ash]v$/) ? OPpOUR_INTRO : 0;
1068 if ($op->private & (OPpLVAL_INTRO|$our_intro)
1069 and not $self->{'avoid_local'}{$$op}) {
1070 my $our_local = ($op->private & OPpLVAL_INTRO) ? "local" : "our";
1071 if( $our_local eq 'our' ) {
1072 if ( $text !~ /^\W(\w+::)*\w+\z/
1073 and !utf8::decode($text) || $text !~ /^\W(\w+::)*\w+\z/
1075 die "Unexpected our($text)\n";
1077 $text =~ s/(\w+::)+//;
1079 if (want_scalar($op)) {
1080 return "$our_local $text";
1082 return $self->maybe_parens_func("$our_local", $text, $cx, 16);
1091 my($op, $cx, $func, @args) = @_;
1092 if ($op->private & OPpTARGET_MY) {
1093 my $var = $self->padname($op->targ);
1094 my $val = $func->($self, $op, 7, @args);
1095 return $self->maybe_parens("$var = $val", $cx, 7);
1097 return $func->($self, $op, $cx, @args);
1104 return $self->{'curcv'}->PADLIST->ARRAYelt(0)->ARRAYelt($targ);
1109 my($op, $cx, $text) = @_;
1110 if ($op->private & OPpLVAL_INTRO and not $self->{'avoid_local'}{$$op}) {
1111 my $my = $op->private & OPpPAD_STATE
1112 ? $self->keyword("state")
1114 if (want_scalar($op)) {
1117 return $self->maybe_parens_func($my, $text, $cx, 16);
1124 # The following OPs don't have functions:
1126 # pp_padany -- does not exist after parsing
1129 if ($AUTOLOAD =~ s/^.*::pp_//) {
1130 warn "unexpected OP_".uc $AUTOLOAD;
1133 die "Undefined subroutine $AUTOLOAD called";
1137 sub DESTROY {} # Do not AUTOLOAD
1139 # $root should be the op which represents the root of whatever
1140 # we're sequencing here. If it's undefined, then we don't append
1141 # any subroutine declarations to the deparsed ops, otherwise we
1142 # append appropriate declarations.
1144 my($self, $root, $cx, @ops) = @_;
1147 my $out_cop = $self->{'curcop'};
1148 my $out_seq = defined($out_cop) ? $out_cop->cop_seq : undef;
1150 if (defined $root) {
1151 $limit_seq = $out_seq;
1153 $nseq = $self->find_scope_st($root->sibling) if ${$root->sibling};
1154 $limit_seq = $nseq if !defined($limit_seq)
1155 or defined($nseq) && $nseq < $limit_seq;
1157 $limit_seq = $self->{'limit_seq'}
1158 if defined($self->{'limit_seq'})
1159 && (!defined($limit_seq) || $self->{'limit_seq'} < $limit_seq);
1160 local $self->{'limit_seq'} = $limit_seq;
1162 $self->walk_lineseq($root, \@ops,
1163 sub { push @exprs, $_[0]} );
1165 my $sep = $cx ? '; ' : ";\n";
1166 my $body = join($sep, grep {length} @exprs);
1168 if (defined $root && defined $limit_seq && !$self->{'in_format'}) {
1169 $subs = join "\n", $self->seq_subs($limit_seq);
1171 return join($sep, grep {length} $body, $subs);
1175 my($real_block, $self, $op, $cx) = @_;
1179 local(@$self{qw'curstash warnings hints hinthash'})
1180 = @$self{qw'curstash warnings hints hinthash'} if $real_block;
1182 $kid = $op->first->sibling; # skip enter
1183 if (is_miniwhile($kid)) {
1184 my $top = $kid->first;
1185 my $name = $top->name;
1186 if ($name eq "and") {
1188 } elsif ($name eq "or") {
1190 } else { # no conditional -> while 1 or until 0
1191 return $self->deparse($top->first, 1) . " while 1";
1193 my $cond = $top->first;
1194 my $body = $cond->sibling->first; # skip lineseq
1195 $cond = $self->deparse($cond, 1);
1196 $body = $self->deparse($body, 1);
1197 return "$body $name $cond";
1202 for (; !null($kid); $kid = $kid->sibling) {
1205 if ($cx > 0) { # inside an expression, (a do {} while for lineseq)
1206 return "do {\n\t" . $self->lineseq($op, 0, @kids) . "\n\b}";
1208 my $lineseq = $self->lineseq($op, $cx, @kids);
1209 return (length ($lineseq) ? "$lineseq;" : "");
1213 sub pp_scope { scopeop(0, @_); }
1214 sub pp_lineseq { scopeop(0, @_); }
1215 sub pp_leave { scopeop(1, @_); }
1217 # This is a special case of scopeop and lineseq, for the case of the
1218 # main_root. The difference is that we print the output statements as
1219 # soon as we get them, for the sake of impatient users.
1223 local(@$self{qw'curstash warnings hints hinthash'})
1224 = @$self{qw'curstash warnings hints hinthash'};
1226 return if null $op->first; # Can happen, e.g., for Bytecode without -k
1227 for (my $kid = $op->first->sibling; !null($kid); $kid = $kid->sibling) {
1230 $self->walk_lineseq($op, \@kids,
1231 sub { print $self->indent($_[0].';');
1232 print "\n" unless $_[1] == $#kids;
1237 my ($self, $op, $kids, $callback) = @_;
1239 for (my $i = 0; $i < @kids; $i++) {
1241 if (is_state $kids[$i]) {
1242 $expr = $self->deparse($kids[$i++], 0);
1244 $callback->($expr, $i);
1248 if (is_for_loop($kids[$i])) {
1249 $callback->($expr . $self->for_loop($kids[$i], 0),
1250 $i += $kids[$i]->sibling->name eq "unstack" ? 2 : 1);
1253 $expr .= $self->deparse($kids[$i], (@kids != 1)/2);
1254 $expr =~ s/;\n?\z//;
1255 $callback->($expr, $i);
1259 # The BEGIN {} is used here because otherwise this code isn't executed
1260 # when you run B::Deparse on itself.
1262 BEGIN { map($globalnames{$_}++, "SIG", "STDIN", "STDOUT", "STDERR", "INC",
1263 "ENV", "ARGV", "ARGVOUT", "_"); }
1269 Carp::confess() unless ref($gv) eq "B::GV";
1270 my $stash = $gv->STASH->NAME;
1271 my $name = $raw ? $gv->NAME : $gv->SAFENAME;
1272 if ($stash eq 'main' && $name =~ /^::/) {
1275 elsif (($stash eq 'main'
1276 && ($globalnames{$name} || $name =~ /^[^A-Za-z_:]/))
1277 or ($stash eq $self->{'curstash'} && !$globalnames{$name}
1278 && ($stash eq 'main' || $name !~ /::/))
1283 $stash = $stash . "::";
1285 if (!$raw and $name =~ /^(\^..|{)/) {
1286 $name = "{$name}"; # ${^WARNING_BITS}, etc and ${
1288 return $stash . $name;
1291 # Return the name to use for a stash variable.
1292 # If a lexical with the same name is in scope, or
1293 # if strictures are enabled, it may need to be
1295 sub stash_variable {
1296 my ($self, $prefix, $name, $cx) = @_;
1298 return "$prefix$name" if $name =~ /::/;
1300 unless ($prefix eq '$' || $prefix eq '@' || #'
1301 $prefix eq '%' || $prefix eq '$#') {
1302 return "$prefix$name";
1305 if ($name =~ /^[^\w+-]$/) {
1306 if (defined $cx && $cx == 26) {
1307 if ($prefix eq '@') {
1308 return "$prefix\{$name}";
1310 elsif ($name eq '#') { return '${#}' } # "${#}a" vs "$#a"
1312 if ($prefix eq '$#') {
1313 return "\$#{$name}";
1317 return $prefix . $self->maybe_qualify($prefix, $name);
1320 # Return just the name, without the prefix. It may be returned as a quoted
1321 # string. The second return value is a boolean indicating that.
1322 sub stash_variable_name {
1323 my($self, $prefix, $gv) = @_;
1324 my $name = $self->gv_name($gv, 1);
1325 $name = $self->maybe_qualify($prefix,$name);
1326 if ($name =~ /^(?:\S|(?!\d)[\ca-\cz]?(?:\w|::)*|\d+)\z/) {
1327 $name =~ s/^([\ca-\cz])/'^'.($1|'@')/e;
1328 $name =~ /^(\^..|{)/ and $name = "{$name}";
1329 return $name, 0; # not quoted
1332 single_delim("q", "'", $name), 1;
1337 my ($self,$prefix,$name) = @_;
1338 my $v = ($prefix eq '$#' ? '@' : $prefix) . $name;
1339 return $name if !$prefix || $name =~ /::/;
1340 return $self->{'curstash'}.'::'. $name
1342 $name =~ /^(?!\d)\w/ # alphabetic
1343 && $v !~ /^\$[ab]\z/ # not $a or $b
1344 && !$globalnames{$name} # not a global name
1345 && $self->{hints} & $strict_bits{vars} # strict vars
1346 && !$self->lex_in_scope($v,1) # no "our"
1347 or $self->lex_in_scope($v); # conflicts with "my" variable
1352 my ($self, $name, $our) = @_;
1353 substr $name, 0, 0, = $our ? 'o' : 'm'; # our/my
1354 $self->populate_curcvlex() if !defined $self->{'curcvlex'};
1356 return 0 if !defined($self->{'curcop'});
1357 my $seq = $self->{'curcop'}->cop_seq;
1358 return 0 if !exists $self->{'curcvlex'}{$name};
1359 for my $a (@{$self->{'curcvlex'}{$name}}) {
1360 my ($st, $en) = @$a;
1361 return 1 if $seq > $st && $seq <= $en;
1366 sub populate_curcvlex {
1368 for (my $cv = $self->{'curcv'}; class($cv) eq "CV"; $cv = $cv->OUTSIDE) {
1369 my $padlist = $cv->PADLIST;
1370 # an undef CV still in lexical chain
1371 next if class($padlist) eq "SPECIAL";
1372 my @padlist = $padlist->ARRAY;
1373 my @ns = $padlist[0]->ARRAY;
1375 for (my $i=0; $i<@ns; ++$i) {
1376 next if class($ns[$i]) eq "SPECIAL";
1377 if (class($ns[$i]) eq "PV") {
1378 # Probably that pesky lexical @_
1381 my $name = $ns[$i]->PVX;
1382 my ($seq_st, $seq_en) =
1383 ($ns[$i]->FLAGS & SVf_FAKE)
1385 : ($ns[$i]->COP_SEQ_RANGE_LOW, $ns[$i]->COP_SEQ_RANGE_HIGH);
1387 push @{$self->{'curcvlex'}{
1388 ($ns[$i]->FLAGS & SVpad_OUR ? 'o' : 'm') . $name
1389 }}, [$seq_st, $seq_en];
1394 sub find_scope_st { ((find_scope(@_))[0]); }
1395 sub find_scope_en { ((find_scope(@_))[1]); }
1397 # Recurses down the tree, looking for pad variable introductions and COPs
1399 my ($self, $op, $scope_st, $scope_en) = @_;
1400 carp("Undefined op in find_scope") if !defined $op;
1401 return ($scope_st, $scope_en) unless $op->flags & OPf_KIDS;
1404 while(my $op = shift @queue ) {
1405 for (my $o=$op->first; $$o; $o=$o->sibling) {
1406 if ($o->name =~ /^pad.v$/ && $o->private & OPpLVAL_INTRO) {
1407 my $s = int($self->padname_sv($o->targ)->COP_SEQ_RANGE_LOW);
1408 my $e = $self->padname_sv($o->targ)->COP_SEQ_RANGE_HIGH;
1409 $scope_st = $s if !defined($scope_st) || $s < $scope_st;
1410 $scope_en = $e if !defined($scope_en) || $e > $scope_en;
1411 return ($scope_st, $scope_en);
1413 elsif (is_state($o)) {
1414 my $c = $o->cop_seq;
1415 $scope_st = $c if !defined($scope_st) || $c < $scope_st;
1416 $scope_en = $c if !defined($scope_en) || $c > $scope_en;
1417 return ($scope_st, $scope_en);
1419 elsif ($o->flags & OPf_KIDS) {
1420 unshift (@queue, $o);
1425 return ($scope_st, $scope_en);
1428 # Returns a list of subs which should be inserted before the COP
1430 my ($self, $op, $out_seq) = @_;
1431 my $seq = $op->cop_seq;
1432 # If we have nephews, then our sequence number indicates
1433 # the cop_seq of the end of some sort of scope.
1434 if (class($op->sibling) ne "NULL" && $op->sibling->flags & OPf_KIDS
1435 and my $nseq = $self->find_scope_st($op->sibling) ) {
1438 $seq = $out_seq if defined($out_seq) && $out_seq < $seq;
1439 return $self->seq_subs($seq);
1443 my ($self, $seq) = @_;
1445 #push @text, "# ($seq)\n";
1447 return "" if !defined $seq;
1448 while (scalar(@{$self->{'subs_todo'}})
1449 and $seq > $self->{'subs_todo'}[0][0]) {
1450 push @text, $self->next_todo;
1455 sub _features_from_bundle {
1456 my ($hints, $hh) = @_;
1457 foreach (@{$feature::feature_bundle{@feature::hint_bundles[$hints >> $feature::hint_shift]}}) {
1458 $hh->{$feature::feature{$_}} = 1;
1463 # Notice how subs and formats are inserted between statements here;
1464 # also $[ assignments and pragmas.
1468 $self->{'curcop'} = $op;
1470 push @text, $self->cop_subs($op);
1471 my $stash = $op->stashpv;
1472 if ($stash ne $self->{'curstash'}) {
1473 push @text, "package $stash;\n";
1474 $self->{'curstash'} = $stash;
1477 if (OPpCONST_ARYBASE && $self->{'arybase'} != $op->arybase) {
1478 push @text, '$[ = '. $op->arybase .";\n";
1479 $self->{'arybase'} = $op->arybase;
1482 my $warnings = $op->warnings;
1484 if ($warnings->isa("B::SPECIAL") && $$warnings == 4) {
1485 $warning_bits = $warnings::Bits{"all"} & WARN_MASK;
1487 elsif ($warnings->isa("B::SPECIAL") && $$warnings == 5) {
1488 $warning_bits = $warnings::NONE;
1490 elsif ($warnings->isa("B::SPECIAL")) {
1491 $warning_bits = undef;
1494 $warning_bits = $warnings->PV & WARN_MASK;
1497 if (defined ($warning_bits) and
1498 !defined($self->{warnings}) || $self->{'warnings'} ne $warning_bits) {
1499 push @text, declare_warnings($self->{'warnings'}, $warning_bits);
1500 $self->{'warnings'} = $warning_bits;
1503 my $hints = $] < 5.008009 ? $op->private : $op->hints;
1504 my $old_hints = $self->{'hints'};
1505 if ($self->{'hints'} != $hints) {
1506 push @text, declare_hints($self->{'hints'}, $hints);
1507 $self->{'hints'} = $hints;
1512 $newhh = $op->hints_hash->HASH;
1515 if ($] >= 5.015006) {
1516 # feature bundle hints
1517 my $from = $old_hints & $feature::hint_mask;
1518 my $to = $ hints & $feature::hint_mask;
1520 if ($to == $feature::hint_mask) {
1521 if ($self->{'hinthash'}) {
1522 delete $self->{'hinthash'}{$_}
1523 for grep /^feature_/, keys %{$self->{'hinthash'}};
1525 else { $self->{'hinthash'} = {} }
1527 = _features_from_bundle($from, $self->{'hinthash'});
1531 $feature::hint_bundles[$to >> $feature::hint_shift];
1532 $bundle =~ s/(\d[13579])\z/$1+1/e; # 5.11 => 5.12
1533 push @text, "no feature;\n",
1534 "use feature ':$bundle';\n";
1540 push @text, declare_hinthash(
1541 $self->{'hinthash'}, $newhh,
1542 $self->{indent_size}, $self->{hints},
1544 $self->{'hinthash'} = $newhh;
1547 # This should go after of any branches that add statements, to
1548 # increase the chances that it refers to the same line it did in
1549 # the original program.
1550 if ($self->{'linenums'}) {
1551 push @text, "\f#line " . $op->line .
1552 ' "' . $op->file, qq'"\n';
1555 push @text, $op->label . ": " if $op->label;
1557 return join("", @text);
1560 sub declare_warnings {
1561 my ($from, $to) = @_;
1562 if (($to & WARN_MASK) eq (warnings::bits("all") & WARN_MASK)) {
1563 return "use warnings;\n";
1565 elsif (($to & WARN_MASK) eq ("\0"x length($to) & WARN_MASK)) {
1566 return "no warnings;\n";
1568 return "BEGIN {\${^WARNING_BITS} = ".perlstring($to)."}\n";
1572 my ($from, $to) = @_;
1573 my $use = $to & ~$from;
1574 my $no = $from & ~$to;
1576 for my $pragma (hint_pragmas($use)) {
1577 $decls .= "use $pragma;\n";
1579 for my $pragma (hint_pragmas($no)) {
1580 $decls .= "no $pragma;\n";
1585 # Internal implementation hints that the core sets automatically, so don't need
1586 # (or want) to be passed back to the user
1587 my %ignored_hints = (
1598 sub declare_hinthash {
1599 my ($from, $to, $indent, $hints) = @_;
1600 my $doing_features =
1601 ($hints & $feature::hint_mask) == $feature::hint_mask;
1604 my @unfeatures; # bugs?
1605 for my $key (sort keys %$to) {
1606 next if $ignored_hints{$key};
1607 my $is_feature = $key =~ /^feature_/ && $^V ge 5.15.6;
1608 next if $is_feature and not $doing_features;
1609 if (!exists $from->{$key} or $from->{$key} ne $to->{$key}) {
1610 push(@features, $key), next if $is_feature;
1612 qq(\$^H{) . single_delim("q", "'", $key) . qq(} = )
1615 ? single_delim("q", "'", $to->{$key})
1621 for my $key (sort keys %$from) {
1622 next if $ignored_hints{$key};
1623 my $is_feature = $key =~ /^feature_/ && $^V ge 5.15.6;
1624 next if $is_feature and not $doing_features;
1625 if (!exists $to->{$key}) {
1626 push(@unfeatures, $key), next if $is_feature;
1627 push @decls, qq(delete \$^H{'$key'};);
1631 if (@features || @unfeatures) {
1632 if (!%rev_feature) { %rev_feature = reverse %feature::feature }
1635 push @ret, "use feature "
1636 . join(", ", map "'$rev_feature{$_}'", @features) . ";\n";
1639 push @ret, "no feature "
1640 . join(", ", map "'$rev_feature{$_}'", @unfeatures)
1645 join("\n" . (" " x $indent), "BEGIN {", @decls) . "\n}\n";
1651 my (@pragmas, @strict);
1652 push @pragmas, "integer" if $bits & 0x1;
1653 for (sort keys %strict_bits) {
1654 push @strict, "'$_'" if $bits & $strict_bits{$_};
1656 if (@strict == keys %strict_bits) {
1657 push @pragmas, "strict";
1660 push @pragmas, "strict " . join ', ', @strict;
1662 push @pragmas, "bytes" if $bits & 0x8;
1666 sub pp_dbstate { pp_nextstate(@_) }
1667 sub pp_setstate { pp_nextstate(@_) }
1669 sub pp_unstack { return "" } # see also leaveloop
1671 my %feature_keywords = (
1672 # keyword => 'feature',
1677 default => 'switch',
1679 evalbytes=>'evalbytes',
1680 __SUB__ => '__SUB__',
1684 # keywords that are strong and also have a prototype
1686 my %strong_proto_keywords = map { $_ => 1 } qw(
1698 return $name if $name =~ /^CORE::/; # just in case
1699 if (exists $feature_keywords{$name}) {
1701 my $hints = $self->{hints} & $feature::hint_mask;
1702 if ($hints && $hints != $feature::hint_mask) {
1703 $hh = _features_from_bundle($hints);
1705 elsif ($hints) { $hh = $self->{'hinthash'} }
1706 return "CORE::$name"
1708 || !$hh->{"feature_$feature_keywords{$name}"}
1710 if ($strong_proto_keywords{$name}
1711 || ($name !~ /^(?:chom?p|do|exec|glob|s(?:elect|ystem))\z/
1712 && !defined eval{prototype "CORE::$name"})
1715 exists $self->{subs_declared}{$name}
1717 exists &{"$self->{curstash}::$name"}
1719 return "CORE::$name"
1726 my($op, $cx, $name) = @_;
1727 return $self->keyword($name);
1732 my($op, $cx, $name) = @_;
1740 sub pp_wantarray { baseop(@_, "wantarray") }
1741 sub pp_fork { baseop(@_, "fork") }
1742 sub pp_wait { maybe_targmy(@_, \&baseop, "wait") }
1743 sub pp_getppid { maybe_targmy(@_, \&baseop, "getppid") }
1744 sub pp_time { maybe_targmy(@_, \&baseop, "time") }
1745 sub pp_tms { baseop(@_, "times") }
1746 sub pp_ghostent { baseop(@_, "gethostent") }
1747 sub pp_gnetent { baseop(@_, "getnetent") }
1748 sub pp_gprotoent { baseop(@_, "getprotoent") }
1749 sub pp_gservent { baseop(@_, "getservent") }
1750 sub pp_ehostent { baseop(@_, "endhostent") }
1751 sub pp_enetent { baseop(@_, "endnetent") }
1752 sub pp_eprotoent { baseop(@_, "endprotoent") }
1753 sub pp_eservent { baseop(@_, "endservent") }
1754 sub pp_gpwent { baseop(@_, "getpwent") }
1755 sub pp_spwent { baseop(@_, "setpwent") }
1756 sub pp_epwent { baseop(@_, "endpwent") }
1757 sub pp_ggrent { baseop(@_, "getgrent") }
1758 sub pp_sgrent { baseop(@_, "setgrent") }
1759 sub pp_egrent { baseop(@_, "endgrent") }
1760 sub pp_getlogin { baseop(@_, "getlogin") }
1762 sub POSTFIX () { 1 }
1764 # I couldn't think of a good short name, but this is the category of
1765 # symbolic unary operators with interesting precedence
1769 my($op, $cx, $name, $prec, $flags) = (@_, 0);
1770 my $kid = $op->first;
1771 $kid = $self->deparse($kid, $prec);
1772 return $self->maybe_parens(($flags & POSTFIX)
1774 # avoid confusion with filetests
1776 && $kid =~ /^[a-zA-Z](?!\w)/
1782 sub pp_preinc { pfixop(@_, "++", 23) }
1783 sub pp_predec { pfixop(@_, "--", 23) }
1784 sub pp_postinc { maybe_targmy(@_, \&pfixop, "++", 23, POSTFIX) }
1785 sub pp_postdec { maybe_targmy(@_, \&pfixop, "--", 23, POSTFIX) }
1786 sub pp_i_preinc { pfixop(@_, "++", 23) }
1787 sub pp_i_predec { pfixop(@_, "--", 23) }
1788 sub pp_i_postinc { maybe_targmy(@_, \&pfixop, "++", 23, POSTFIX) }
1789 sub pp_i_postdec { maybe_targmy(@_, \&pfixop, "--", 23, POSTFIX) }
1790 sub pp_complement { maybe_targmy(@_, \&pfixop, "~", 21) }
1792 sub pp_negate { maybe_targmy(@_, \&real_negate) }
1796 if ($op->first->name =~ /^(i_)?negate$/) {
1798 $self->pfixop($op, $cx, "-", 21.5);
1800 $self->pfixop($op, $cx, "-", 21);
1803 sub pp_i_negate { pp_negate(@_) }
1809 $self->listop($op, $cx, "not", $op->first);
1811 $self->pfixop($op, $cx, "!", 21);
1817 my($op, $cx, $name, $nollafr) = @_;
1819 if ($op->flags & OPf_KIDS) {
1822 # this deals with 'boolkeys' right now
1823 return $self->deparse($kid,$cx);
1825 my $builtinname = $name;
1826 $builtinname =~ /^CORE::/ or $builtinname = "CORE::$name";
1827 if (defined prototype($builtinname)
1828 && prototype($builtinname) =~ /^;?\*/
1829 && $kid->name eq "rv2gv") {
1834 ($kid = $self->deparse($kid, 16)) =~ s/^\cS//;
1835 return $self->maybe_parens(
1836 $self->keyword($name) . " $kid", $cx, 16
1839 return $self->maybe_parens_unop($name, $kid, $cx);
1841 return $self->maybe_parens(
1842 $self->keyword($name) . ($op->flags & OPf_SPECIAL ? "()" : ""),
1848 sub pp_chop { maybe_targmy(@_, \&unop, "chop") }
1849 sub pp_chomp { maybe_targmy(@_, \&unop, "chomp") }
1850 sub pp_schop { maybe_targmy(@_, \&unop, "chop") }
1851 sub pp_schomp { maybe_targmy(@_, \&unop, "chomp") }
1852 sub pp_defined { unop(@_, "defined") }
1853 sub pp_undef { unop(@_, "undef") }
1854 sub pp_study { unop(@_, "study") }
1855 sub pp_ref { unop(@_, "ref") }
1856 sub pp_pos { maybe_local(@_, unop(@_, "pos")) }
1858 sub pp_sin { maybe_targmy(@_, \&unop, "sin") }
1859 sub pp_cos { maybe_targmy(@_, \&unop, "cos") }
1860 sub pp_rand { maybe_targmy(@_, \&unop, "rand") }
1861 sub pp_srand { unop(@_, "srand") }
1862 sub pp_exp { maybe_targmy(@_, \&unop, "exp") }
1863 sub pp_log { maybe_targmy(@_, \&unop, "log") }
1864 sub pp_sqrt { maybe_targmy(@_, \&unop, "sqrt") }
1865 sub pp_int { maybe_targmy(@_, \&unop, "int") }
1866 sub pp_hex { maybe_targmy(@_, \&unop, "hex") }
1867 sub pp_oct { maybe_targmy(@_, \&unop, "oct") }
1868 sub pp_abs { maybe_targmy(@_, \&unop, "abs") }
1870 sub pp_length { maybe_targmy(@_, \&unop, "length") }
1871 sub pp_ord { maybe_targmy(@_, \&unop, "ord") }
1872 sub pp_chr { maybe_targmy(@_, \&unop, "chr") }
1874 sub pp_each { unop(@_, "each") }
1875 sub pp_values { unop(@_, "values") }
1876 sub pp_keys { unop(@_, "keys") }
1877 { no strict 'refs'; *{"pp_r$_"} = *{"pp_$_"} for qw< keys each values >; }
1879 # no name because its an optimisation op that has no keyword
1882 sub pp_aeach { unop(@_, "each") }
1883 sub pp_avalues { unop(@_, "values") }
1884 sub pp_akeys { unop(@_, "keys") }
1885 sub pp_pop { unop(@_, "pop") }
1886 sub pp_shift { unop(@_, "shift") }
1888 sub pp_caller { unop(@_, "caller") }
1889 sub pp_reset { unop(@_, "reset") }
1890 sub pp_exit { unop(@_, "exit") }
1891 sub pp_prototype { unop(@_, "prototype") }
1893 sub pp_close { unop(@_, "close") }
1894 sub pp_fileno { unop(@_, "fileno") }
1895 sub pp_umask { unop(@_, "umask") }
1896 sub pp_untie { unop(@_, "untie") }
1897 sub pp_tied { unop(@_, "tied") }
1898 sub pp_dbmclose { unop(@_, "dbmclose") }
1899 sub pp_getc { unop(@_, "getc") }
1900 sub pp_eof { unop(@_, "eof") }
1901 sub pp_tell { unop(@_, "tell") }
1902 sub pp_getsockname { unop(@_, "getsockname") }
1903 sub pp_getpeername { unop(@_, "getpeername") }
1905 sub pp_chdir { maybe_targmy(@_, \&unop, "chdir") }
1906 sub pp_chroot { maybe_targmy(@_, \&unop, "chroot") }
1907 sub pp_readlink { unop(@_, "readlink") }
1908 sub pp_rmdir { maybe_targmy(@_, \&unop, "rmdir") }
1909 sub pp_readdir { unop(@_, "readdir") }
1910 sub pp_telldir { unop(@_, "telldir") }
1911 sub pp_rewinddir { unop(@_, "rewinddir") }
1912 sub pp_closedir { unop(@_, "closedir") }
1913 sub pp_getpgrp { maybe_targmy(@_, \&unop, "getpgrp") }
1914 sub pp_localtime { unop(@_, "localtime") }
1915 sub pp_gmtime { unop(@_, "gmtime") }
1916 sub pp_alarm { unop(@_, "alarm") }
1917 sub pp_sleep { maybe_targmy(@_, \&unop, "sleep") }
1920 my $code = unop(@_, "do", 1); # llafr does not apply
1921 if ($code =~ s/^((?:CORE::)?do) \{/$1({/) { $code .= ')' }
1927 $_[1]->private & OPpEVAL_BYTES ? $_[0]->keyword('evalbytes') : "eval"
1931 sub pp_ghbyname { unop(@_, "gethostbyname") }
1932 sub pp_gnbyname { unop(@_, "getnetbyname") }
1933 sub pp_gpbyname { unop(@_, "getprotobyname") }
1934 sub pp_shostent { unop(@_, "sethostent") }
1935 sub pp_snetent { unop(@_, "setnetent") }
1936 sub pp_sprotoent { unop(@_, "setprotoent") }
1937 sub pp_sservent { unop(@_, "setservent") }
1938 sub pp_gpwnam { unop(@_, "getpwnam") }
1939 sub pp_gpwuid { unop(@_, "getpwuid") }
1940 sub pp_ggrnam { unop(@_, "getgrnam") }
1941 sub pp_ggrgid { unop(@_, "getgrgid") }
1943 sub pp_lock { unop(@_, "lock") }
1945 sub pp_continue { unop(@_, "continue"); }
1946 sub pp_break { unop(@_, "break"); }
1950 my($op, $cx, $givwhen) = @_;
1952 my $enterop = $op->first;
1954 if ($enterop->flags & OPf_SPECIAL) {
1955 $head = $self->keyword("default");
1956 $block = $self->deparse($enterop->first, 0);
1959 my $cond = $enterop->first;
1960 my $cond_str = $self->deparse($cond, 1);
1961 $head = "$givwhen ($cond_str)";
1962 $block = $self->deparse($cond->sibling, 0);
1970 sub pp_leavegiven { givwhen(@_, $_[0]->keyword("given")); }
1971 sub pp_leavewhen { givwhen(@_, $_[0]->keyword("when")); }
1977 if ($op->private & OPpEXISTS_SUB) {
1978 # Checking for the existence of a subroutine
1979 return $self->maybe_parens_func("exists",
1980 $self->pp_rv2cv($op->first, 16), $cx, 16);
1982 if ($op->flags & OPf_SPECIAL) {
1983 # Array element, not hash element
1984 return $self->maybe_parens_func("exists",
1985 $self->pp_aelem($op->first, 16), $cx, 16);
1987 return $self->maybe_parens_func("exists", $self->pp_helem($op->first, 16),
1995 if ($op->private & OPpSLICE) {
1996 if ($op->flags & OPf_SPECIAL) {
1997 # Deleting from an array, not a hash
1998 return $self->maybe_parens_func("delete",
1999 $self->pp_aslice($op->first, 16),
2002 return $self->maybe_parens_func("delete",
2003 $self->pp_hslice($op->first, 16),
2006 if ($op->flags & OPf_SPECIAL) {
2007 # Deleting from an array, not a hash
2008 return $self->maybe_parens_func("delete",
2009 $self->pp_aelem($op->first, 16),
2012 return $self->maybe_parens_func("delete",
2013 $self->pp_helem($op->first, 16),
2021 my $opname = $op->flags & OPf_SPECIAL ? 'CORE::require' : 'require';
2022 if (class($op) eq "UNOP" and $op->first->name eq "const"
2023 and $op->first->private & OPpCONST_BARE)
2025 my $name = $self->const_sv($op->first)->PV;
2028 return $self->maybe_parens("$opname $name", $cx, 16);
2032 $op->first->name eq 'const'
2033 && $op->first->private & OPpCONST_NOVER
2036 1, # llafr does not apply
2044 my $kid = $op->first;
2045 if (not null $kid->sibling) {
2046 # XXX Was a here-doc
2047 return $self->dquote($op);
2049 $self->unop(@_, "scalar");
2056 return $self->{'curcv'}->PADLIST->ARRAYelt(1)->ARRAYelt($targ);
2059 sub anon_hash_or_list {
2063 my($pre, $post) = @{{"anonlist" => ["[","]"],
2064 "anonhash" => ["{","}"]}->{$op->name}};
2066 $op = $op->first->sibling; # skip pushmark
2067 for (; !null($op); $op = $op->sibling) {
2068 $expr = $self->deparse($op, 6);
2071 if ($pre eq "{" and $cx < 1) {
2072 # Disambiguate that it's not a block
2075 return $pre . join(", ", @exprs) . $post;
2081 if ($op->flags & OPf_SPECIAL) {
2082 return $self->anon_hash_or_list($op, $cx);
2084 warn "Unexpected op pp_" . $op->name() . " without OPf_SPECIAL";
2088 *pp_anonhash = \&pp_anonlist;
2093 my $kid = $op->first;
2094 if ($kid->name eq "null") {
2096 if (!null($kid->sibling) and
2097 $kid->sibling->name eq "anoncode") {
2098 return $self->e_anoncode({ code => $self->padval($kid->sibling->targ) });
2099 } elsif ($kid->name eq "pushmark") {
2100 my $sib_name = $kid->sibling->name;
2101 if ($sib_name =~ /^(pad|rv2)[ah]v$/
2102 and not $kid->sibling->flags & OPf_REF)
2104 # The @a in \(@a) isn't in ref context, but only when the
2106 return "\\(" . $self->pp_list($op->first) . ")";
2107 } elsif ($sib_name eq 'entersub') {
2108 my $text = $self->deparse($kid->sibling, 1);
2109 # Always show parens for \(&func()), but only with -p otherwise
2110 $text = "($text)" if $self->{'parens'}
2111 or $kid->sibling->private & OPpENTERSUB_AMPER;
2116 $self->pfixop($op, $cx, "\\", 20);
2120 my ($self, $info) = @_;
2121 my $text = $self->deparse_sub($info->{code});
2122 return "sub " . $text;
2125 sub pp_srefgen { pp_refgen(@_) }
2130 my $kid = $op->first;
2131 $kid = $kid->first if $kid->name eq "rv2gv"; # <$fh>
2132 return "<" . $self->deparse($kid, 1) . ">" if is_scalar($kid);
2133 return $self->unop($op, $cx, "readline");
2139 return "<" . $self->gv_name($self->gv_or_padgv($op)) . ">";
2142 # Unary operators that can occur as pseudo-listops inside double quotes
2145 my($op, $cx, $name, $prec, $flags) = (@_, 0, 0);
2147 if ($op->flags & OPf_KIDS) {
2149 # If there's more than one kid, the first is an ex-pushmark.
2150 $kid = $kid->sibling if not null $kid->sibling;
2151 return $self->maybe_parens_unop($name, $kid, $cx);
2153 return $name . ($op->flags & OPf_SPECIAL ? "()" : "");
2157 sub pp_ucfirst { dq_unop(@_, "ucfirst") }
2158 sub pp_lcfirst { dq_unop(@_, "lcfirst") }
2159 sub pp_uc { dq_unop(@_, "uc") }
2160 sub pp_lc { dq_unop(@_, "lc") }
2161 sub pp_quotemeta { maybe_targmy(@_, \&dq_unop, "quotemeta") }
2162 sub pp_fc { dq_unop(@_, "fc") }
2166 my ($op, $cx, $name) = @_;
2167 if (class($op) eq "PVOP") {
2168 $name .= " " . $op->pv;
2169 } elsif (class($op) eq "OP") {
2171 } elsif (class($op) eq "UNOP") {
2172 (my $kid = $self->deparse($op->first, 7)) =~ s/^\cS//;
2175 return $self->maybe_parens($name, $cx, 7);
2178 sub pp_last { loopex(@_, "last") }
2179 sub pp_next { loopex(@_, "next") }
2180 sub pp_redo { loopex(@_, "redo") }
2181 sub pp_goto { loopex(@_, "goto") }
2182 sub pp_dump { loopex(@_, "CORE::dump") }
2186 my($op, $cx, $name) = @_;
2187 if (class($op) eq "UNOP") {
2188 # Genuine '-X' filetests are exempt from the LLAFR, but not
2190 if ($name =~ /^-/) {
2191 (my $kid = $self->deparse($op->first, 16)) =~ s/^\cS//;
2192 return $self->maybe_parens("$name $kid", $cx, 16);
2194 return $self->maybe_parens_unop($name, $op->first, $cx);
2195 } elsif (class($op) =~ /^(SV|PAD)OP$/) {
2196 return $self->maybe_parens_func($name, $self->pp_gv($op, 1), $cx, 16);
2197 } else { # I don't think baseop filetests ever survive ck_ftst, but...
2202 sub pp_lstat { ftst(@_, "lstat") }
2203 sub pp_stat { ftst(@_, "stat") }
2204 sub pp_ftrread { ftst(@_, "-R") }
2205 sub pp_ftrwrite { ftst(@_, "-W") }
2206 sub pp_ftrexec { ftst(@_, "-X") }
2207 sub pp_fteread { ftst(@_, "-r") }
2208 sub pp_ftewrite { ftst(@_, "-w") }
2209 sub pp_fteexec { ftst(@_, "-x") }
2210 sub pp_ftis { ftst(@_, "-e") }
2211 sub pp_fteowned { ftst(@_, "-O") }
2212 sub pp_ftrowned { ftst(@_, "-o") }
2213 sub pp_ftzero { ftst(@_, "-z") }
2214 sub pp_ftsize { ftst(@_, "-s") }
2215 sub pp_ftmtime { ftst(@_, "-M") }
2216 sub pp_ftatime { ftst(@_, "-A") }
2217 sub pp_ftctime { ftst(@_, "-C") }
2218 sub pp_ftsock { ftst(@_, "-S") }
2219 sub pp_ftchr { ftst(@_, "-c") }
2220 sub pp_ftblk { ftst(@_, "-b") }
2221 sub pp_ftfile { ftst(@_, "-f") }
2222 sub pp_ftdir { ftst(@_, "-d") }
2223 sub pp_ftpipe { ftst(@_, "-p") }
2224 sub pp_ftlink { ftst(@_, "-l") }
2225 sub pp_ftsuid { ftst(@_, "-u") }
2226 sub pp_ftsgid { ftst(@_, "-g") }
2227 sub pp_ftsvtx { ftst(@_, "-k") }
2228 sub pp_fttty { ftst(@_, "-t") }
2229 sub pp_fttext { ftst(@_, "-T") }
2230 sub pp_ftbinary { ftst(@_, "-B") }
2232 sub SWAP_CHILDREN () { 1 }
2233 sub ASSIGN () { 2 } # has OP= variant
2234 sub LIST_CONTEXT () { 4 } # Assignment is in list context
2240 my $name = $op->name;
2241 if ($name eq "concat" and $op->first->name eq "concat") {
2242 # avoid spurious '=' -- see comment in pp_concat
2245 if ($name eq "null" and class($op) eq "UNOP"
2246 and $op->first->name =~ /^(and|x?or)$/
2247 and null $op->first->sibling)
2249 # Like all conditional constructs, OP_ANDs and OP_ORs are topped
2250 # with a null that's used as the common end point of the two
2251 # flows of control. For precedence purposes, ignore it.
2252 # (COND_EXPRs have these too, but we don't bother with
2253 # their associativity).
2254 return assoc_class($op->first);
2256 return $name . ($op->flags & OPf_STACKED ? "=" : "");
2259 # Left associative operators, like '+', for which
2260 # $a + $b + $c is equivalent to ($a + $b) + $c
2263 %left = ('multiply' => 19, 'i_multiply' => 19,
2264 'divide' => 19, 'i_divide' => 19,
2265 'modulo' => 19, 'i_modulo' => 19,
2267 'add' => 18, 'i_add' => 18,
2268 'subtract' => 18, 'i_subtract' => 18,
2270 'left_shift' => 17, 'right_shift' => 17,
2272 'bit_or' => 12, 'bit_xor' => 12,
2274 'or' => 2, 'xor' => 2,
2278 sub deparse_binop_left {
2280 my($op, $left, $prec) = @_;
2281 if ($left{assoc_class($op)} && $left{assoc_class($left)}
2282 and $left{assoc_class($op)} == $left{assoc_class($left)})
2284 return $self->deparse($left, $prec - .00001);
2286 return $self->deparse($left, $prec);
2290 # Right associative operators, like '=', for which
2291 # $a = $b = $c is equivalent to $a = ($b = $c)
2294 %right = ('pow' => 22,
2295 'sassign=' => 7, 'aassign=' => 7,
2296 'multiply=' => 7, 'i_multiply=' => 7,
2297 'divide=' => 7, 'i_divide=' => 7,
2298 'modulo=' => 7, 'i_modulo=' => 7,
2300 'add=' => 7, 'i_add=' => 7,
2301 'subtract=' => 7, 'i_subtract=' => 7,
2303 'left_shift=' => 7, 'right_shift=' => 7,
2305 'bit_or=' => 7, 'bit_xor=' => 7,
2311 sub deparse_binop_right {
2313 my($op, $right, $prec) = @_;
2314 if ($right{assoc_class($op)} && $right{assoc_class($right)}
2315 and $right{assoc_class($op)} == $right{assoc_class($right)})
2317 return $self->deparse($right, $prec - .00001);
2319 return $self->deparse($right, $prec);
2325 my ($op, $cx, $opname, $prec, $flags) = (@_, 0);
2326 my $left = $op->first;
2327 my $right = $op->last;
2329 if ($op->flags & OPf_STACKED && $flags & ASSIGN) {
2333 if ($flags & SWAP_CHILDREN) {
2334 ($left, $right) = ($right, $left);
2336 $left = $self->deparse_binop_left($op, $left, $prec);
2337 $left = "($left)" if $flags & LIST_CONTEXT
2338 && $left !~ /^(my|our|local|)[\@\(]/;
2339 $right = $self->deparse_binop_right($op, $right, $prec);
2340 return $self->maybe_parens("$left $opname$eq $right", $cx, $prec);
2343 sub pp_add { maybe_targmy(@_, \&binop, "+", 18, ASSIGN) }
2344 sub pp_multiply { maybe_targmy(@_, \&binop, "*", 19, ASSIGN) }
2345 sub pp_subtract { maybe_targmy(@_, \&binop, "-",18, ASSIGN) }
2346 sub pp_divide { maybe_targmy(@_, \&binop, "/", 19, ASSIGN) }
2347 sub pp_modulo { maybe_targmy(@_, \&binop, "%", 19, ASSIGN) }
2348 sub pp_i_add { maybe_targmy(@_, \&binop, "+", 18, ASSIGN) }
2349 sub pp_i_multiply { maybe_targmy(@_, \&binop, "*", 19, ASSIGN) }
2350 sub pp_i_subtract { maybe_targmy(@_, \&binop, "-", 18, ASSIGN) }
2351 sub pp_i_divide { maybe_targmy(@_, \&binop, "/", 19, ASSIGN) }
2352 sub pp_i_modulo { maybe_targmy(@_, \&binop, "%", 19, ASSIGN) }
2353 sub pp_pow { maybe_targmy(@_, \&binop, "**", 22, ASSIGN) }
2355 sub pp_left_shift { maybe_targmy(@_, \&binop, "<<", 17, ASSIGN) }
2356 sub pp_right_shift { maybe_targmy(@_, \&binop, ">>", 17, ASSIGN) }
2357 sub pp_bit_and { maybe_targmy(@_, \&binop, "&", 13, ASSIGN) }
2358 sub pp_bit_or { maybe_targmy(@_, \&binop, "|", 12, ASSIGN) }
2359 sub pp_bit_xor { maybe_targmy(@_, \&binop, "^", 12, ASSIGN) }
2361 sub pp_eq { binop(@_, "==", 14) }
2362 sub pp_ne { binop(@_, "!=", 14) }
2363 sub pp_lt { binop(@_, "<", 15) }
2364 sub pp_gt { binop(@_, ">", 15) }
2365 sub pp_ge { binop(@_, ">=", 15) }
2366 sub pp_le { binop(@_, "<=", 15) }
2367 sub pp_ncmp { binop(@_, "<=>", 14) }
2368 sub pp_i_eq { binop(@_, "==", 14) }
2369 sub pp_i_ne { binop(@_, "!=", 14) }
2370 sub pp_i_lt { binop(@_, "<", 15) }
2371 sub pp_i_gt { binop(@_, ">", 15) }
2372 sub pp_i_ge { binop(@_, ">=", 15) }
2373 sub pp_i_le { binop(@_, "<=", 15) }
2374 sub pp_i_ncmp { binop(@_, "<=>", 14) }
2376 sub pp_seq { binop(@_, "eq", 14) }
2377 sub pp_sne { binop(@_, "ne", 14) }
2378 sub pp_slt { binop(@_, "lt", 15) }
2379 sub pp_sgt { binop(@_, "gt", 15) }
2380 sub pp_sge { binop(@_, "ge", 15) }
2381 sub pp_sle { binop(@_, "le", 15) }
2382 sub pp_scmp { binop(@_, "cmp", 14) }
2384 sub pp_sassign { binop(@_, "=", 7, SWAP_CHILDREN) }
2385 sub pp_aassign { binop(@_, "=", 7, SWAP_CHILDREN | LIST_CONTEXT) }
2388 my ($self, $op, $cx) = @_;
2389 if ($op->flags & OPf_SPECIAL) {
2390 return $self->deparse($op->last, $cx);
2393 binop(@_, "~~", 14);
2397 # '.' is special because concats-of-concats are optimized to save copying
2398 # by making all but the first concat stacked. The effect is as if the
2399 # programmer had written '($a . $b) .= $c', except legal.
2400 sub pp_concat { maybe_targmy(@_, \&real_concat) }
2404 my $left = $op->first;
2405 my $right = $op->last;
2408 if ($op->flags & OPf_STACKED and $op->first->name ne "concat") {
2412 $left = $self->deparse_binop_left($op, $left, $prec);
2413 $right = $self->deparse_binop_right($op, $right, $prec);
2414 return $self->maybe_parens("$left .$eq $right", $cx, $prec);
2417 # 'x' is weird when the left arg is a list
2421 my $left = $op->first;
2422 my $right = $op->last;
2425 if ($op->flags & OPf_STACKED) {
2429 if (null($right)) { # list repeat; count is inside left-side ex-list
2430 my $kid = $left->first->sibling; # skip pushmark
2432 for (; !null($kid->sibling); $kid = $kid->sibling) {
2433 push @exprs, $self->deparse($kid, 6);
2436 $left = "(" . join(", ", @exprs). ")";
2438 $left = $self->deparse_binop_left($op, $left, $prec);
2440 $right = $self->deparse_binop_right($op, $right, $prec);
2441 return $self->maybe_parens("$left x$eq $right", $cx, $prec);
2446 my ($op, $cx, $type) = @_;
2447 my $left = $op->first;
2448 my $right = $left->sibling;
2449 $left = $self->deparse($left, 9);
2450 $right = $self->deparse($right, 9);
2451 return $self->maybe_parens("$left $type $right", $cx, 9);
2457 my $flip = $op->first;
2458 my $type = ($flip->flags & OPf_SPECIAL) ? "..." : "..";
2459 return $self->range($flip->first, $cx, $type);
2462 # one-line while/until is handled in pp_leave
2466 my ($op, $cx, $lowop, $lowprec, $highop, $highprec, $blockname) = @_;
2467 my $left = $op->first;
2468 my $right = $op->first->sibling;
2469 if ($cx < 1 and is_scope($right) and $blockname
2470 and $self->{'expand'} < 7)
2472 $left = $self->deparse($left, 1);
2473 $right = $self->deparse($right, 0);
2474 return "$blockname ($left) {\n\t$right\n\b}\cK";
2475 } elsif ($cx < 1 and $blockname and not $self->{'parens'}
2476 and $self->{'expand'} < 7) { # $b if $a
2477 $right = $self->deparse($right, 1);
2478 $left = $self->deparse($left, 1);
2479 return "$right $blockname $left";
2480 } elsif ($cx > $lowprec and $highop) { # $a && $b
2481 $left = $self->deparse_binop_left($op, $left, $highprec);
2482 $right = $self->deparse_binop_right($op, $right, $highprec);
2483 return $self->maybe_parens("$left $highop $right", $cx, $highprec);
2484 } else { # $a and $b
2485 $left = $self->deparse_binop_left($op, $left, $lowprec);
2486 $right = $self->deparse_binop_right($op, $right, $lowprec);
2487 return $self->maybe_parens("$left $lowop $right", $cx, $lowprec);
2491 sub pp_and { logop(@_, "and", 3, "&&", 11, "if") }
2492 sub pp_or { logop(@_, "or", 2, "||", 10, "unless") }
2493 sub pp_dor { logop(@_, "//", 10) }
2495 # xor is syntactically a logop, but it's really a binop (contrary to
2496 # old versions of opcode.pl). Syntax is what matters here.
2497 sub pp_xor { logop(@_, "xor", 2, "", 0, "") }
2501 my ($op, $cx, $opname) = @_;
2502 my $left = $op->first;
2503 my $right = $op->first->sibling->first; # skip sassign
2504 $left = $self->deparse($left, 7);
2505 $right = $self->deparse($right, 7);
2506 return $self->maybe_parens("$left $opname $right", $cx, 7);
2509 sub pp_andassign { logassignop(@_, "&&=") }
2510 sub pp_orassign { logassignop(@_, "||=") }
2511 sub pp_dorassign { logassignop(@_, "//=") }
2513 sub rv2gv_or_string {
2515 if ($op->name eq "gv") { # could be open("open") or open("###")
2517 $self->stash_variable_name("", $self->gv_or_padgv($op));
2518 $quoted ? $name : "*$name";
2521 $self->deparse($op, 6);
2527 my($op, $cx, $name, $kid, $nollafr) = @_;
2529 my $parens = ($cx >= 5) || $self->{'parens'};
2530 $kid ||= $op->first->sibling;
2531 # If there are no arguments, add final parentheses (or parenthesize the
2532 # whole thing if the llafr does not apply) to account for cases like
2533 # (return)+1 or setpgrp()+1. When the llafr does not apply, we use a
2534 # precedence of 6 (< comma), as "return, 1" does not need parentheses.
2537 ? $self->maybe_parens($self->keyword($name), $cx, 7)
2538 : $self->keyword($name) . '()' x (7 < $cx);
2541 $name = "socketpair" if $name eq "sockpair";
2542 my $fullname = $self->keyword($name);
2543 my $proto = prototype("CORE::$name");
2545 && $proto =~ /^;?\*/
2546 && $kid->name eq "rv2gv" && !($kid->private & OPpLVAL_INTRO)) {
2547 $first = $self->rv2gv_or_string($kid->first);
2550 $first = $self->deparse($kid, 6);
2552 if ($name eq "chmod" && $first =~ /^\d+$/) {
2553 $first = sprintf("%#o", $first);
2556 if not $parens and not $nollafr and substr($first, 0, 1) eq "(";
2557 push @exprs, $first;
2558 $kid = $kid->sibling;
2559 if (defined $proto && $proto =~ /^\*\*/ && $kid->name eq "rv2gv"
2560 && !($kid->private & OPpLVAL_INTRO)) {
2561 push @exprs, $first = $self->rv2gv_or_string($kid->first);
2562 $kid = $kid->sibling;
2564 for (; !null($kid); $kid = $kid->sibling) {
2565 push @exprs, $self->deparse($kid, 6);
2567 if ($name eq "reverse" && ($op->private & OPpREVERSE_INPLACE)) {
2568 return "$exprs[0] = $fullname"
2569 . ($parens ? "($exprs[0])" : " $exprs[0]");
2571 if ($name =~ /^(system|exec)$/
2572 && ($op->flags & OPf_STACKED)
2575 # handle the "system prog a1,a2,.." form
2576 my $prog = shift @exprs;
2577 $exprs[0] = "$prog $exprs[0]";
2580 if ($parens && $nollafr) {
2581 return "($fullname " . join(", ", @exprs) . ")";
2583 return "$fullname(" . join(", ", @exprs) . ")";
2585 return "$fullname " . join(", ", @exprs);
2589 sub pp_bless { listop(@_, "bless") }
2590 sub pp_atan2 { maybe_targmy(@_, \&listop, "atan2") }
2592 my ($self,$op,$cx) = @_;
2593 if ($op->private & OPpSUBSTR_REPL_FIRST) {
2595 listop($self, $op, 7, "substr", $op->first->sibling->sibling)
2597 . $self->deparse($op->first->sibling, 7);
2599 maybe_local(@_, listop(@_, "substr"))
2601 sub pp_vec { maybe_local(@_, listop(@_, "vec")) }
2602 sub pp_index { maybe_targmy(@_, \&listop, "index") }
2603 sub pp_rindex { maybe_targmy(@_, \&listop, "rindex") }
2604 sub pp_sprintf { maybe_targmy(@_, \&listop, "sprintf") }
2605 sub pp_formline { listop(@_, "formline") } # see also deparse_format
2606 sub pp_crypt { maybe_targmy(@_, \&listop, "crypt") }
2607 sub pp_unpack { listop(@_, "unpack") }
2608 sub pp_pack { listop(@_, "pack") }
2609 sub pp_join { maybe_targmy(@_, \&listop, "join") }
2610 sub pp_splice { listop(@_, "splice") }
2611 sub pp_push { maybe_targmy(@_, \&listop, "push") }
2612 sub pp_unshift { maybe_targmy(@_, \&listop, "unshift") }
2613 sub pp_reverse { listop(@_, "reverse") }
2614 sub pp_warn { listop(@_, "warn") }
2615 sub pp_die { listop(@_, "die") }
2616 sub pp_return { listop(@_, "return", undef, 1) } # llafr does not apply
2617 sub pp_open { listop(@_, "open") }
2618 sub pp_pipe_op { listop(@_, "pipe") }
2619 sub pp_tie { listop(@_, "tie") }
2620 sub pp_binmode { listop(@_, "binmode") }
2621 sub pp_dbmopen { listop(@_, "dbmopen") }
2622 sub pp_sselect { listop(@_, "select") }
2623 sub pp_select { listop(@_, "select") }
2624 sub pp_read { listop(@_, "read") }
2625 sub pp_sysopen { listop(@_, "sysopen") }
2626 sub pp_sysseek { listop(@_, "sysseek") }
2627 sub pp_sysread { listop(@_, "sysread") }
2628 sub pp_syswrite { listop(@_, "syswrite") }
2629 sub pp_send { listop(@_, "send") }
2630 sub pp_recv { listop(@_, "recv") }
2631 sub pp_seek { listop(@_, "seek") }
2632 sub pp_fcntl { listop(@_, "fcntl") }
2633 sub pp_ioctl { listop(@_, "ioctl") }
2634 sub pp_flock { maybe_targmy(@_, \&listop, "flock") }
2635 sub pp_socket { listop(@_, "socket") }
2636 sub pp_sockpair { listop(@_, "sockpair") }
2637 sub pp_bind { listop(@_, "bind") }
2638 sub pp_connect { listop(@_, "connect") }
2639 sub pp_listen { listop(@_, "listen") }
2640 sub pp_accept { listop(@_, "accept") }
2641 sub pp_shutdown { listop(@_, "shutdown") }
2642 sub pp_gsockopt { listop(@_, "getsockopt") }
2643 sub pp_ssockopt { listop(@_, "setsockopt") }
2644 sub pp_chown { maybe_targmy(@_, \&listop, "chown") }
2645 sub pp_unlink { maybe_targmy(@_, \&listop, "unlink") }
2646 sub pp_chmod { maybe_targmy(@_, \&listop, "chmod") }
2647 sub pp_utime { maybe_targmy(@_, \&listop, "utime") }
2648 sub pp_rename { maybe_targmy(@_, \&listop, "rename") }
2649 sub pp_link { maybe_targmy(@_, \&listop, "link") }
2650 sub pp_symlink { maybe_targmy(@_, \&listop, "symlink") }
2651 sub pp_mkdir { maybe_targmy(@_, \&listop, "mkdir") }
2652 sub pp_open_dir { listop(@_, "opendir") }
2653 sub pp_seekdir { listop(@_, "seekdir") }
2654 sub pp_waitpid { maybe_targmy(@_, \&listop, "waitpid") }
2655 sub pp_system { maybe_targmy(@_, \&listop, "system") }
2656 sub pp_exec { maybe_targmy(@_, \&listop, "exec") }
2657 sub pp_kill { maybe_targmy(@_, \&listop, "kill") }
2658 sub pp_setpgrp { maybe_targmy(@_, \&listop, "setpgrp") }
2659 sub pp_getpriority { maybe_targmy(@_, \&listop, "getpriority") }
2660 sub pp_setpriority { maybe_targmy(@_, \&listop, "setpriority") }
2661 sub pp_shmget { listop(@_, "shmget") }
2662 sub pp_shmctl { listop(@_, "shmctl") }
2663 sub pp_shmread { listop(@_, "shmread") }
2664 sub pp_shmwrite { listop(@_, "shmwrite") }
2665 sub pp_msgget { listop(@_, "msgget") }
2666 sub pp_msgctl { listop(@_, "msgctl") }
2667 sub pp_msgsnd { listop(@_, "msgsnd") }
2668 sub pp_msgrcv { listop(@_, "msgrcv") }
2669 sub pp_semget { listop(@_, "semget") }
2670 sub pp_semctl { listop(@_, "semctl") }
2671 sub pp_semop { listop(@_, "semop") }
2672 sub pp_ghbyaddr { listop(@_, "gethostbyaddr") }
2673 sub pp_gnbyaddr { listop(@_, "getnetbyaddr") }
2674 sub pp_gpbynumber { listop(@_, "getprotobynumber") }
2675 sub pp_gsbyname { listop(@_, "getservbyname") }
2676 sub pp_gsbyport { listop(@_, "getservbyport") }
2677 sub pp_syscall { listop(@_, "syscall") }
2682 my $text = $self->dq($op->first->sibling); # skip pushmark
2684 $op->flags & OPf_SPECIAL ? 'glob' : $self->keyword('glob');
2685 if ($text =~ /^\$?(\w|::|\`)+$/ # could look like a readline
2686 or $keyword =~ /^CORE::/
2687 or $text =~ /[<>]/) {
2688 return "$keyword(" . single_delim('qq', '"', $text) . ')';
2690 return '<' . $text . '>';
2694 # Truncate is special because OPf_SPECIAL makes a bareword first arg
2695 # be a filehandle. This could probably be better fixed in the core
2696 # by moving the GV lookup into ck_truc.
2702 my $parens = ($cx >= 5) || $self->{'parens'};
2703 my $kid = $op->first->sibling;
2705 if ($op->flags & OPf_SPECIAL) {
2706 # $kid is an OP_CONST
2707 $fh = $self->const_sv($kid)->PV;
2709 $fh = $self->deparse($kid, 6);
2710 $fh = "+$fh" if not $parens and substr($fh, 0, 1) eq "(";
2712 my $len = $self->deparse($kid->sibling, 6);
2713 my $name = $self->keyword('truncate');
2715 return "$name($fh, $len)";
2717 return "$name $fh, $len";
2723 my($op, $cx, $name) = @_;
2725 my $firstkid = my $kid = $op->first->sibling;
2727 if ($op->flags & OPf_STACKED) {
2729 $indir = $indir->first; # skip rv2gv
2730 if (is_scope($indir)) {
2731 $indir = "{" . $self->deparse($indir, 0) . "}";
2732 $indir = "{;}" if $indir eq "{}";
2733 } elsif ($indir->name eq "const" && $indir->private & OPpCONST_BARE) {
2734 $indir = $self->const_sv($indir)->PV;
2736 $indir = $self->deparse($indir, 24);
2738 $indir = $indir . " ";
2739 $kid = $kid->sibling;
2741 if ($name eq "sort" && $op->private & (OPpSORT_NUMERIC | OPpSORT_INTEGER)) {
2742 $indir = ($op->private & OPpSORT_DESCEND) ? '{$b <=> $a} '
2745 elsif ($name eq "sort" && $op->private & OPpSORT_DESCEND) {
2746 $indir = '{$b cmp $a} ';
2748 for (; !null($kid); $kid = $kid->sibling) {
2749 $expr = $self->deparse($kid, !$indir && $kid == $firstkid && $name eq "sort" && $firstkid->name eq "entersub" ? 16 : 6);
2753 if ($name eq "sort" && $op->private & OPpSORT_REVERSE) {
2754 $name2 = $self->keyword('reverse') . ' ' . $self->keyword('sort');
2756 else { $name2 = $self->keyword($name) }
2757 if ($name eq "sort" && ($op->private & OPpSORT_INPLACE)) {
2758 return "$exprs[0] = $name2 $indir $exprs[0]";
2761 my $args = $indir . join(", ", @exprs);
2762 if ($indir ne "" && $name eq "sort") {
2763 # We don't want to say "sort(f 1, 2, 3)", since perl -w will
2764 # give bareword warnings in that case. Therefore if context
2765 # requires, we'll put parens around the outside "(sort f 1, 2,
2766 # 3)". Unfortunately, we'll currently think the parens are
2767 # necessary more often that they really are, because we don't
2768 # distinguish which side of an assignment we're on.
2770 return "($name2 $args)";
2772 return "$name2 $args";
2775 !$indir && $name eq "sort"
2776 && !null($op->first->sibling)
2777 && $op->first->sibling->name eq 'entersub'
2779 # We cannot say sort foo(bar), as foo will be interpreted as a
2780 # comparison routine. We have to say sort(...) in that case.
2781 return "$name2($args)";
2783 return $self->maybe_parens_func($name2, $args, $cx, 5);
2788 sub pp_prtf { indirop(@_, "printf") }
2789 sub pp_print { indirop(@_, "print") }
2790 sub pp_say { indirop(@_, "say") }
2791 sub pp_sort { indirop(@_, "sort") }
2795 my($op, $cx, $name) = @_;
2797 my $kid = $op->first; # this is the (map|grep)start
2798 $kid = $kid->first->sibling; # skip a pushmark
2799 my $code = $kid->first; # skip a null
2800 if (is_scope $code) {
2801 $code = "{" . $self->deparse($code, 0) . "} ";
2803 $code = $self->deparse($code, 24);
2804 $code .= ", " if !null($kid->sibling);
2806 $kid = $kid->sibling;
2807 for (; !null($kid); $kid = $kid->sibling) {
2808 $expr = $self->deparse($kid, 6);
2809 push @exprs, $expr if defined $expr;
2811 return $self->maybe_parens_func($name, $code . join(", ", @exprs), $cx, 5);
2814 sub pp_mapwhile { mapop(@_, "map") }
2815 sub pp_grepwhile { mapop(@_, "grep") }
2816 sub pp_mapstart { baseop(@_, "map") }
2817 sub pp_grepstart { baseop(@_, "grep") }
2823 my $kid = $op->first->sibling; # skip pushmark
2824 return '' if class($kid) eq 'NULL';
2826 my $local = "either"; # could be local(...), my(...), state(...) or our(...)
2827 for ($lop = $kid; !null($lop); $lop = $lop->sibling) {
2828 # This assumes that no other private flags equal 128, and that
2829 # OPs that store things other than flags in their op_private,
2830 # like OP_AELEMFAST, won't be immediate children of a list.
2832 # OP_ENTERSUB can break this logic, so check for it.
2833 # I suspect that open and exit can too.
2835 if (!($lop->private & (OPpLVAL_INTRO|OPpOUR_INTRO)
2836 or $lop->name eq "undef")
2837 or $lop->name eq "entersub"
2838 or $lop->name eq "exit"
2839 or $lop->name eq "open")
2841 $local = ""; # or not
2844 if ($lop->name =~ /^pad[ash]v$/) {
2845 if ($lop->private & OPpPAD_STATE) { # state()
2846 ($local = "", last) if $local =~ /^(?:local|our|my)$/;
2849 ($local = "", last) if $local =~ /^(?:local|our|state)$/;
2852 } elsif ($lop->name =~ /^(gv|rv2)[ash]v$/
2853 && $lop->private & OPpOUR_INTRO
2854 or $lop->name eq "null" && $lop->first->name eq "gvsv"
2855 && $lop->first->private & OPpOUR_INTRO) { # our()
2856 ($local = "", last) if $local =~ /^(?:my|local|state)$/;
2858 } elsif ($lop->name ne "undef"
2859 # specifically avoid the "reverse sort" optimisation,
2860 # where "reverse" is nullified
2861 && !($lop->name eq 'sort' && ($lop->flags & OPpSORT_REVERSE)))
2864 ($local = "", last) if $local =~ /^(?:my|our|state)$/;
2868 $local = "" if $local eq "either"; # no point if it's all undefs
2869 return $self->deparse($kid, $cx) if null $kid->sibling and not $local;
2870 for (; !null($kid); $kid = $kid->sibling) {
2872 if (class($kid) eq "UNOP" and $kid->first->name eq "gvsv") {
2877 $self->{'avoid_local'}{$$lop}++;
2878 $expr = $self->deparse($kid, 6);
2879 delete $self->{'avoid_local'}{$$lop};
2881 $expr = $self->deparse($kid, 6);
2886 return "$local(" . join(", ", @exprs) . ")";
2888 return $self->maybe_parens( join(", ", @exprs), $cx, 6);
2892 sub is_ifelse_cont {
2894 return ($op->name eq "null" and class($op) eq "UNOP"
2895 and $op->first->name =~ /^(and|cond_expr)$/
2896 and is_scope($op->first->first->sibling));
2902 my $cond = $op->first;
2903 my $true = $cond->sibling;
2904 my $false = $true->sibling;
2905 my $cuddle = $self->{'cuddle'};
2906 unless ($cx < 1 and (is_scope($true) and $true->name ne "null") and
2907 (is_scope($false) || is_ifelse_cont($false))
2908 and $self->{'expand'} < 7) {
2909 $cond = $self->deparse($cond, 8);
2910 $true = $self->deparse($true, 6);
2911 $false = $self->deparse($false, 8);
2912 return $self->maybe_parens("$cond ? $true : $false", $cx, 8);
2915 $cond = $self->deparse($cond, 1);
2916 $true = $self->deparse($true, 0);
2917 my $head = "if ($cond) {\n\t$true\n\b}";
2919 while (!null($false) and is_ifelse_cont($false)) {
2920 my $newop = $false->first;
2921 my $newcond = $newop->first;
2922 my $newtrue = $newcond->sibling;
2923 $false = $newtrue->sibling; # last in chain is OP_AND => no else
2924 if ($newcond->name eq "lineseq")
2926 # lineseq to ensure correct line numbers in elsif()
2927 # Bug #37302 fixed by change #33710.
2928 $newcond = $newcond->first->sibling;
2930 $newcond = $self->deparse($newcond, 1);
2931 $newtrue = $self->deparse($newtrue, 0);
2932 push @elsifs, "elsif ($newcond) {\n\t$newtrue\n\b}";
2934 if (!null($false)) {
2935 $false = $cuddle . "else {\n\t" .
2936 $self->deparse($false, 0) . "\n\b}\cK";
2940 return $head . join($cuddle, "", @elsifs) . $false;
2944 my ($self, $op, $cx) = @_;
2945 my $cond = $op->first;
2946 my $true = $cond->sibling;
2948 return $self->deparse($true, $cx);
2953 my($op, $cx, $init) = @_;
2954 my $enter = $op->first;
2955 my $kid = $enter->sibling;
2956 local(@$self{qw'curstash warnings hints hinthash'})
2957 = @$self{qw'curstash warnings hints hinthash'};
2962 if ($kid->name eq "lineseq") { # bare or infinite loop
2963 if ($kid->last->name eq "unstack") { # infinite
2964 $head = "while (1) "; # Can't use for(;;) if there's a continue
2970 } elsif ($enter->name eq "enteriter") { # foreach
2971 my $ary = $enter->first->sibling; # first was pushmark
2972 my $var = $ary->sibling;
2973 if ($ary->name eq 'null' and $enter->private & OPpITER_REVERSED) {
2974 # "reverse" was optimised away
2975 $ary = listop($self, $ary->first->sibling, 1, 'reverse');
2976 } elsif ($enter->flags & OPf_STACKED
2977 and not null $ary->first->sibling->sibling)
2979 $ary = $self->deparse($ary->first->sibling, 9) . " .. " .
2980 $self->deparse($ary->first->sibling->sibling, 9);
2982 $ary = $self->deparse($ary, 1);
2985 if (($enter->flags & OPf_SPECIAL) && ($] < 5.009)) {
2986 # thread special var, under 5005threads
2987 $var = $self->pp_threadsv($enter, 1);
2988 } else { # regular my() variable
2989 $var = $self->pp_padsv($enter, 1);
2991 } elsif ($var->name eq "rv2gv") {
2992 $var = $self->pp_rv2sv($var, 1);
2993 if ($enter->private & OPpOUR_INTRO) {
2994 # our declarations don't have package names
2995 $var =~ s/^(.).*::/$1/;
2998 } elsif ($var->name eq "gv") {
2999 $var = "\$" . $self->deparse($var, 1);
3001 $body = $kid->first->first->sibling; # skip OP_AND and OP_ITER
3002 if (!is_state $body->first and $body->first->name !~ /^(?:stub|leave|scope)$/) {
3003 confess unless $var eq '$_';
3004 $body = $body->first;
3005 return $self->deparse($body, 2) . " foreach ($ary)";
3007 $head = "foreach $var ($ary) ";
3008 } elsif ($kid->name eq "null") { # while/until
3010 my $name = {"and" => "while", "or" => "until"}->{$kid->name};
3011 $cond = $self->deparse($kid->first, 1);
3012 $head = "$name ($cond) ";
3013 $body = $kid->first->sibling;
3014 } elsif ($kid->name eq "stub") { # bare and empty
3015 return "{;}"; # {} could be a hashref
3017 # If there isn't a continue block, then the next pointer for the loop
3018 # will point to the unstack, which is kid's last child, except
3019 # in a bare loop, when it will point to the leaveloop. When neither of
3020 # these conditions hold, then the second-to-last child is the continue
3021 # block (or the last in a bare loop).
3022 my $cont_start = $enter->nextop;
3024 if ($$cont_start != $$op && ${$cont_start} != ${$body->last}) {
3026 $cont = $body->last;
3028 $cont = $body->first;
3029 while (!null($cont->sibling->sibling)) {
3030 $cont = $cont->sibling;
3033 my $state = $body->first;
3034 my $cuddle = $self->{'cuddle'};
3036 for (; $$state != $$cont; $state = $state->sibling) {
3037 push @states, $state;
3039 $body = $self->lineseq(undef, 0, @states);
3040 if (defined $cond and not is_scope $cont and $self->{'expand'} < 3) {
3041 $head = "for ($init; $cond; " . $self->deparse($cont, 1) .") ";
3044 $cont = $cuddle . "continue {\n\t" .
3045 $self->deparse($cont, 0) . "\n\b}\cK";
3048 return "" if !defined $body;
3050 $head = "for ($init; $cond;) ";
3053 $body = $self->deparse($body, 0);
3055 $body =~ s/;?$/;\n/;
3057 return $head . "{\n\t" . $body . "\b}" . $cont;
3060 sub pp_leaveloop { shift->loop_common(@_, "") }
3065 my $init = $self->deparse($op, 1);
3066 my $s = $op->sibling;
3067 my $ll = $s->name eq "unstack" ? $s->sibling : $s->first->sibling;
3068 return $self->loop_common($ll, $cx, $init);
3073 return "eval {\n\t" . $self->pp_leave(@_) . "\n\b}";
3076 BEGIN { for (qw[ const stringify rv2sv list glob ]) {
3077 eval "sub OP_\U$_ () { " . opnumber($_) . "}"
3083 if (class($op) eq "OP") {
3085 return $self->{'ex_const'} if $op->targ == OP_CONST;
3086 } elsif ($op->first->name eq "pushmark") {
3087 return $self->pp_list($op, $cx);
3088 } elsif ($op->first->name eq "enter") {
3089 return $self->pp_leave($op, $cx);
3090 } elsif ($op->first->name eq "leave") {
3091 return $self->pp_leave($op->first, $cx);
3092 } elsif ($op->first->name eq "scope") {
3093 return $self->pp_scope($op->first, $cx);
3094 } elsif ($op->targ == OP_STRINGIFY) {
3095 return $self->dquote($op, $cx);
3096 } elsif ($op->targ == OP_GLOB) {
3097 return $self->pp_glob(
3098 $op->first # entersub
3104 } elsif (!null($op->first->sibling) and
3105 $op->first->sibling->name eq "readline" and
3106 $op->first->sibling->flags & OPf_STACKED) {
3107 return $self->maybe_parens($self->deparse($op->first, 7) . " = "
3108 . $self->deparse($op->first->sibling, 7),
3110 } elsif (!null($op->first->sibling) and
3111 $op->first->sibling->name eq "trans" and
3112 $op->first->sibling->flags & OPf_STACKED) {
3113 return $self->maybe_parens($self->deparse($op->first, 20) . " =~ "
3114 . $self->deparse($op->first->sibling, 20),
3116 } elsif ($op->flags & OPf_SPECIAL && $cx < 1 && !$op->targ) {
3117 return "do {\n\t". $self->deparse($op->first, $cx) ."\n\b};";
3118 } elsif (!null($op->first->sibling) and
3119 $op->first->sibling->name eq "null" and
3120 class($op->first->sibling) eq "UNOP" and
3121 $op->first->sibling->first->flags & OPf_STACKED and
3122 $op->first->sibling->first->name eq "rcatline") {
3123 return $self->maybe_parens($self->deparse($op->first, 18) . " .= "
3124 . $self->deparse($op->first->sibling, 18),
3127 return $self->deparse($op->first, $cx);
3134 return $self->padname_sv($targ)->PVX;
3140 return substr($self->padname($op->targ), 1); # skip $/@/%
3146 return $self->maybe_my($op, $cx, $self->padname($op->targ));
3149 sub pp_padav { pp_padsv(@_) }
3150 sub pp_padhv { pp_padsv(@_) }
3152 my @threadsv_names = B::threadsv_names;
3156 return $self->maybe_local($op, $cx, "\$" . $threadsv_names[$op->targ]);
3162 if (class($op) eq "PADOP") {
3163 return $self->padval($op->padix);
3164 } else { # class($op) eq "SVOP"
3172 my $gv = $self->gv_or_padgv($op);
3173 return $self->maybe_local($op, $cx, $self->stash_variable("\$",
3174 $self->gv_name($gv), $cx));
3180 my $gv = $self->gv_or_padgv($op);
3181 return $self->gv_name($gv);
3184 sub pp_aelemfast_lex {
3187 my $name = $self->padname($op->targ);
3189 return $name . "[" . ($op->private + $self->{'arybase'}) . "]";
3195 # optimised PADAV, pre 5.15
3196 return $self->pp_aelemfast_lex(@_) if ($op->flags & OPf_SPECIAL);
3198 my $gv = $self->gv_or_padgv($op);
3199 my($name,$quoted) = $self->stash_variable_name('@',$gv);
3200 $name = $quoted ? "$name->" : '$' . $name;
3201 return $name . "[" . ($op->private + $self->{'arybase'}) . "]";
3206 my($op, $cx, $type) = @_;
3208 if (class($op) eq 'NULL' || !$op->can("first")) {
3209 carp("Unexpected op in pp_rv2x");
3212 my $kid = $op->first;
3213 if ($kid->name eq "gv") {
3214 return $self->stash_variable($type, $self->deparse($kid, 0), $cx);
3215 } elsif (is_scalar $kid) {
3216 my $str = $self->deparse($kid, 0);
3217 if ($str =~ /^\$([^\w\d])\z/) {
3218 # "$$+" isn't a legal way to write the scalar dereference
3219 # of $+, since the lexer can't tell you aren't trying to
3220 # do something like "$$ + 1" to get one more than your
3221 # PID. Either "${$+}" or "$${+}" are workable
3222 # disambiguations, but if the programmer did the former,
3223 # they'd be in the "else" clause below rather than here.
3224 # It's not clear if this should somehow be unified with
3225 # the code in dq and re_dq that also adds lexer
3226 # disambiguation braces.
3227 $str = '$' . "{$1}"; #'
3229 return $type . $str;
3231 return $type . "{" . $self->deparse($kid, 0) . "}";
3235 sub pp_rv2sv { maybe_local(@_, rv2x(@_, "\$")) }
3236 sub pp_rv2hv { maybe_local(@_, rv2x(@_, "%")) }
3237 sub pp_rv2gv { maybe_local(@_, rv2x(@_, "*")) }
3243 if ($op->first->name eq "padav") {
3244 return $self->maybe_local($op, $cx, '$#' . $self->padany($op->first));
3246 return $self->maybe_local($op, $cx,
3247 $self->rv2x($op->first, $cx, '$#'));
3251 # skip down to the old, ex-rv2cv
3253 my ($self, $op, $cx) = @_;
3254 if (!null($op->first) && $op->first->name eq 'null' &&
3255 $op->first->targ eq OP_LIST)
3257 return $self->rv2x($op->first->first->sibling, $cx, "&")
3260 return $self->rv2x($op, $cx, "")
3266 my($cx, @list) = @_;
3267 my @a = map $self->const($_, 6), @list;
3272 } elsif ( @a > 2 and !grep(!/^-?\d+$/, @a)) {
3273 # collapse (-1,0,1,2) into (-1..2)
3274 my ($s, $e) = @a[0,-1];
3276 return $self->maybe_parens("$s..$e", $cx, 9)
3277 unless grep $i++ != $_, @a;
3279 return $self->maybe_parens(join(", ", @a), $cx, 6);
3285 my $kid = $op->first;
3286 if ($kid->name eq "const") { # constant list
3287 my $av = $self->const_sv($kid);
3288 return $self->list_const($cx, $av->ARRAY);
3290 return $self->maybe_local($op, $cx, $self->rv2x($op, $cx, "\@"));
3294 sub is_subscriptable {
3296 if ($op->name =~ /^[ahg]elem/) {
3298 } elsif ($op->name eq "entersub") {
3299 my $kid = $op->first;
3300 return 0 unless null $kid->sibling;
3302 $kid = $kid->sibling until null $kid->sibling;
3303 return 0 if is_scope($kid);
3305 return 0 if $kid->name eq "gv";
3306 return 0 if is_scalar($kid);
3307 return is_subscriptable($kid);
3313 sub elem_or_slice_array_name
3316 my ($array, $left, $padname, $allow_arrow) = @_;
3318 if ($array->name eq $padname) {
3319 return $self->padany($array);
3320 } elsif (is_scope($array)) { # ${expr}[0]
3321 return "{" . $self->deparse($array, 0) . "}";
3322 } elsif ($array->name eq "gv") {
3323 ($array, my $quoted) =
3324 $self->stash_variable_name(
3325 $left eq '[' ? '@' : '%', $self->gv_or_padgv($array)
3327 if (!$allow_arrow && $quoted) {
3328 # This cannot happen.
3329 die "Invalid variable name $array for slice";
3331 return $quoted ? "$array->" : $array;
3332 } elsif (!$allow_arrow || is_scalar $array) { # $x[0], $$x[0], ...
3333 return $self->deparse($array, 24);
3339 sub elem_or_slice_single_index
3344 $idx = $self->deparse($idx, 1);
3346 # Outer parens in an array index will confuse perl
3347 # if we're interpolating in a regular expression, i.e.
3348 # /$x$foo[(-1)]/ is *not* the same as /$x$foo[-1]/
3350 # If $self->{parens}, then an initial '(' will
3351 # definitely be paired with a final ')'. If
3352 # !$self->{parens}, the misleading parens won't
3353 # have been added in the first place.
3355 # [You might think that we could get "(...)...(...)"
3356 # where the initial and final parens do not match
3357 # each other. But we can't, because the above would
3358 # only happen if there's an infix binop between the
3359 # two pairs of parens, and *that* means that the whole
3360 # expression would be parenthesized as well.]
3362 $idx =~ s/^\((.*)\)$/$1/ if $self->{'parens'};
3364 # Hash-element braces will autoquote a bareword inside themselves.
3365 # We need to make sure that C<$hash{warn()}> doesn't come out as
3366 # C<$hash{warn}>, which has a quite different meaning. Currently
3367 # B::Deparse will always quote strings, even if the string was a
3368 # bareword in the original (i.e. the OPpCONST_BARE flag is ignored
3369 # for constant strings.) So we can cheat slightly here - if we see
3370 # a bareword, we know that it is supposed to be a function call.
3372 $idx =~ s/^([A-Za-z_]\w*)$/$1()/;
3379 my ($op, $cx, $left, $right, $padname) = @_;
3380 my($array, $idx) = ($op->first, $op->first->sibling);
3382 $idx = $self->elem_or_slice_single_index($idx);
3384 unless ($array->name eq $padname) { # Maybe this has been fixed
3385 $array = $array->first; # skip rv2av (or ex-rv2av in _53+)
3387 if (my $array_name=$self->elem_or_slice_array_name
3388 ($array, $left, $padname, 1)) {
3389 return ($array_name =~ /->\z/ ? $array_name : "\$" . $array_name)
3390 . $left . $idx . $right;
3392 # $x[20][3]{hi} or expr->[20]
3393 my $arrow = is_subscriptable($array) ? "" : "->";
3394 return $self->deparse($array, 24) . $arrow . $left . $idx . $right;
3399 sub pp_aelem { maybe_local(@_, elem(@_, "[", "]", "padav")) }
3400 sub pp_helem { maybe_local(@_, elem(@_, "{", "}", "padhv")) }
3405 my($glob, $part) = ($op->first, $op->last);
3406 $glob = $glob->first; # skip rv2gv
3407 $glob = $glob->first if $glob->name eq "rv2gv"; # this one's a bug
3408 my $scope = is_scope($glob);
3409 $glob = $self->deparse($glob, 0);
3410 $part = $self->deparse($part, 1);
3411 return "*" . ($scope ? "{$glob}" : $glob) . "{$part}";
3416 my ($op, $cx, $left, $right, $regname, $padname) = @_;
3418 my(@elems, $kid, $array, $list);
3419 if (class($op) eq "LISTOP") {
3421 } else { # ex-hslice inside delete()
3422 for ($kid = $op->first; !null $kid->sibling; $kid = $kid->sibling) {}
3426 $array = $array->first
3427 if $array->name eq $regname or $array->name eq "null";
3428 $array = $self->elem_or_slice_array_name($array,$left,$padname,0);
3429 $kid = $op->first->sibling; # skip pushmark
3430 if ($kid->name eq "list") {
3431 $kid = $kid->first->sibling; # skip list, pushmark
3432 for (; !null $kid; $kid = $kid->sibling) {
3433 push @elems, $self->deparse($kid, 6);
3435 $list = join(", ", @elems);
3437 $list = $self->elem_or_slice_single_index($kid);
3439 return "\@" . $array . $left . $list . $right;
3442 sub pp_aslice { maybe_local(@_, slice(@_, "[", "]", "rv2av", "padav")) }
3443 sub pp_hslice { maybe_local(@_, slice(@_, "{", "}", "rv2hv", "padhv")) }
3448 my $idx = $op->first;
3449 my $list = $op->last;
3451 $list = $self->deparse($list, 1);
3452 $idx = $self->deparse($idx, 1);
3453 return "($list)" . "[$idx]";
3458 return ($op->flags & OPf_WANT) == OPf_WANT_SCALAR;
3463 return ($op->flags & OPf_WANT) == OPf_WANT_LIST;
3469 my $kid = $op->first->sibling; # skip pushmark
3470 my($meth, $obj, @exprs);
3471 if ($kid->name eq "list" and want_list $kid) {
3472 # When an indirect object isn't a bareword but the args are in
3473 # parens, the parens aren't part of the method syntax (the LLAFR
3474 # doesn't apply), but they make a list with OPf_PARENS set that
3475 # doesn't get flattened by the append_elem that adds the method,
3476 # making a (object, arg1, arg2, ...) list where the object
3477 # usually is. This can be distinguished from
3478 # '($obj, $arg1, $arg2)->meth()' (which is legal if $arg2 is an
3479 # object) because in the later the list is in scalar context
3480 # as the left side of -> always is, while in the former
3481 # the list is in list context as method arguments always are.
3482 # (Good thing there aren't method prototypes!)
3483 $meth = $kid->sibling;
3484 $kid = $kid->first->sibling; # skip pushmark
3486 $kid = $kid->sibling;
3487 for (; not null $kid; $kid = $kid->sibling) {
3492 $kid = $kid->sibling;
3493 for (; !null ($kid->sibling) && $kid->name!~/^method(?:_named)?\z/;
3494 $kid = $kid->sibling) {
3500 if ($meth->name eq "method_named") {
3501 $meth = $self->const_sv($meth)->PV;
3503 $meth = $meth->first;
3504 if ($meth->name eq "const") {
3505 # As of 5.005_58, this case is probably obsoleted by the
3506 # method_named case above
3507 $meth = $self->const_sv($meth)->PV; # needs to be bare
3511 return { method => $meth, variable_method => ref($meth),
3512 object => $obj, args => \@exprs },
3516 # compat function only
3519 my $info = $self->_method(@_);
3520 return $self->e_method( $self->_method(@_) );
3524 my ($self, $info, $cx) = @_;
3525 my $obj = $self->deparse($info->{object}, 24);
3527 my $meth = $info->{method};
3528 $meth = $self->deparse($meth, 1) if $info->{variable_method};
3529 my $args = join(", ", map { $self->deparse($_, 6) } @{$info->{args}} );
3530 if ($info->{object}->name eq 'scope' && want_list $info->{object}) {
3531 # method { $object }
3532 # This must be deparsed this way to preserve list context
3534 my $need_paren = $cx >= 6;
3535 return '(' x $need_paren
3536 . $meth . substr($obj,2) # chop off the "do"
3538 . ')' x $need_paren;
3540 my $kid = $obj . "->" . $meth;
3542 return $kid . "(" . $args . ")"; # parens mandatory
3548 # returns "&" if the prototype doesn't match the args,
3549 # or ("", $args_after_prototype_demunging) if it does.
3552 return "&" if $self->{'noproto'};
3553 my($proto, @args) = @_;
3557 # An unbackslashed @ or % gobbles up the rest of the args
3558 1 while $proto =~ s/(?<!\\)([@%])[^\]]+$/$1/;
3560 $proto =~ s/^(\\?[\$\@&%*_]|\\\[[\$\@&%*]+\]|;)//;
3563 return "&" if @args;
3564 } elsif ($chr eq ";") {
3566 } elsif ($chr eq "@" or $chr eq "%") {
3567 push @reals, map($self->deparse($_, 6), @args);
3572 if ($chr eq "\$" || $chr eq "_") {
3573 if (want_scalar $arg) {
3574 push @reals, $self->deparse($arg, 6);
3578 } elsif ($chr eq "&") {
3579 if ($arg->name =~ /^(s?refgen|undef)$/) {
3580 push @reals, $self->deparse($arg, 6);
3584 } elsif ($chr eq "*") {
3585 if ($arg->name =~ /^s?refgen$/
3586 and $arg->first->first->name eq "rv2gv")
3588 $real = $arg->first->first; # skip refgen, null
3589 if ($real->first->name eq "gv") {
3590 push @reals, $self->deparse($real, 6);
3592 push @reals, $self->deparse($real->first, 6);
3597 } elsif (substr($chr, 0, 1) eq "\\") {
3599 if ($arg->name =~ /^s?refgen$/ and
3600 !null($real = $arg->first) and
3601 ($chr =~ /\$/ && is_scalar($real->first)
3603 && class($real->first->sibling) ne 'NULL'
3604 && $real->first->sibling->name
3607 && class($real->first->sibling) ne 'NULL'
3608 && $real->first->sibling->name
3610 #or ($chr =~ /&/ # This doesn't work
3611 # && $real->first->name eq "rv2cv")
3613 && $real->first->name eq "rv2gv")))
3615 push @reals, $self->deparse($real, 6);
3622 return "&" if $proto and !$doneok; # too few args and no ';'
3623 return "&" if @args; # too many args
3624 return ("", join ", ", @reals);
3630 return $self->e_method($self->_method($op, $cx))
3631 unless null $op->first->sibling;
3635 if ($op->flags & OPf_SPECIAL && !($op->flags & OPf_MOD)) {
3637 } elsif ($op->private & OPpENTERSUB_AMPER) {
3641 $kid = $kid->first->sibling; # skip ex-list, pushmark
3642 for (; not null $kid->sibling; $kid = $kid->sibling) {
3647 if (is_scope($kid)) {
3649 $kid = "{" . $self->deparse($kid, 0) . "}";
3650 } elsif ($kid->first->name eq "gv") {
3651 my $gv = $self->gv_or_padgv($kid->first);
3652 if (class($gv->CV) ne "SPECIAL") {
3653 $proto = $gv->CV->PV if $gv->CV->FLAGS & SVf_POK;
3655 $simple = 1; # only calls of named functions can be prototyped
3656 $kid = $self->deparse($kid, 24);
3658 if ($kid eq 'main::') {
3660 } elsif ($kid !~ /^(?:\w|::)(?:[\w\d]|::(?!\z))*\z/) {
3661 $kid = single_delim("q", "'", $kid) . '->';
3664 } elsif (is_scalar ($kid->first) && $kid->first->name ne 'rv2cv') {
3666 $kid = $self->deparse($kid, 24);
3669 my $arrow = is_subscriptable($kid->first) ? "" : "->";
3670 $kid = $self->deparse($kid, 24) . $arrow;
3673 # Doesn't matter how many prototypes there are, if
3674 # they haven't happened yet!
3678 no warnings 'uninitialized';
3679 $declared = exists $self->{'subs_declared'}{$kid}
3681 defined &{ ${$self->{'curstash'}."::"}{$kid} }
3683 $self->{'subs_deparsed'}{$self->{'curstash'}."::".$kid}
3684 && defined prototype $self->{'curstash'}."::".$kid
3686 if (!$declared && defined($proto)) {
3687 # Avoid "too early to check prototype" warning
3688 ($amper, $proto) = ('&');
3693 if ($declared and defined $proto and not $amper) {
3694 ($amper, $args) = $self->check_proto($proto, @exprs);
3695 if ($amper eq "&") {
3696 $args = join(", ", map($self->deparse($_, 6), @exprs));
3699 $args = join(", ", map($self->deparse($_, 6), @exprs));
3701 if ($prefix or $amper) {
3702 if ($kid eq '&') { $kid = "{$kid}" } # &{&} cannot be written as &&
3703 if ($op->flags & OPf_STACKED) {
3704 return $prefix . $amper . $kid . "(" . $args . ")";
3706 return $prefix . $amper. $kid;
3709 # It's a syntax error to call CORE::GLOBAL::foo with a prefix,
3710 # so it must have been translated from a keyword call. Translate
3712 $kid =~ s/^CORE::GLOBAL:://;
3714 my $dproto = defined($proto) ? $proto : "undefined";
3716 return "$kid(" . $args . ")";
3717 } elsif ($dproto eq "") {
3719 } elsif ($dproto eq "\$" and is_scalar($exprs[0])) {
3720 # is_scalar is an excessively conservative test here:
3721 # really, we should be comparing to the precedence of the
3722 # top operator of $exprs[0] (ala unop()), but that would
3723 # take some major code restructuring to do right.
3724 return $self->maybe_parens_func($kid, $args, $cx, 16);
3725 } elsif ($dproto ne '$' and defined($proto) || $simple) { #'
3726 return $self->maybe_parens_func($kid, $args, $cx, 5);
3728 return "$kid(" . $args . ")";
3733 sub pp_enterwrite { unop(@_, "write") }
3735 # escape things that cause interpolation in double quotes,
3736 # but not character escapes
3739 $str =~ s/(^|\G|[^\\])((?:\\\\)*)([\$\@]|\\[uUlLQE])/$1$2\\$3/g;
3747 # Matches any string which is balanced with respect to {braces}
3758 # the same, but treat $|, $), $( and $ at the end of the string differently
3772 (\(\?\??\{$bal\}\)) # $4
3778 /defined($4) && length($4) ? "$1$2$4" : "$1$2\\$3"/xeg;
3783 # This is for regular expressions with the /x modifier
3784 # We have to leave comments unmangled.
3785 sub re_uninterp_extended {
3798 ( \(\?\??\{$bal\}\) # $4 (skip over (?{}) and (??{}) blocks)
3799 | \#[^\n]* # (skip over comments)
3806 /defined($4) && length($4) ? "$1$2$4" : "$1$2\\$3"/xeg;
3812 my %unctrl = # portable to to EBCDIC
3814 "\c@" => '\c@', # unused
3841 "\c[" => '\c[', # unused
3842 "\c\\" => '\c\\', # unused
3843 "\c]" => '\c]', # unused
3844 "\c_" => '\c_', # unused
3847 # character escapes, but not delimiters that might need to be escaped
3848 sub escape_str { # ASCII, UTF8
3850 $str =~ s/(.)/ord($1) > 255 ? sprintf("\\x{%x}", ord($1)) : $1/eg;
3852 # $str =~ s/\cH/\\b/g; # \b means something different in a regex
3858 $str =~ s/([\cA-\cZ])/$unctrl{$1}/ge;
3859 $str =~ s/([[:^print:]])/sprintf("\\%03o", ord($1))/ge;
3863 # For regexes with the /x modifier.
3864 # Leave whitespace unmangled.
3865 sub escape_extended_re {
3867 $str =~ s/(.)/ord($1) > 255 ? sprintf("\\x{%x}", ord($1)) : $1/eg;
3868 $str =~ s/([[:^print:]])/
3869 ($1 =~ y! \t\n!!) ? $1 : sprintf("\\%03o", ord($1))/ge;
3870 $str =~ s/\n/\n\f/g;
3874 # Don't do this for regexen
3877 $str =~ s/\\/\\\\/g;
3881 # Remove backslashes which precede literal control characters,
3882 # to avoid creating ambiguity when we escape the latter.
3886 # the insane complexity here is due to the behaviour of "\c\"
3887 $str =~ s/(^|[^\\]|\\c\\)(?<!\\c)\\(\\\\)*(?=[[:^print:]])/$1$2/g;
3891 sub balanced_delim {
3893 my @str = split //, $str;
3894 my($ar, $open, $close, $fail, $c, $cnt, $last_bs);
3895 for $ar (['[',']'], ['(',')'], ['<','>'], ['{','}']) {
3896 ($open, $close) = @$ar;
3897 $fail = 0; $cnt = 0; $last_bs = 0;
3900 $fail = 1 if $last_bs;
3902 } elsif ($c eq $close) {
3903 $fail = 1 if $last_bs;
3911 $last_bs = $c eq '\\';
3913 $fail = 1 if $cnt != 0;
3914 return ($open, "$open$str$close") if not $fail;
3920 my($q, $default, $str) = @_;
3921 return "$default$str$default" if $default and index($str, $default) == -1;
3923 (my $succeed, $str) = balanced_delim($str);
3924 return "$q$str" if $succeed;
3926 for my $delim ('/', '"', '#') {
3927 return "$q$delim" . $str . $delim if index($str, $delim) == -1;
3930 $str =~ s/$default/\\$default/g;
3931 return "$default$str$default";
3939 BEGIN { $max_prec = int(0.999 + 8*length(pack("F", 42))*log(2)/log(10)); }
3941 # Split a floating point number into an integer mantissa and a binary
3942 # exponent. Assumes you've already made sure the number isn't zero or
3943 # some weird infinity or NaN.
3947 if ($f == int($f)) {
3948 while ($f % 2 == 0) {
3953 while ($f != int($f)) {
3958 my $mantissa = sprintf("%.0f", $f);
3959 return ($mantissa, $exponent);
3965 if ($self->{'use_dumper'}) {
3966 return $self->const_dumper($sv, $cx);
3968 if (class($sv) eq "SPECIAL") {
3969 # sv_undef, sv_yes, sv_no
3970 return ('undef', '1', $self->maybe_parens("!1", $cx, 21))[$$sv-1];
3972 if (class($sv) eq "NULL") {
3975 # convert a version object into the "v1.2.3" string in its V magic
3976 if ($sv->FLAGS & SVs_RMG) {
3977 for (my $mg = $sv->MAGIC; $mg; $mg = $mg->MOREMAGIC) {
3978 return $mg->PTR if $mg->TYPE eq 'V';
3982 if ($sv->FLAGS & SVf_IOK) {
3983 my $str = $sv->int_value;
3984 $str = $self->maybe_parens($str, $cx, 21) if $str < 0;
3986 } elsif ($sv->FLAGS & SVf_NOK) {
3989 if (pack("F", $nv) eq pack("F", 0)) {
3994 return $self->maybe_parens("-.0", $cx, 21);
3996 } elsif (1/$nv == 0) {
3999 return $self->maybe_parens("9**9**9", $cx, 22);
4002 return $self->maybe_parens("-9**9**9", $cx, 21);
4004 } elsif ($nv != $nv) {
4006 if (pack("F", $nv) eq pack("F", sin(9**9**9))) {
4008 return "sin(9**9**9)";
4009 } elsif (pack("F", $nv) eq pack("F", -sin(9**9**9))) {
4011 return $self->maybe_parens("-sin(9**9**9)", $cx, 21);
4014 my $hex = unpack("h*", pack("F", $nv));
4015 return qq'unpack("F", pack("h*", "$hex"))';
4018 # first, try the default stringification
4021 # failing that, try using more precision
4022 $str = sprintf("%.${max_prec}g", $nv);
4023 # if (pack("F", $str) ne pack("F", $nv)) {
4025 # not representable in decimal with whatever sprintf()
4026 # and atof() Perl is using here.
4027 my($mant, $exp) = split_float($nv);
4028 return $self->maybe_parens("$mant * 2**$exp", $cx, 19);
4031 $str = $self->maybe_parens($str, $cx, 21) if $nv < 0;
4033 } elsif ($sv->FLAGS & SVf_ROK && $sv->can("RV")) {
4035 if (class($ref) eq "AV") {
4036 return "[" . $self->list_const(2, $ref->ARRAY) . "]";
4037 } elsif (class($ref) eq "HV") {
4038 my %hash = $ref->ARRAY;
4040 for my $k (sort keys %hash) {
4041 push @elts, "$k => " . $self->const($hash{$k}, 6);
4043 return "{" . join(", ", @elts) . "}";
4044 } elsif (class($ref) eq "CV") {
4046 if ($] > 5.0150051) {
4047 require overloading;
4048 unimport overloading;
4051 if ($] > 5.0150051 && $self->{curcv} &&
4052 $self->{curcv}->object_2svref == $ref->object_2svref) {
4053 return $self->keyword("__SUB__");
4055 return "sub " . $self->deparse_sub($ref);
4057 if ($ref->FLAGS & SVs_SMG) {
4058 for (my $mg = $ref->MAGIC; $mg; $mg = $mg->MOREMAGIC) {
4059 if ($mg->TYPE eq 'r') {
4060 my $re = re_uninterp(escape_str(re_unback($mg->precomp)));
4061 return single_delim("qr", "", $re);
4066 return $self->maybe_parens("\\" . $self->const($ref, 20), $cx, 20);
4067 } elsif ($sv->FLAGS & SVf_POK) {
4069 if ($str =~ /[[:^print:]]/) {
4070 return single_delim("qq", '"', uninterp escape_str unback $str);
4072 return single_delim("q", "'", unback $str);
4082 my $ref = $sv->object_2svref();
4083 my $dumper = Data::Dumper->new([$$ref], ['$v']);
4084 $dumper->Purity(1)->Terse(1)->Deparse(1)->Indent(0)->Useqq(1)->Sortkeys(1);
4085 my $str = $dumper->Dump();
4086 if ($str =~ /^\$v/) {
4087 return '${my ' . $str . ' \$v}';
4097 # the constant could be in the pad (under useithreads)
4098 $sv = $self->padval($op->targ) unless $$sv;
4105 if ($op->private & OPpCONST_ARYBASE) {
4108 # if ($op->private & OPpCONST_BARE) { # trouble with '=>' autoquoting
4109 # return $self->const_sv($op)->PV;
4111 my $sv = $self->const_sv($op);
4112 return $self->const($sv, $cx);
4118 my $type = $op->name;
4119 if ($type eq "const") {
4120 return '$[' if $op->private & OPpCONST_ARYBASE;
4121 return uninterp(escape_str(unback($self->const_sv($op)->as_string)));
4122 } elsif ($type eq "concat") {
4123 my $first = $self->dq($op->first);
4124 my $last = $self->dq($op->last);
4126 # Disambiguate "${foo}bar", "${foo}{bar}", "${foo}[1]", "$foo\::bar"
4127 ($last =~ /^[A-Z\\\^\[\]_?]/ &&
4128 $first =~ s/([\$@])\^$/${1}{^}/) # "${^}W" etc
4129 || ($last =~ /^[:'{\[\w_]/ && #'
4130 $first =~ s/([\$@])([A-Za-z_]\w*)$/${1}{$2}/);
4132 return $first . $last;
4133 } elsif ($type eq "uc") {
4134 return '\U' . $self->dq($op->first->sibling) . '\E';
4135 } elsif ($type eq "lc") {
4136 return '\L' . $self->dq($op->first->sibling) . '\E';
4137 } elsif ($type eq "ucfirst") {
4138 return '\u' . $self->dq($op->first->sibling);
4139 } elsif ($type eq "lcfirst") {
4140 return '\l' . $self->dq($op->first->sibling);
4141 } elsif ($type eq "quotemeta") {
4142 return '\Q' . $self->dq($op->first->sibling) . '\E';
4143 } elsif ($type eq "fc") {
4144 return '\F' . $self->dq($op->first->sibling) . '\E';
4145 } elsif ($type eq "join") {
4146 return $self->deparse($op->last, 26); # was join($", @ary)
4148 return $self->deparse($op, 26);
4155 # skip pushmark if it exists (readpipe() vs ``)
4156 my $child = $op->first->sibling->isa('B::NULL')
4157 ? $op->first : $op->first->sibling;
4158 if ($self->pure_string($child)) {
4159 return single_delim("qx", '`', $self->dq($child, 1));
4161 unop($self, @_, "readpipe");
4167 my $kid = $op->first->sibling; # skip ex-stringify, pushmark
4168 return $self->deparse($kid, $cx) if $self->{'unquote'};
4169 $self->maybe_targmy($kid, $cx,
4170 sub {single_delim("qq", '"', $self->dq($_[1]))});
4173 # OP_STRINGIFY is a listop, but it only ever has one arg
4174 sub pp_stringify { maybe_targmy(@_, \&dquote) }
4176 # tr/// and s/// (and tr[][], tr[]//, tr###, etc)
4177 # note that tr(from)/to/ is OK, but not tr/from/(to)
4179 my($from, $to) = @_;
4180 my($succeed, $delim);
4181 if ($from !~ m[/] and $to !~ m[/]) {
4182 return "/$from/$to/";
4183 } elsif (($succeed, $from) = balanced_delim($from) and $succeed) {
4184 if (($succeed, $to) = balanced_delim($to) and $succeed) {
4187 for $delim ('/', '"', '#') { # note no "'" -- s''' is special
4188 return "$from$delim$to$delim" if index($to, $delim) == -1;
4191 return "$from/$to/";
4194 for $delim ('/', '"', '#') { # note no '
4195 return "$delim$from$delim$to$delim"
4196 if index($to . $from, $delim) == -1;
4198 $from =~ s[/][\\/]g;
4200 return "/$from/$to/";
4204 # Only used by tr///, so backslashes hyphens
4207 if ($n == ord '\\') {
4209 } elsif ($n == ord "-") {
4211 } elsif ($n >= ord(' ') and $n <= ord('~')) {
4213 } elsif ($n == ord "\a") {
4215 } elsif ($n == ord "\b") {
4217 } elsif ($n == ord "\t") {
4219 } elsif ($n == ord "\n") {
4221 } elsif ($n == ord "\e") {
4223 } elsif ($n == ord "\f") {
4225 } elsif ($n == ord "\r") {
4227 } elsif ($n >= ord("\cA") and $n <= ord("\cZ")) {
4228 return '\\c' . chr(ord("@") + $n);
4230 # return '\x' . sprintf("%02x", $n);
4231 return '\\' . sprintf("%03o", $n);
4237 my($str, $c, $tr) = ("");
4238 for ($c = 0; $c < @chars; $c++) {
4241 if ($c <= $#chars - 2 and $chars[$c + 1] == $tr + 1 and
4242 $chars[$c + 2] == $tr + 2)
4244 for (; $c <= $#chars-1 and $chars[$c + 1] == $chars[$c] + 1; $c++)
4247 $str .= pchr($chars[$c]);
4253 sub tr_decode_byte {
4254 my($table, $flags) = @_;
4255 my(@table) = unpack("s*", $table);
4256 splice @table, 0x100, 1; # Number of subsequent elements
4257 my($c, $tr, @from, @to, @delfrom, $delhyphen);
4258 if ($table[ord "-"] != -1 and
4259 $table[ord("-") - 1] == -1 || $table[ord("-") + 1] == -1)
4261 $tr = $table[ord "-"];
4262 $table[ord "-"] = -1;
4266 } else { # -2 ==> delete
4270 for ($c = 0; $c < @table; $c++) {
4273 push @from, $c; push @to, $tr;
4274 } elsif ($tr == -2) {
4278 @from = (@from, @delfrom);
4279 if ($flags & OPpTRANS_COMPLEMENT) {
4282 @from{@from} = (1) x @from;
4283 for ($c = 0; $c < 256; $c++) {
4284 push @newfrom, $c unless $from{$c};
4288 unless ($flags & OPpTRANS_DELETE || !@to) {
4289 pop @to while $#to and $to[$#to] == $to[$#to -1];
4292 $from = collapse(@from);
4293 $to = collapse(@to);
4294 $from .= "-" if $delhyphen;
4295 return ($from, $to);
4300 if ($x == ord "-") {
4302 } elsif ($x == ord "\\") {
4309 # XXX This doesn't yet handle all cases correctly either
4311 sub tr_decode_utf8 {
4312 my($swash_hv, $flags) = @_;
4313 my %swash = $swash_hv->ARRAY;
4315 $final = $swash{'FINAL'}->IV if exists $swash{'FINAL'};
4316 my $none = $swash{"NONE"}->IV;
4317 my $extra = $none + 1;
4318 my(@from, @delfrom, @to);
4320 foreach $line (split /\n/, $swash{'LIST'}->PV) {
4321 my($min, $max, $result) = split(/\t/, $line);
4328 $result = hex $result;
4329 if ($result == $extra) {
4330 push @delfrom, [$min, $max];
4332 push @from, [$min, $max];
4333 push @to, [$result, $result + $max - $min];
4336 for my $i (0 .. $#from) {
4337 if ($from[$i][0] == ord '-') {
4338 unshift @from, splice(@from, $i, 1);
4339 unshift @to, splice(@to, $i, 1);
4341 } elsif ($from[$i][1] == ord '-') {
4344 unshift @from, ord '-';
4345 unshift @to, ord '-';
4349 for my $i (0 .. $#delfrom) {
4350 if ($delfrom[$i][0] == ord '-') {
4351 push @delfrom, splice(@delfrom, $i, 1);
4353 } elsif ($delfrom[$i][1] == ord '-') {
4355 push @delfrom, ord '-';
4359 if (defined $final and $to[$#to][1] != $final) {