This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
B::Deparse: loopexes have assignment prec
[perl5.git] / dist / B-Deparse / Deparse.pm
... / ...
CommitLineData
1# B::Deparse.pm
2# Copyright (c) 1998-2000, 2002, 2003, 2004, 2005, 2006 Stephen McCamant.
3# All rights reserved.
4# This module is free software; you can redistribute and/or modify
5# it under the same terms as Perl itself.
6
7# This is based on the module of the same name by Malcolm Beattie,
8# but essentially none of his code remains.
9
10package B::Deparse;
11use Carp;
12use 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
18 OPpSORT_REVERSE
19 SVf_IOK SVf_NOK SVf_ROK SVf_POK SVpad_OUR SVf_FAKE SVs_RMG SVs_SMG
20 CVf_METHOD CVf_LVALUE
21 PMf_KEEP PMf_GLOBAL PMf_CONTINUE PMf_EVAL PMf_ONCE
22 PMf_MULTILINE PMf_SINGLELINE PMf_FOLD PMf_EXTENDED);
23$VERSION = '1.16';
24use strict;
25use vars qw/$AUTOLOAD/;
26use warnings ();
27require feature;
28
29BEGIN {
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)) {
38 eval { import B $_ };
39 no strict 'refs';
40 *{$_} = sub () {0} unless *{$_}{CODE};
41 }
42}
43
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,
64# thanks to Gisle Aas
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
91# Changes after 0.57:
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)
114# - many bug-fixes
115# - support for pragmas and 'use'
116# - support for the little-used $[ variable
117# - support for __DATA__ sections
118# - UTF8 support
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)
127# - bug-fixes
128# - new switch -P
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
134# - more bug fixes
135# - discovered lots more bugs not yet fixed
136#
137# ...
138#
139# Changes between 0.72 and 0.73
140# - support new switch constructs
141
142# Todo:
143# (See also BUGS section at the end of this file)
144#
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?)
159# - here-docs?
160
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
175# 'sub f { f($x) }'
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
179# uni/tr_ several
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
183# ext/Encode/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
192# lib/charnames 35
193# lib/constant 32
194# lib/English 40
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
202# lib/Symbol 4
203# lib/Test/Simple several
204# lib/Term/Complete
205# lib/Tie/File/t/29_downcopy 5
206# lib/vars 22
207
208# Object fields (were globals):
209#
210# avoid_local:
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
216# is done with my().
217#
218# curcv:
219# CV for current sub (or main program) being deparsed
220#
221# curcvlex:
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.
226#
227# curcop:
228# COP for statement being deparsed
229#
230# curstash:
231# name of the current package for deparsed code
232#
233# subs_todo:
234# array of [cop_seq, CV, is_format?] for subs and formats we still
235# want to deparse
236#
237# protos_todo:
238# as above, but [name, prototype] for subs that never got a GV
239#
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)
243#
244# subs_declared
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.
248#
249# subs_deparsed
250# Keeps track of fully qualified names of all deparsed subs.
251#
252# parens: -p
253# linenums: -l
254# unquote: -q
255# cuddle: ' ' or '\n', depending on -sC
256# indent_size: -si
257# use_tabs: -sT
258# ex_const: -sv
259
260# A little explanation of how precedence contexts and associativity
261# work:
262#
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.
274
275# Precedences:
276# 26 [TODO] inside interpolation context ("")
277# 25 left terms and list operators (leftward)
278# 24 left ->
279# 23 nonassoc ++ --
280# 22 right **
281# 21 right ! ~ \ and unary + and -
282# 20 left =~ !~
283# 19 left * / % x
284# 18 left + - .
285# 17 left << >>
286# 16 nonassoc named unary operators
287# 15 nonassoc < > <= >= lt gt le ge
288# 14 nonassoc == != <=> eq ne cmp
289# 13 left &
290# 12 left | ^
291# 11 left &&
292# 10 left ||
293# 9 nonassoc .. ...
294# 8 right ?:
295# 7 right = += -= *= etc.
296# 6 left , =>
297# 5 nonassoc list operators (rightward)
298# 4 right not
299# 3 left and
300# 2 left or xor
301# 1 statement modifiers
302# 0.5 statements, but still print scopes as do { ... }
303# 0 statement level
304
305# Nonprinting characters with special meaning:
306# \cS - steal parens (see maybe_parens_unop)
307# \n - newline and indent
308# \t - increase indent
309# \b - decrease indent ('outdent')
310# \f - flush left (no indent)
311# \cK - kill following semicolon, if any
312
313sub null {
314 my $op = shift;
315 return class($op) eq "NULL";
316}
317
318sub todo {
319 my $self = shift;
320 my($cv, $is_form) = @_;
321 return unless ($cv->FILE eq $0 || exists $self->{files}{$cv->FILE});
322 my $seq;
323 if ($cv->OUTSIDE_SEQ) {
324 $seq = $cv->OUTSIDE_SEQ;
325 } elsif (!null($cv->START) and is_state($cv->START)) {
326 $seq = $cv->START->cop_seq;
327 } else {
328 $seq = 0;
329 }
330 push @{$self->{'subs_todo'}}, [$seq, $cv, $is_form];
331 unless ($is_form || class($cv->STASH) eq 'SPECIAL') {
332 $self->{'subs_deparsed'}{$cv->STASH->NAME."::".$cv->GV->NAME} = 1;
333 }
334}
335
336sub next_todo {
337 my $self = shift;
338 my $ent = shift @{$self->{'subs_todo'}};
339 my $cv = $ent->[1];
340 my $gv = $cv->GV;
341 my $name = $self->gv_name($gv);
342 if ($ent->[2]) {
343 return "format $name =\n"
344 . $self->deparse_format($ent->[1]). "\n";
345 } else {
346 $self->{'subs_declared'}{$name} = 1;
347 if ($name eq "BEGIN") {
348 my $use_dec = $self->begin_is_use($cv);
349 if (defined ($use_dec) and $self->{'expand'} < 5) {
350 return () if 0 == length($use_dec);
351 return $use_dec;
352 }
353 }
354 my $l = '';
355 if ($self->{'linenums'}) {
356 my $line = $gv->LINE;
357 my $file = $gv->FILE;
358 $l = "\n\f#line $line \"$file\"\n";
359 }
360 my $p = '';
361 if (class($cv->STASH) ne "SPECIAL") {
362 my $stash = $cv->STASH->NAME;
363 if ($stash ne $self->{'curstash'}) {
364 $p = "package $stash;\n";
365 $name = "$self->{'curstash'}::$name" unless $name =~ /::/;
366 $self->{'curstash'} = $stash;
367 }
368 $name =~ s/^\Q$stash\E::(?!\z|.*::)//;
369 }
370 return "${p}${l}sub $name " . $self->deparse_sub($cv);
371 }
372}
373
374# Return a "use" declaration for this BEGIN block, if appropriate
375sub begin_is_use {
376 my ($self, $cv) = @_;
377 my $root = $cv->ROOT;
378 local @$self{qw'curcv curcvlex'} = ($cv);
379#require B::Debug;
380#B::walkoptree($cv->ROOT, "debug");
381 my $lineseq = $root->first;
382 return if $lineseq->name ne "lineseq";
383
384 my $req_op = $lineseq->first->sibling;
385 return if $req_op->name ne "require";
386
387 my $module;
388 if ($req_op->first->private & OPpCONST_BARE) {
389 # Actually it should always be a bareword
390 $module = $self->const_sv($req_op->first)->PV;
391 $module =~ s[/][::]g;
392 $module =~ s/.pm$//;
393 }
394 else {
395 $module = $self->const($self->const_sv($req_op->first), 6);
396 }
397
398 my $version;
399 my $version_op = $req_op->sibling;
400 return if class($version_op) eq "NULL";
401 if ($version_op->name eq "lineseq") {
402 # We have a version parameter; skip nextstate & pushmark
403 my $constop = $version_op->first->next->next;
404
405 return unless $self->const_sv($constop)->PV eq $module;
406 $constop = $constop->sibling;
407 $version = $self->const_sv($constop);
408 if (class($version) eq "IV") {
409 $version = $version->int_value;
410 } elsif (class($version) eq "NV") {
411 $version = $version->NV;
412 } elsif (class($version) ne "PVMG") {
413 # Includes PVIV and PVNV
414 $version = $version->PV;
415 } else {
416 # version specified as a v-string
417 $version = 'v'.join '.', map ord, split //, $version->PV;
418 }
419 $constop = $constop->sibling;
420 return if $constop->name ne "method_named";
421 return if $self->const_sv($constop)->PV ne "VERSION";
422 }
423
424 $lineseq = $version_op->sibling;
425 return if $lineseq->name ne "lineseq";
426 my $entersub = $lineseq->first->sibling;
427 if ($entersub->name eq "stub") {
428 return "use $module $version ();\n" if defined $version;
429 return "use $module ();\n";
430 }
431 return if $entersub->name ne "entersub";
432
433 # See if there are import arguments
434 my $args = '';
435
436 my $svop = $entersub->first->sibling; # Skip over pushmark
437 return unless $self->const_sv($svop)->PV eq $module;
438
439 # Pull out the arguments
440 for ($svop=$svop->sibling; $svop->name ne "method_named";
441 $svop = $svop->sibling) {
442 $args .= ", " if length($args);
443 $args .= $self->deparse($svop, 6);
444 }
445
446 my $use = 'use';
447 my $method_named = $svop;
448 return if $method_named->name ne "method_named";
449 my $method_name = $self->const_sv($method_named)->PV;
450
451 if ($method_name eq "unimport") {
452 $use = 'no';
453 }
454
455 # Certain pragmas are dealt with using hint bits,
456 # so we ignore them here
457 if ($module eq 'strict' || $module eq 'integer'
458 || $module eq 'bytes' || $module eq 'warnings'
459 || $module eq 'feature') {
460 return "";
461 }
462
463 if (defined $version && length $args) {
464 return "$use $module $version ($args);\n";
465 } elsif (defined $version) {
466 return "$use $module $version;\n";
467 } elsif (length $args) {
468 return "$use $module ($args);\n";
469 } else {
470 return "$use $module;\n";
471 }
472}
473
474sub stash_subs {
475 my ($self, $pack, $seen) = @_;
476 my (@ret, $stash);
477 if (!defined $pack) {
478 $pack = '';
479 $stash = \%::;
480 }
481 else {
482 $pack =~ s/(::)?$/::/;
483 no strict 'refs';
484 $stash = \%{"main::$pack"};
485 }
486 return
487 if ($seen ||= {})->{
488 $INC{"overload.pm"} ? overload::StrVal($stash) : $stash
489 }++;
490 my %stash = svref_2object($stash)->ARRAY;
491 while (my ($key, $val) = each %stash) {
492 my $class = class($val);
493 if ($class eq "PV") {
494 # Just a prototype. As an ugly but fairly effective way
495 # to find out if it belongs here is to see if the AUTOLOAD
496 # (if any) for the stash was defined in one of our files.
497 my $A = $stash{"AUTOLOAD"};
498 if (defined ($A) && class($A) eq "GV" && defined($A->CV)
499 && class($A->CV) eq "CV") {
500 my $AF = $A->FILE;
501 next unless $AF eq $0 || exists $self->{'files'}{$AF};
502 }
503 push @{$self->{'protos_todo'}}, [$pack . $key, $val->PV];
504 } elsif ($class eq "IV" && !($val->FLAGS & SVf_ROK)) {
505 # Just a name. As above.
506 # But skip proxy constant subroutines, as some form of perl-space
507 # visible code must have created them, be it a use statement, or
508 # some direct symbol-table manipulation code that we will Deparse
509 my $A = $stash{"AUTOLOAD"};
510 if (defined ($A) && class($A) eq "GV" && defined($A->CV)
511 && class($A->CV) eq "CV") {
512 my $AF = $A->FILE;
513 next unless $AF eq $0 || exists $self->{'files'}{$AF};
514 }
515 push @{$self->{'protos_todo'}}, [$pack . $key, undef];
516 } elsif ($class eq "GV") {
517 if (class(my $cv = $val->CV) ne "SPECIAL") {
518 next if $self->{'subs_done'}{$$val}++;
519 next if $$val != ${$cv->GV}; # Ignore imposters
520 $self->todo($cv, 0);
521 }
522 if (class(my $cv = $val->FORM) ne "SPECIAL") {
523 next if $self->{'forms_done'}{$$val}++;
524 next if $$val != ${$cv->GV}; # Ignore imposters
525 $self->todo($cv, 1);
526 }
527 if (class($val->HV) ne "SPECIAL" && $key =~ /::$/) {
528 $self->stash_subs($pack . $key, $seen);
529 }
530 }
531 }
532}
533
534sub print_protos {
535 my $self = shift;
536 my $ar;
537 my @ret;
538 foreach $ar (@{$self->{'protos_todo'}}) {
539 my $proto = (defined $ar->[1] ? " (". $ar->[1] . ")" : "");
540 push @ret, "sub " . $ar->[0] . "$proto;\n";
541 }
542 delete $self->{'protos_todo'};
543 return @ret;
544}
545
546sub style_opts {
547 my $self = shift;
548 my $opts = shift;
549 my $opt;
550 while (length($opt = substr($opts, 0, 1))) {
551 if ($opt eq "C") {
552 $self->{'cuddle'} = " ";
553 $opts = substr($opts, 1);
554 } elsif ($opt eq "i") {
555 $opts =~ s/^i(\d+)//;
556 $self->{'indent_size'} = $1;
557 } elsif ($opt eq "T") {
558 $self->{'use_tabs'} = 1;
559 $opts = substr($opts, 1);
560 } elsif ($opt eq "v") {
561 $opts =~ s/^v([^.]*)(.|$)//;
562 $self->{'ex_const'} = $1;
563 }
564 }
565}
566
567sub new {
568 my $class = shift;
569 my $self = bless {}, $class;
570 $self->{'cuddle'} = "\n";
571 $self->{'curcop'} = undef;
572 $self->{'curstash'} = "main";
573 $self->{'ex_const'} = "'???'";
574 $self->{'expand'} = 0;
575 $self->{'files'} = {};
576 $self->{'indent_size'} = 4;
577 $self->{'linenums'} = 0;
578 $self->{'parens'} = 0;
579 $self->{'subs_todo'} = [];
580 $self->{'unquote'} = 0;
581 $self->{'use_dumper'} = 0;
582 $self->{'use_tabs'} = 0;
583
584 $self->{'ambient_arybase'} = 0;
585 $self->{'ambient_warnings'} = undef; # Assume no lexical warnings
586 $self->{'ambient_hints'} = 0;
587 $self->{'ambient_hinthash'} = undef;
588 $self->init();
589
590 while (my $arg = shift @_) {
591 if ($arg eq "-d") {
592 $self->{'use_dumper'} = 1;
593 require Data::Dumper;
594 } elsif ($arg =~ /^-f(.*)/) {
595 $self->{'files'}{$1} = 1;
596 } elsif ($arg eq "-l") {
597 $self->{'linenums'} = 1;
598 } elsif ($arg eq "-p") {
599 $self->{'parens'} = 1;
600 } elsif ($arg eq "-P") {
601 $self->{'noproto'} = 1;
602 } elsif ($arg eq "-q") {
603 $self->{'unquote'} = 1;
604 } elsif (substr($arg, 0, 2) eq "-s") {
605 $self->style_opts(substr $arg, 2);
606 } elsif ($arg =~ /^-x(\d)$/) {
607 $self->{'expand'} = $1;
608 }
609 }
610 return $self;
611}
612
613{
614 # Mask out the bits that L<warnings::register> uses
615 my $WARN_MASK;
616 BEGIN {
617 $WARN_MASK = $warnings::Bits{all} | $warnings::DeadBits{all};
618 }
619 sub WARN_MASK () {
620 return $WARN_MASK;
621 }
622}
623
624# Initialise the contextual information, either from
625# defaults provided with the ambient_pragmas method,
626# or from perl's own defaults otherwise.
627sub init {
628 my $self = shift;
629
630 $self->{'arybase'} = $self->{'ambient_arybase'};
631 $self->{'warnings'} = defined ($self->{'ambient_warnings'})
632 ? $self->{'ambient_warnings'} & WARN_MASK
633 : undef;
634 $self->{'hints'} = $self->{'ambient_hints'};
635 $self->{'hints'} &= 0xFF if $] < 5.009;
636 $self->{'hinthash'} = $self->{'ambient_hinthash'};
637
638 # also a convenient place to clear out subs_declared
639 delete $self->{'subs_declared'};
640}
641
642sub compile {
643 my(@args) = @_;
644 return sub {
645 my $self = B::Deparse->new(@args);
646 # First deparse command-line args
647 if (defined $^I) { # deparse -i
648 print q(BEGIN { $^I = ).perlstring($^I).qq(; }\n);
649 }
650 if ($^W) { # deparse -w
651 print qq(BEGIN { \$^W = $^W; }\n);
652 }
653 if ($/ ne "\n" or defined $O::savebackslash) { # deparse -l and -0
654 my $fs = perlstring($/) || 'undef';
655 my $bs = perlstring($O::savebackslash) || 'undef';
656 print qq(BEGIN { \$/ = $fs; \$\\ = $bs; }\n);
657 }
658 my @BEGINs = B::begin_av->isa("B::AV") ? B::begin_av->ARRAY : ();
659 my @UNITCHECKs = B::unitcheck_av->isa("B::AV")
660 ? B::unitcheck_av->ARRAY
661 : ();
662 my @CHECKs = B::check_av->isa("B::AV") ? B::check_av->ARRAY : ();
663 my @INITs = B::init_av->isa("B::AV") ? B::init_av->ARRAY : ();
664 my @ENDs = B::end_av->isa("B::AV") ? B::end_av->ARRAY : ();
665 for my $block (@BEGINs, @UNITCHECKs, @CHECKs, @INITs, @ENDs) {
666 $self->todo($block, 0);
667 }
668 $self->stash_subs();
669 local($SIG{"__DIE__"}) =
670 sub {
671 if ($self->{'curcop'}) {
672 my $cop = $self->{'curcop'};
673 my($line, $file) = ($cop->line, $cop->file);
674 print STDERR "While deparsing $file near line $line,\n";
675 }
676 };
677 $self->{'curcv'} = main_cv;
678 $self->{'curcvlex'} = undef;
679 print $self->print_protos;
680 @{$self->{'subs_todo'}} =
681 sort {$a->[0] <=> $b->[0]} @{$self->{'subs_todo'}};
682 print $self->indent($self->deparse_root(main_root)), "\n"
683 unless null main_root;
684 my @text;
685 while (scalar(@{$self->{'subs_todo'}})) {
686 push @text, $self->next_todo;
687 }
688 print $self->indent(join("", @text)), "\n" if @text;
689
690 # Print __DATA__ section, if necessary
691 no strict 'refs';
692 my $laststash = defined $self->{'curcop'}
693 ? $self->{'curcop'}->stash->NAME : $self->{'curstash'};
694 if (defined *{$laststash."::DATA"}{IO}) {
695 print "package $laststash;\n"
696 unless $laststash eq $self->{'curstash'};
697 print "__DATA__\n";
698 print readline(*{$laststash."::DATA"});
699 }
700 }
701}
702
703sub coderef2text {
704 my $self = shift;
705 my $sub = shift;
706 croak "Usage: ->coderef2text(CODEREF)" unless UNIVERSAL::isa($sub, "CODE");
707
708 $self->init();
709 return $self->indent($self->deparse_sub(svref_2object($sub)));
710}
711
712my %strict_bits = do {
713 local $^H;
714 map +($_ => strict::bits($_)), qw/refs subs vars/
715};
716
717sub ambient_pragmas {
718 my $self = shift;
719 my ($arybase, $hint_bits, $warning_bits, $hinthash) = (0, 0);
720
721 while (@_ > 1) {
722 my $name = shift();
723 my $val = shift();
724
725 if ($name eq 'strict') {
726 require strict;
727
728 if ($val eq 'none') {
729 $hint_bits &= $strict_bits{$_} for qw/refs subs vars/;
730 next();
731 }
732
733 my @names;
734 if ($val eq "all") {
735 @names = qw/refs subs vars/;
736 }
737 elsif (ref $val) {
738 @names = @$val;
739 }
740 else {
741 @names = split' ', $val;
742 }
743 $hint_bits |= $strict_bits{$_} for @names;
744 }
745
746 elsif ($name eq '$[') {
747 if (OPpCONST_ARYBASE) {
748 $arybase = $val;
749 } else {
750 croak "\$[ can't be non-zero on this perl" unless $val == 0;
751 }
752 }
753
754 elsif ($name eq 'integer'
755 || $name eq 'bytes'
756 || $name eq 'utf8') {
757 require "$name.pm";
758 if ($val) {
759 $hint_bits |= ${$::{"${name}::"}{"hint_bits"}};
760 }
761 else {
762 $hint_bits &= ~${$::{"${name}::"}{"hint_bits"}};
763 }
764 }
765
766 elsif ($name eq 're') {
767 require re;
768 if ($val eq 'none') {
769 $hint_bits &= ~re::bits(qw/taint eval/);
770 next();
771 }
772
773 my @names;
774 if ($val eq 'all') {
775 @names = qw/taint eval/;
776 }
777 elsif (ref $val) {
778 @names = @$val;
779 }
780 else {
781 @names = split' ',$val;
782 }
783 $hint_bits |= re::bits(@names);
784 }
785
786 elsif ($name eq 'warnings') {
787 if ($val eq 'none') {
788 $warning_bits = $warnings::NONE;
789 next();
790 }
791
792 my @names;
793 if (ref $val) {
794 @names = @$val;
795 }
796 else {
797 @names = split/\s+/, $val;
798 }
799
800 $warning_bits = $warnings::NONE if !defined ($warning_bits);
801 $warning_bits |= warnings::bits(@names);
802 }
803
804 elsif ($name eq 'warning_bits') {
805 $warning_bits = $val;
806 }
807
808 elsif ($name eq 'hint_bits') {
809 $hint_bits = $val;
810 }
811
812 elsif ($name eq '%^H') {
813 $hinthash = $val;
814 }
815
816 else {
817 croak "Unknown pragma type: $name";
818 }
819 }
820 if (@_) {
821 croak "The ambient_pragmas method expects an even number of args";
822 }
823
824 $self->{'ambient_arybase'} = $arybase;
825 $self->{'ambient_warnings'} = $warning_bits;
826 $self->{'ambient_hints'} = $hint_bits;
827 $self->{'ambient_hinthash'} = $hinthash;
828}
829
830# This method is the inner loop, so try to keep it simple
831sub deparse {
832 my $self = shift;
833 my($op, $cx) = @_;
834
835 Carp::confess("Null op in deparse") if !defined($op)
836 || class($op) eq "NULL";
837 my $meth = "pp_" . $op->name;
838 return $self->$meth($op, $cx);
839}
840
841sub indent {
842 my $self = shift;
843 my $txt = shift;
844 my @lines = split(/\n/, $txt);
845 my $leader = "";
846 my $level = 0;
847 my $line;
848 for $line (@lines) {
849 my $cmd = substr($line, 0, 1);
850 if ($cmd eq "\t" or $cmd eq "\b") {
851 $level += ($cmd eq "\t" ? 1 : -1) * $self->{'indent_size'};
852 if ($self->{'use_tabs'}) {
853 $leader = "\t" x ($level / 8) . " " x ($level % 8);
854 } else {
855 $leader = " " x $level;
856 }
857 $line = substr($line, 1);
858 }
859 if (substr($line, 0, 1) eq "\f") {
860 $line = substr($line, 1); # no indent
861 } else {
862 $line = $leader . $line;
863 }
864 $line =~ s/\cK;?//g;
865 }
866 return join("\n", @lines);
867}
868
869sub deparse_sub {
870 my $self = shift;
871 my $cv = shift;
872 my $proto = "";
873Carp::confess("NULL in deparse_sub") if !defined($cv) || $cv->isa("B::NULL");
874Carp::confess("SPECIAL in deparse_sub") if $cv->isa("B::SPECIAL");
875 local $self->{'curcop'} = $self->{'curcop'};
876 if ($cv->FLAGS & SVf_POK) {
877 $proto = "(". $cv->PV . ") ";
878 }
879 if ($cv->CvFLAGS & (CVf_METHOD|CVf_LOCKED|CVf_LVALUE)) {
880 $proto .= ": ";
881 $proto .= "lvalue " if $cv->CvFLAGS & CVf_LVALUE;
882 $proto .= "locked " if $cv->CvFLAGS & CVf_LOCKED;
883 $proto .= "method " if $cv->CvFLAGS & CVf_METHOD;
884 }
885
886 local($self->{'curcv'}) = $cv;
887 local($self->{'curcvlex'});
888 local(@$self{qw'curstash warnings hints hinthash'})
889 = @$self{qw'curstash warnings hints hinthash'};
890 my $body;
891 if (not null $cv->ROOT) {
892 my $lineseq = $cv->ROOT->first;
893 if ($lineseq->name eq "lineseq") {
894 my @ops;
895 for(my$o=$lineseq->first; $$o; $o=$o->sibling) {
896 push @ops, $o;
897 }
898 $body = $self->lineseq(undef, @ops).";";
899 my $scope_en = $self->find_scope_en($lineseq);
900 if (defined $scope_en) {
901 my $subs = join"", $self->seq_subs($scope_en);
902 $body .= ";\n$subs" if length($subs);
903 }
904 }
905 else {
906 $body = $self->deparse($cv->ROOT->first, 0);
907 }
908 }
909 else {
910 my $sv = $cv->const_sv;
911 if ($$sv) {
912 # uh-oh. inlinable sub... format it differently
913 return $proto . "{ " . $self->const($sv, 0) . " }\n";
914 } else { # XSUB? (or just a declaration)
915 return "$proto;\n";
916 }
917 }
918 return $proto ."{\n\t$body\n\b}" ."\n";
919}
920
921sub deparse_format {
922 my $self = shift;
923 my $form = shift;
924 my @text;
925 local($self->{'curcv'}) = $form;
926 local($self->{'curcvlex'});
927 local($self->{'in_format'}) = 1;
928 local(@$self{qw'curstash warnings hints hinthash'})
929 = @$self{qw'curstash warnings hints hinthash'};
930 my $op = $form->ROOT;
931 my $kid;
932 return "\f." if $op->first->name eq 'stub'
933 || $op->first->name eq 'nextstate';
934 $op = $op->first->first; # skip leavewrite, lineseq
935 while (not null $op) {
936 $op = $op->sibling; # skip nextstate
937 my @exprs;
938 $kid = $op->first->sibling; # skip pushmark
939 push @text, "\f".$self->const_sv($kid)->PV;
940 $kid = $kid->sibling;
941 for (; not null $kid; $kid = $kid->sibling) {
942 push @exprs, $self->deparse($kid, 0);
943 }
944 push @text, "\f".join(", ", @exprs)."\n" if @exprs;
945 $op = $op->sibling;
946 }
947 return join("", @text) . "\f.";
948}
949
950sub is_scope {
951 my $op = shift;
952 return $op->name eq "leave" || $op->name eq "scope"
953 || $op->name eq "lineseq"
954 || ($op->name eq "null" && class($op) eq "UNOP"
955 && (is_scope($op->first) || $op->first->name eq "enter"));
956}
957
958sub is_state {
959 my $name = $_[0]->name;
960 return $name eq "nextstate" || $name eq "dbstate" || $name eq "setstate";
961}
962
963sub is_miniwhile { # check for one-line loop ('foo() while $y--')
964 my $op = shift;
965 return (!null($op) and null($op->sibling)
966 and $op->name eq "null" and class($op) eq "UNOP"
967 and (($op->first->name =~ /^(and|or)$/
968 and $op->first->first->sibling->name eq "lineseq")
969 or ($op->first->name eq "lineseq"
970 and not null $op->first->first->sibling
971 and $op->first->first->sibling->name eq "unstack")
972 ));
973}
974
975# Check if the op and its sibling are the initialization and the rest of a
976# for (..;..;..) { ... } loop
977sub is_for_loop {
978 my $op = shift;
979 # This OP might be almost anything, though it won't be a
980 # nextstate. (It's the initialization, so in the canonical case it
981 # will be an sassign.) The sibling is (old style) a lineseq whose
982 # first child is a nextstate and whose second is a leaveloop, or
983 # (new style) an unstack whose sibling is a leaveloop.
984 my $lseq = $op->sibling;
985 return 0 unless !is_state($op) and !null($lseq);
986 if ($lseq->name eq "lineseq") {
987 if ($lseq->first && !null($lseq->first) && is_state($lseq->first)
988 && (my $sib = $lseq->first->sibling)) {
989 return (!null($sib) && $sib->name eq "leaveloop");
990 }
991 } elsif ($lseq->name eq "unstack" && ($lseq->flags & OPf_SPECIAL)) {
992 my $sib = $lseq->sibling;
993 return $sib && !null($sib) && $sib->name eq "leaveloop";
994 }
995 return 0;
996}
997
998sub is_scalar {
999 my $op = shift;
1000 return ($op->name eq "rv2sv" or
1001 $op->name eq "padsv" or
1002 $op->name eq "gv" or # only in array/hash constructs
1003 $op->flags & OPf_KIDS && !null($op->first)
1004 && $op->first->name eq "gvsv");
1005}
1006
1007sub maybe_parens {
1008 my $self = shift;
1009 my($text, $cx, $prec) = @_;
1010 if ($prec < $cx # unary ops nest just fine
1011 or $prec == $cx and $cx != 4 and $cx != 16 and $cx != 21
1012 or $self->{'parens'})
1013 {
1014 $text = "($text)";
1015 # In a unop, let parent reuse our parens; see maybe_parens_unop
1016 $text = "\cS" . $text if $cx == 16;
1017 return $text;
1018 } else {
1019 return $text;
1020 }
1021}
1022
1023# same as above, but get around the 'if it looks like a function' rule
1024sub maybe_parens_unop {
1025 my $self = shift;
1026 my($name, $kid, $cx) = @_;
1027 if ($cx > 16 or $self->{'parens'}) {
1028 $kid = $self->deparse($kid, 1);
1029 if ($name eq "umask" && $kid =~ /^\d+$/) {
1030 $kid = sprintf("%#o", $kid);
1031 }
1032 return $self->keyword($name) . "($kid)";
1033 } else {
1034 $kid = $self->deparse($kid, 16);
1035 if ($name eq "umask" && $kid =~ /^\d+$/) {
1036 $kid = sprintf("%#o", $kid);
1037 }
1038 $name = $self->keyword($name);
1039 if (substr($kid, 0, 1) eq "\cS") {
1040 # use kid's parens
1041 return $name . substr($kid, 1);
1042 } elsif (substr($kid, 0, 1) eq "(") {
1043 # avoid looks-like-a-function trap with extra parens
1044 # ('+' can lead to ambiguities)
1045 return "$name(" . $kid . ")";
1046 } else {
1047 return "$name $kid";
1048 }
1049 }
1050}
1051
1052sub maybe_parens_func {
1053 my $self = shift;
1054 my($func, $text, $cx, $prec) = @_;
1055 if ($prec <= $cx or substr($text, 0, 1) eq "(" or $self->{'parens'}) {
1056 return "$func($text)";
1057 } else {
1058 return "$func $text";
1059 }
1060}
1061
1062sub maybe_local {
1063 my $self = shift;
1064 my($op, $cx, $text) = @_;
1065 my $our_intro = ($op->name =~ /^(gv|rv2)[ash]v$/) ? OPpOUR_INTRO : 0;
1066 if ($op->private & (OPpLVAL_INTRO|$our_intro)
1067 and not $self->{'avoid_local'}{$$op}) {
1068 my $our_local = ($op->private & OPpLVAL_INTRO) ? "local" : "our";
1069 if( $our_local eq 'our' ) {
1070 if ( $text !~ /^\W(\w+::)*\w+\z/
1071 and !utf8::decode($text) || $text !~ /^\W(\w+::)*\w+\z/
1072 ) {
1073 die "Unexpected our($text)\n";
1074 }
1075 $text =~ s/(\w+::)+//;
1076 }
1077 if (want_scalar($op)) {
1078 return "$our_local $text";
1079 } else {
1080 return $self->maybe_parens_func("$our_local", $text, $cx, 16);
1081 }
1082 } else {
1083 return $text;
1084 }
1085}
1086
1087sub maybe_targmy {
1088 my $self = shift;
1089 my($op, $cx, $func, @args) = @_;
1090 if ($op->private & OPpTARGET_MY) {
1091 my $var = $self->padname($op->targ);
1092 my $val = $func->($self, $op, 7, @args);
1093 return $self->maybe_parens("$var = $val", $cx, 7);
1094 } else {
1095 return $func->($self, $op, $cx, @args);
1096 }
1097}
1098
1099sub padname_sv {
1100 my $self = shift;
1101 my $targ = shift;
1102 return $self->{'curcv'}->PADLIST->ARRAYelt(0)->ARRAYelt($targ);
1103}
1104
1105sub maybe_my {
1106 my $self = shift;
1107 my($op, $cx, $text) = @_;
1108 if ($op->private & OPpLVAL_INTRO and not $self->{'avoid_local'}{$$op}) {
1109 my $my = $op->private & OPpPAD_STATE
1110 ? $self->keyword("state")
1111 : "my";
1112 if (want_scalar($op)) {
1113 return "$my $text";
1114 } else {
1115 return $self->maybe_parens_func($my, $text, $cx, 16);
1116 }
1117 } else {
1118 return $text;
1119 }
1120}
1121
1122# The following OPs don't have functions:
1123
1124# pp_padany -- does not exist after parsing
1125
1126sub AUTOLOAD {
1127 if ($AUTOLOAD =~ s/^.*::pp_//) {
1128 warn "unexpected OP_".uc $AUTOLOAD;
1129 return "XXX";
1130 } else {
1131 die "Undefined subroutine $AUTOLOAD called";
1132 }
1133}
1134
1135sub DESTROY {} # Do not AUTOLOAD
1136
1137# $root should be the op which represents the root of whatever
1138# we're sequencing here. If it's undefined, then we don't append
1139# any subroutine declarations to the deparsed ops, otherwise we
1140# append appropriate declarations.
1141sub lineseq {
1142 my($self, $root, @ops) = @_;
1143 my($expr, @exprs);
1144
1145 my $out_cop = $self->{'curcop'};
1146 my $out_seq = defined($out_cop) ? $out_cop->cop_seq : undef;
1147 my $limit_seq;
1148 if (defined $root) {
1149 $limit_seq = $out_seq;
1150 my $nseq;
1151 $nseq = $self->find_scope_st($root->sibling) if ${$root->sibling};
1152 $limit_seq = $nseq if !defined($limit_seq)
1153 or defined($nseq) && $nseq < $limit_seq;
1154 }
1155 $limit_seq = $self->{'limit_seq'}
1156 if defined($self->{'limit_seq'})
1157 && (!defined($limit_seq) || $self->{'limit_seq'} < $limit_seq);
1158 local $self->{'limit_seq'} = $limit_seq;
1159
1160 $self->walk_lineseq($root, \@ops,
1161 sub { push @exprs, $_[0]} );
1162
1163 my $body = join(";\n", grep {length} @exprs);
1164 my $subs = "";
1165 if (defined $root && defined $limit_seq && !$self->{'in_format'}) {
1166 $subs = join "\n", $self->seq_subs($limit_seq);
1167 }
1168 return join(";\n", grep {length} $body, $subs);
1169}
1170
1171sub scopeop {
1172 my($real_block, $self, $op, $cx) = @_;
1173 my $kid;
1174 my @kids;
1175
1176 local(@$self{qw'curstash warnings hints hinthash'})
1177 = @$self{qw'curstash warnings hints hinthash'} if $real_block;
1178 if ($real_block) {
1179 $kid = $op->first->sibling; # skip enter
1180 if (is_miniwhile($kid)) {
1181 my $top = $kid->first;
1182 my $name = $top->name;
1183 if ($name eq "and") {
1184 $name = "while";
1185 } elsif ($name eq "or") {
1186 $name = "until";
1187 } else { # no conditional -> while 1 or until 0
1188 return $self->deparse($top->first, 1) . " while 1";
1189 }
1190 my $cond = $top->first;
1191 my $body = $cond->sibling->first; # skip lineseq
1192 $cond = $self->deparse($cond, 1);
1193 $body = $self->deparse($body, 1);
1194 return "$body $name $cond";
1195 }
1196 } else {
1197 $kid = $op->first;
1198 }
1199 for (; !null($kid); $kid = $kid->sibling) {
1200 push @kids, $kid;
1201 }
1202 if ($cx > 0) { # inside an expression, (a do {} while for lineseq)
1203 return "do {\n\t" . $self->lineseq($op, @kids) . "\n\b}";
1204 } else {
1205 my $lineseq = $self->lineseq($op, @kids);
1206 return (length ($lineseq) ? "$lineseq;" : "");
1207 }
1208}
1209
1210sub pp_scope { scopeop(0, @_); }
1211sub pp_lineseq { scopeop(0, @_); }
1212sub pp_leave { scopeop(1, @_); }
1213
1214# This is a special case of scopeop and lineseq, for the case of the
1215# main_root. The difference is that we print the output statements as
1216# soon as we get them, for the sake of impatient users.
1217sub deparse_root {
1218 my $self = shift;
1219 my($op) = @_;
1220 local(@$self{qw'curstash warnings hints hinthash'})
1221 = @$self{qw'curstash warnings hints hinthash'};
1222 my @kids;
1223 return if null $op->first; # Can happen, e.g., for Bytecode without -k
1224 for (my $kid = $op->first->sibling; !null($kid); $kid = $kid->sibling) {
1225 push @kids, $kid;
1226 }
1227 $self->walk_lineseq($op, \@kids,
1228 sub { print $self->indent($_[0].';');
1229 print "\n" unless $_[1] == $#kids;
1230 });
1231}
1232
1233sub walk_lineseq {
1234 my ($self, $op, $kids, $callback) = @_;
1235 my @kids = @$kids;
1236 for (my $i = 0; $i < @kids; $i++) {
1237 my $expr = "";
1238 if (is_state $kids[$i]) {
1239 $expr = $self->deparse($kids[$i++], 0);
1240 if ($i > $#kids) {
1241 $callback->($expr, $i);
1242 last;
1243 }
1244 }
1245 if (is_for_loop($kids[$i])) {
1246 $callback->($expr . $self->for_loop($kids[$i], 0),
1247 $i += $kids[$i]->sibling->name eq "unstack" ? 2 : 1);
1248 next;
1249 }
1250 $expr .= $self->deparse($kids[$i], (@kids != 1)/2);
1251 $expr =~ s/;\n?\z//;
1252 $callback->($expr, $i);
1253 }
1254}
1255
1256# The BEGIN {} is used here because otherwise this code isn't executed
1257# when you run B::Deparse on itself.
1258my %globalnames;
1259BEGIN { map($globalnames{$_}++, "SIG", "STDIN", "STDOUT", "STDERR", "INC",
1260 "ENV", "ARGV", "ARGVOUT", "_"); }
1261
1262sub gv_name {
1263 my $self = shift;
1264 my $gv = shift;
1265 my $raw = shift;
1266Carp::confess() unless ref($gv) eq "B::GV";
1267 my $stash = $gv->STASH->NAME;
1268 my $name = $raw ? $gv->NAME : $gv->SAFENAME;
1269 if ($stash eq 'main' && $name =~ /^::/) {
1270 $stash = '::';
1271 }
1272 elsif (($stash eq 'main'
1273 && ($globalnames{$name} || $name =~ /^[^A-Za-z_:]/))
1274 or ($stash eq $self->{'curstash'} && !$globalnames{$name}
1275 && ($stash eq 'main' || $name !~ /::/))
1276 )
1277 {
1278 $stash = "";
1279 } else {
1280 $stash = $stash . "::";
1281 }
1282 if (!$raw and $name =~ /^(\^..|{)/) {
1283 $name = "{$name}"; # ${^WARNING_BITS}, etc and ${
1284 }
1285 return $stash . $name;
1286}
1287
1288# Return the name to use for a stash variable.
1289# If a lexical with the same name is in scope, or
1290# if strictures are enabled, it may need to be
1291# fully-qualified.
1292sub stash_variable {
1293 my ($self, $prefix, $name, $cx) = @_;
1294
1295 return "$prefix$name" if $name =~ /::/;
1296
1297 unless ($prefix eq '$' || $prefix eq '@' || #'
1298 $prefix eq '%' || $prefix eq '$#') {
1299 return "$prefix$name";
1300 }
1301
1302 if ($name =~ /^[^\w+-]$/) {
1303 if (defined $cx && $cx == 26) {
1304 if ($prefix eq '@') {
1305 return "$prefix\{$name}";
1306 }
1307 elsif ($name eq '#') { return '${#}' } # "${#}a" vs "$#a"
1308 }
1309 if ($prefix eq '$#') {
1310 return "\$#{$name}";
1311 }
1312 }
1313
1314 return $prefix . $self->maybe_qualify($prefix, $name);
1315}
1316
1317# Return just the name, without the prefix. It may be returned as a quoted
1318# string. The second return value is a boolean indicating that.
1319sub stash_variable_name {
1320 my($self, $prefix, $gv) = @_;
1321 my $name = $self->gv_name($gv, 1);
1322 $name = $self->maybe_qualify($prefix,$name);
1323 if ($name =~ /^(?:\S|(?!\d)[\ca-\cz]?(?:\w|::)*|\d+)\z/) {
1324 $name =~ s/^([\ca-\cz])/'^'.($1|'@')/e;
1325 $name =~ /^(\^..|{)/ and $name = "{$name}";
1326 return $name, 0; # not quoted
1327 }
1328 else {
1329 single_delim("q", "'", $name), 1;
1330 }
1331}
1332
1333sub maybe_qualify {
1334 my ($self,$prefix,$name) = @_;
1335 my $v = ($prefix eq '$#' ? '@' : $prefix) . $name;
1336 return $name if !$prefix || $name =~ /::/;
1337 return $self->{'curstash'}.'::'. $name
1338 if
1339 $name =~ /^(?!\d)\w/ # alphabetic
1340 && $v !~ /^\$[ab]\z/ # not $a or $b
1341 && !$globalnames{$name} # not a global name
1342 && $self->{hints} & $strict_bits{vars} # strict vars
1343 && !$self->lex_in_scope($v,1) # no "our"
1344 or $self->lex_in_scope($v); # conflicts with "my" variable
1345 return $name;
1346}
1347
1348sub lex_in_scope {
1349 my ($self, $name, $our) = @_;
1350 substr $name, 0, 0, = $our ? 'o' : 'm'; # our/my
1351 $self->populate_curcvlex() if !defined $self->{'curcvlex'};
1352
1353 return 0 if !defined($self->{'curcop'});
1354 my $seq = $self->{'curcop'}->cop_seq;
1355 return 0 if !exists $self->{'curcvlex'}{$name};
1356 for my $a (@{$self->{'curcvlex'}{$name}}) {
1357 my ($st, $en) = @$a;
1358 return 1 if $seq > $st && $seq <= $en;
1359 }
1360 return 0;
1361}
1362
1363sub populate_curcvlex {
1364 my $self = shift;
1365 for (my $cv = $self->{'curcv'}; class($cv) eq "CV"; $cv = $cv->OUTSIDE) {
1366 my $padlist = $cv->PADLIST;
1367 # an undef CV still in lexical chain
1368 next if class($padlist) eq "SPECIAL";
1369 my @padlist = $padlist->ARRAY;
1370 my @ns = $padlist[0]->ARRAY;
1371
1372 for (my $i=0; $i<@ns; ++$i) {
1373 next if class($ns[$i]) eq "SPECIAL";
1374 if (class($ns[$i]) eq "PV") {
1375 # Probably that pesky lexical @_
1376 next;
1377 }
1378 my $name = $ns[$i]->PVX;
1379 my ($seq_st, $seq_en) =
1380 ($ns[$i]->FLAGS & SVf_FAKE)
1381 ? (0, 999999)
1382 : ($ns[$i]->COP_SEQ_RANGE_LOW, $ns[$i]->COP_SEQ_RANGE_HIGH);
1383
1384 push @{$self->{'curcvlex'}{
1385 ($ns[$i]->FLAGS & SVpad_OUR ? 'o' : 'm') . $name
1386 }}, [$seq_st, $seq_en];
1387 }
1388 }
1389}
1390
1391sub find_scope_st { ((find_scope(@_))[0]); }
1392sub find_scope_en { ((find_scope(@_))[1]); }
1393
1394# Recurses down the tree, looking for pad variable introductions and COPs
1395sub find_scope {
1396 my ($self, $op, $scope_st, $scope_en) = @_;
1397 carp("Undefined op in find_scope") if !defined $op;
1398 return ($scope_st, $scope_en) unless $op->flags & OPf_KIDS;
1399
1400 my @queue = ($op);
1401 while(my $op = shift @queue ) {
1402 for (my $o=$op->first; $$o; $o=$o->sibling) {
1403 if ($o->name =~ /^pad.v$/ && $o->private & OPpLVAL_INTRO) {
1404 my $s = int($self->padname_sv($o->targ)->COP_SEQ_RANGE_LOW);
1405 my $e = $self->padname_sv($o->targ)->COP_SEQ_RANGE_HIGH;
1406 $scope_st = $s if !defined($scope_st) || $s < $scope_st;
1407 $scope_en = $e if !defined($scope_en) || $e > $scope_en;
1408 return ($scope_st, $scope_en);
1409 }
1410 elsif (is_state($o)) {
1411 my $c = $o->cop_seq;
1412 $scope_st = $c if !defined($scope_st) || $c < $scope_st;
1413 $scope_en = $c if !defined($scope_en) || $c > $scope_en;
1414 return ($scope_st, $scope_en);
1415 }
1416 elsif ($o->flags & OPf_KIDS) {
1417 unshift (@queue, $o);
1418 }
1419 }
1420 }
1421
1422 return ($scope_st, $scope_en);
1423}
1424
1425# Returns a list of subs which should be inserted before the COP
1426sub cop_subs {
1427 my ($self, $op, $out_seq) = @_;
1428 my $seq = $op->cop_seq;
1429 # If we have nephews, then our sequence number indicates
1430 # the cop_seq of the end of some sort of scope.
1431 if (class($op->sibling) ne "NULL" && $op->sibling->flags & OPf_KIDS
1432 and my $nseq = $self->find_scope_st($op->sibling) ) {
1433 $seq = $nseq;
1434 }
1435 $seq = $out_seq if defined($out_seq) && $out_seq < $seq;
1436 return $self->seq_subs($seq);
1437}
1438
1439sub seq_subs {
1440 my ($self, $seq) = @_;
1441 my @text;
1442#push @text, "# ($seq)\n";
1443
1444 return "" if !defined $seq;
1445 while (scalar(@{$self->{'subs_todo'}})
1446 and $seq > $self->{'subs_todo'}[0][0]) {
1447 push @text, $self->next_todo;
1448 }
1449 return @text;
1450}
1451
1452sub _features_from_bundle {
1453 my ($hints, $hh) = @_;
1454 foreach (@{$feature::feature_bundle{@feature::hint_bundles[$hints >> $feature::hint_shift]}}) {
1455 $hh->{$feature::feature{$_}} = 1;
1456 }
1457 return $hh;
1458}
1459
1460# Notice how subs and formats are inserted between statements here;
1461# also $[ assignments and pragmas.
1462sub pp_nextstate {
1463 my $self = shift;
1464 my($op, $cx) = @_;
1465 $self->{'curcop'} = $op;
1466 my @text;
1467 push @text, $self->cop_subs($op);
1468 my $stash = $op->stashpv;
1469 if ($stash ne $self->{'curstash'}) {
1470 push @text, "package $stash;\n";
1471 $self->{'curstash'} = $stash;
1472 }
1473
1474 if (OPpCONST_ARYBASE && $self->{'arybase'} != $op->arybase) {
1475 push @text, '$[ = '. $op->arybase .";\n";
1476 $self->{'arybase'} = $op->arybase;
1477 }
1478
1479 my $warnings = $op->warnings;
1480 my $warning_bits;
1481 if ($warnings->isa("B::SPECIAL") && $$warnings == 4) {
1482 $warning_bits = $warnings::Bits{"all"} & WARN_MASK;
1483 }
1484 elsif ($warnings->isa("B::SPECIAL") && $$warnings == 5) {
1485 $warning_bits = $warnings::NONE;
1486 }
1487 elsif ($warnings->isa("B::SPECIAL")) {
1488 $warning_bits = undef;
1489 }
1490 else {
1491 $warning_bits = $warnings->PV & WARN_MASK;
1492 }
1493
1494 if (defined ($warning_bits) and
1495 !defined($self->{warnings}) || $self->{'warnings'} ne $warning_bits) {
1496 push @text, declare_warnings($self->{'warnings'}, $warning_bits);
1497 $self->{'warnings'} = $warning_bits;
1498 }
1499
1500 my $hints = $] < 5.008009 ? $op->private : $op->hints;
1501 my $old_hints = $self->{'hints'};
1502 if ($self->{'hints'} != $hints) {
1503 push @text, declare_hints($self->{'hints'}, $hints);
1504 $self->{'hints'} = $hints;
1505 }
1506
1507 my $newhh;
1508 if ($] > 5.009) {
1509 $newhh = $op->hints_hash->HASH;
1510 }
1511
1512 if ($] >= 5.015006) {
1513 # feature bundle hints
1514 my $from = $old_hints & $feature::hint_mask;
1515 my $to = $ hints & $feature::hint_mask;
1516 if ($from != $to) {
1517 if ($to == $feature::hint_mask) {
1518 if ($self->{'hinthash'}) {
1519 delete $self->{'hinthash'}{$_}
1520 for grep /^feature_/, keys %{$self->{'hinthash'}};
1521 }
1522 else { $self->{'hinthash'} = {} }
1523 $self->{'hinthash'}
1524 = _features_from_bundle($from, $self->{'hinthash'});
1525 }
1526 else {
1527 my $bundle =
1528 $feature::hint_bundles[$to >> $feature::hint_shift];
1529 $bundle =~ s/(\d[13579])\z/$1+1/e; # 5.11 => 5.12
1530 push @text, "no feature;\n",
1531 "use feature ':$bundle';\n";
1532 }
1533 }
1534 }
1535
1536 if ($] > 5.009) {
1537 push @text, declare_hinthash(
1538 $self->{'hinthash'}, $newhh,
1539 $self->{indent_size}, $self->{hints},
1540 );
1541 $self->{'hinthash'} = $newhh;
1542 }
1543
1544 # This should go after of any branches that add statements, to
1545 # increase the chances that it refers to the same line it did in
1546 # the original program.
1547 if ($self->{'linenums'}) {
1548 push @text, "\f#line " . $op->line .
1549 ' "' . $op->file, qq'"\n';
1550 }
1551
1552 push @text, $op->label . ": " if $op->label;
1553
1554 return join("", @text);
1555}
1556
1557sub declare_warnings {
1558 my ($from, $to) = @_;
1559 if (($to & WARN_MASK) eq (warnings::bits("all") & WARN_MASK)) {
1560 return "use warnings;\n";
1561 }
1562 elsif (($to & WARN_MASK) eq ("\0"x length($to) & WARN_MASK)) {
1563 return "no warnings;\n";
1564 }
1565 return "BEGIN {\${^WARNING_BITS} = ".perlstring($to)."}\n";
1566}
1567
1568sub declare_hints {
1569 my ($from, $to) = @_;
1570 my $use = $to & ~$from;
1571 my $no = $from & ~$to;
1572 my $decls = "";
1573 for my $pragma (hint_pragmas($use)) {
1574 $decls .= "use $pragma;\n";
1575 }
1576 for my $pragma (hint_pragmas($no)) {
1577 $decls .= "no $pragma;\n";
1578 }
1579 return $decls;
1580}
1581
1582# Internal implementation hints that the core sets automatically, so don't need
1583# (or want) to be passed back to the user
1584my %ignored_hints = (
1585 'open<' => 1,
1586 'open>' => 1,
1587 ':' => 1,
1588 'strict/refs' => 1,
1589 'strict/subs' => 1,
1590 'strict/vars' => 1,
1591);
1592
1593my %rev_feature;
1594
1595sub declare_hinthash {
1596 my ($from, $to, $indent, $hints) = @_;
1597 my $doing_features =
1598 ($hints & $feature::hint_mask) == $feature::hint_mask;
1599 my @decls;
1600 my @features;
1601 my @unfeatures; # bugs?
1602 for my $key (sort keys %$to) {
1603 next if $ignored_hints{$key};
1604 my $is_feature = $key =~ /^feature_/ && $^V ge 5.15.6;
1605 next if $is_feature and not $doing_features;
1606 if (!exists $from->{$key} or $from->{$key} ne $to->{$key}) {
1607 push(@features, $key), next if $is_feature;
1608 push @decls,
1609 qq(\$^H{) . single_delim("q", "'", $key) . qq(} = )
1610 . (
1611 defined $to->{$key}
1612 ? single_delim("q", "'", $to->{$key})
1613 : 'undef'
1614 )
1615 . qq(;);
1616 }
1617 }
1618 for my $key (sort keys %$from) {
1619 next if $ignored_hints{$key};
1620 my $is_feature = $key =~ /^feature_/ && $^V ge 5.15.6;
1621 next if $is_feature and not $doing_features;
1622 if (!exists $to->{$key}) {
1623 push(@unfeatures, $key), next if $is_feature;
1624 push @decls, qq(delete \$^H{'$key'};);
1625 }
1626 }
1627 my @ret;
1628 if (@features || @unfeatures) {
1629 if (!%rev_feature) { %rev_feature = reverse %feature::feature }
1630 }
1631 if (@features) {
1632 push @ret, "use feature "
1633 . join(", ", map "'$rev_feature{$_}'", @features) . ";\n";
1634 }
1635 if (@unfeatures) {
1636 push @ret, "no feature "
1637 . join(", ", map "'$rev_feature{$_}'", @unfeatures)
1638 . ";\n";
1639 }
1640 @decls and
1641 push @ret,
1642 join("\n" . (" " x $indent), "BEGIN {", @decls) . "\n}\n";
1643 return @ret;
1644}
1645
1646sub hint_pragmas {
1647 my ($bits) = @_;
1648 my (@pragmas, @strict);
1649 push @pragmas, "integer" if $bits & 0x1;
1650 for (sort keys %strict_bits) {
1651 push @strict, "'$_'" if $bits & $strict_bits{$_};
1652 }
1653 if (@strict == keys %strict_bits) {
1654 push @pragmas, "strict";
1655 }
1656 elsif (@strict) {
1657 push @pragmas, "strict " . join ', ', @strict;
1658 }
1659 push @pragmas, "bytes" if $bits & 0x8;
1660 return @pragmas;
1661}
1662
1663sub pp_dbstate { pp_nextstate(@_) }
1664sub pp_setstate { pp_nextstate(@_) }
1665
1666sub pp_unstack { return "" } # see also leaveloop
1667
1668my %feature_keywords = (
1669 # keyword => 'feature',
1670 state => 'state',
1671 say => 'say',
1672 given => 'switch',
1673 when => 'switch',
1674 default => 'switch',
1675 break => 'switch',
1676 evalbytes=>'evalbytes',
1677 __SUB__ => '__SUB__',
1678 fc => 'fc',
1679);
1680
1681sub keyword {
1682 my $self = shift;
1683 my $name = shift;
1684 return $name if $name =~ /^CORE::/; # just in case
1685 if (exists $feature_keywords{$name}) {
1686 my $hh;
1687 my $hints = $self->{hints} & $feature::hint_mask;
1688 if ($hints && $hints != $feature::hint_mask) {
1689 $hh = _features_from_bundle($hints);
1690 }
1691 elsif ($hints) { $hh = $self->{'hinthash'} }
1692 return "CORE::$name"
1693 if !$hh
1694 || !$hh->{"feature_$feature_keywords{$name}"}
1695 }
1696 if (
1697 $name !~ /^(?:chom?p|do|exec|glob|s(?:elect|ystem))\z/
1698 && !defined eval{prototype "CORE::$name"}
1699 ) { return $name }
1700 if (
1701 exists $self->{subs_declared}{$name}
1702 or
1703 exists &{"$self->{curstash}::$name"}
1704 ) {
1705 return "CORE::$name"
1706 }
1707 return $name;
1708}
1709
1710sub baseop {
1711 my $self = shift;
1712 my($op, $cx, $name) = @_;
1713 return $self->keyword($name);
1714}
1715
1716sub pp_stub {
1717 my $self = shift;
1718 my($op, $cx, $name) = @_;
1719 if ($cx >= 1) {
1720 return "()";
1721 }
1722 else {
1723 return "();";
1724 }
1725}
1726sub pp_wantarray { baseop(@_, "wantarray") }
1727sub pp_fork { baseop(@_, "fork") }
1728sub pp_wait { maybe_targmy(@_, \&baseop, "wait") }
1729sub pp_getppid { maybe_targmy(@_, \&baseop, "getppid") }
1730sub pp_time { maybe_targmy(@_, \&baseop, "time") }
1731sub pp_tms { baseop(@_, "times") }
1732sub pp_ghostent { baseop(@_, "gethostent") }
1733sub pp_gnetent { baseop(@_, "getnetent") }
1734sub pp_gprotoent { baseop(@_, "getprotoent") }
1735sub pp_gservent { baseop(@_, "getservent") }
1736sub pp_ehostent { baseop(@_, "endhostent") }
1737sub pp_enetent { baseop(@_, "endnetent") }
1738sub pp_eprotoent { baseop(@_, "endprotoent") }
1739sub pp_eservent { baseop(@_, "endservent") }
1740sub pp_gpwent { baseop(@_, "getpwent") }
1741sub pp_spwent { baseop(@_, "setpwent") }
1742sub pp_epwent { baseop(@_, "endpwent") }
1743sub pp_ggrent { baseop(@_, "getgrent") }
1744sub pp_sgrent { baseop(@_, "setgrent") }
1745sub pp_egrent { baseop(@_, "endgrent") }
1746sub pp_getlogin { baseop(@_, "getlogin") }
1747
1748sub POSTFIX () { 1 }
1749
1750# I couldn't think of a good short name, but this is the category of
1751# symbolic unary operators with interesting precedence
1752
1753sub pfixop {
1754 my $self = shift;
1755 my($op, $cx, $name, $prec, $flags) = (@_, 0);
1756 my $kid = $op->first;
1757 $kid = $self->deparse($kid, $prec);
1758 return $self->maybe_parens(($flags & POSTFIX)
1759 ? "$kid$name"
1760 # avoid confusion with filetests
1761 : $name eq '-'
1762 && $kid =~ /^[a-zA-Z](?!\w)/
1763 ? "$name($kid)"
1764 : "$name$kid",
1765 $cx, $prec);
1766}
1767
1768sub pp_preinc { pfixop(@_, "++", 23) }
1769sub pp_predec { pfixop(@_, "--", 23) }
1770sub pp_postinc { maybe_targmy(@_, \&pfixop, "++", 23, POSTFIX) }
1771sub pp_postdec { maybe_targmy(@_, \&pfixop, "--", 23, POSTFIX) }
1772sub pp_i_preinc { pfixop(@_, "++", 23) }
1773sub pp_i_predec { pfixop(@_, "--", 23) }
1774sub pp_i_postinc { maybe_targmy(@_, \&pfixop, "++", 23, POSTFIX) }
1775sub pp_i_postdec { maybe_targmy(@_, \&pfixop, "--", 23, POSTFIX) }
1776sub pp_complement { maybe_targmy(@_, \&pfixop, "~", 21) }
1777
1778sub pp_negate { maybe_targmy(@_, \&real_negate) }
1779sub real_negate {
1780 my $self = shift;
1781 my($op, $cx) = @_;
1782 if ($op->first->name =~ /^(i_)?negate$/) {
1783 # avoid --$x
1784 $self->pfixop($op, $cx, "-", 21.5);
1785 } else {
1786 $self->pfixop($op, $cx, "-", 21);
1787 }
1788}
1789sub pp_i_negate { pp_negate(@_) }
1790
1791sub pp_not {
1792 my $self = shift;
1793 my($op, $cx) = @_;
1794 if ($cx <= 4) {
1795 $self->listop($op, $cx, "not", $op->first);
1796 } else {
1797 $self->pfixop($op, $cx, "!", 21);
1798 }
1799}
1800
1801sub unop {
1802 my $self = shift;
1803 my($op, $cx, $name, $nollafr) = @_;
1804 my $kid;
1805 if ($op->flags & OPf_KIDS) {
1806 $kid = $op->first;
1807 if (not $name) {
1808 # this deals with 'boolkeys' right now
1809 return $self->deparse($kid,$cx);
1810 }
1811 my $builtinname = $name;
1812 $builtinname =~ /^CORE::/ or $builtinname = "CORE::$name";
1813 if (defined prototype($builtinname)
1814 && prototype($builtinname) =~ /^;?\*/
1815 && $kid->name eq "rv2gv") {
1816 $kid = $kid->first;
1817 }
1818
1819 if ($nollafr) {
1820 ($kid = $self->deparse($kid, 16)) =~ s/^\cS//;
1821 return $self->maybe_parens(
1822 $self->keyword($name) . " $kid", $cx, 16
1823 );
1824 }
1825 return $self->maybe_parens_unop($name, $kid, $cx);
1826 } else {
1827 return $self->maybe_parens(
1828 $self->keyword($name) . ($op->flags & OPf_SPECIAL ? "()" : ""),
1829 $cx, 16,
1830 );
1831 }
1832}
1833
1834sub pp_chop { maybe_targmy(@_, \&unop, "chop") }
1835sub pp_chomp { maybe_targmy(@_, \&unop, "chomp") }
1836sub pp_schop { maybe_targmy(@_, \&unop, "chop") }
1837sub pp_schomp { maybe_targmy(@_, \&unop, "chomp") }
1838sub pp_defined { unop(@_, "defined") }
1839sub pp_undef { unop(@_, "undef") }
1840sub pp_study { unop(@_, "study") }
1841sub pp_ref { unop(@_, "ref") }
1842sub pp_pos { maybe_local(@_, unop(@_, "pos")) }
1843
1844sub pp_sin { maybe_targmy(@_, \&unop, "sin") }
1845sub pp_cos { maybe_targmy(@_, \&unop, "cos") }
1846sub pp_rand { maybe_targmy(@_, \&unop, "rand") }
1847sub pp_srand { unop(@_, "srand") }
1848sub pp_exp { maybe_targmy(@_, \&unop, "exp") }
1849sub pp_log { maybe_targmy(@_, \&unop, "log") }
1850sub pp_sqrt { maybe_targmy(@_, \&unop, "sqrt") }
1851sub pp_int { maybe_targmy(@_, \&unop, "int") }
1852sub pp_hex { maybe_targmy(@_, \&unop, "hex") }
1853sub pp_oct { maybe_targmy(@_, \&unop, "oct") }
1854sub pp_abs { maybe_targmy(@_, \&unop, "abs") }
1855
1856sub pp_length { maybe_targmy(@_, \&unop, "length") }
1857sub pp_ord { maybe_targmy(@_, \&unop, "ord") }
1858sub pp_chr { maybe_targmy(@_, \&unop, "chr") }
1859
1860sub pp_each { unop(@_, "each") }
1861sub pp_values { unop(@_, "values") }
1862sub pp_keys { unop(@_, "keys") }
1863{ no strict 'refs'; *{"pp_r$_"} = *{"pp_$_"} for qw< keys each values >; }
1864sub pp_boolkeys {
1865 # no name because its an optimisation op that has no keyword
1866 unop(@_,"");
1867}
1868sub pp_aeach { unop(@_, "each") }
1869sub pp_avalues { unop(@_, "values") }
1870sub pp_akeys { unop(@_, "keys") }
1871sub pp_pop { unop(@_, "pop") }
1872sub pp_shift { unop(@_, "shift") }
1873
1874sub pp_caller { unop(@_, "caller") }
1875sub pp_reset { unop(@_, "reset") }
1876sub pp_exit { unop(@_, "exit") }
1877sub pp_prototype { unop(@_, "prototype") }
1878
1879sub pp_close { unop(@_, "close") }
1880sub pp_fileno { unop(@_, "fileno") }
1881sub pp_umask { unop(@_, "umask") }
1882sub pp_untie { unop(@_, "untie") }
1883sub pp_tied { unop(@_, "tied") }
1884sub pp_dbmclose { unop(@_, "dbmclose") }
1885sub pp_getc { unop(@_, "getc") }
1886sub pp_eof { unop(@_, "eof") }
1887sub pp_tell { unop(@_, "tell") }
1888sub pp_getsockname { unop(@_, "getsockname") }
1889sub pp_getpeername { unop(@_, "getpeername") }
1890
1891sub pp_chdir { maybe_targmy(@_, \&unop, "chdir") }
1892sub pp_chroot { maybe_targmy(@_, \&unop, "chroot") }
1893sub pp_readlink { unop(@_, "readlink") }
1894sub pp_rmdir { maybe_targmy(@_, \&unop, "rmdir") }
1895sub pp_readdir { unop(@_, "readdir") }
1896sub pp_telldir { unop(@_, "telldir") }
1897sub pp_rewinddir { unop(@_, "rewinddir") }
1898sub pp_closedir { unop(@_, "closedir") }
1899sub pp_getpgrp { maybe_targmy(@_, \&unop, "getpgrp") }
1900sub pp_localtime { unop(@_, "localtime") }
1901sub pp_gmtime { unop(@_, "gmtime") }
1902sub pp_alarm { unop(@_, "alarm") }
1903sub pp_sleep { maybe_targmy(@_, \&unop, "sleep") }
1904
1905sub pp_dofile {
1906 my $code = unop(@_, "do", 1); # llafr does not apply
1907 if ($code =~ s/^((?:CORE::)?do) \{/$1({/) { $code .= ')' }
1908 $code;
1909}
1910sub pp_entereval {
1911 unop(
1912 @_,
1913 $_[1]->private & OPpEVAL_BYTES ? $_[0]->keyword('evalbytes') : "eval"
1914 )
1915}
1916
1917sub pp_ghbyname { unop(@_, "gethostbyname") }
1918sub pp_gnbyname { unop(@_, "getnetbyname") }
1919sub pp_gpbyname { unop(@_, "getprotobyname") }
1920sub pp_shostent { unop(@_, "sethostent") }
1921sub pp_snetent { unop(@_, "setnetent") }
1922sub pp_sprotoent { unop(@_, "setprotoent") }
1923sub pp_sservent { unop(@_, "setservent") }
1924sub pp_gpwnam { unop(@_, "getpwnam") }
1925sub pp_gpwuid { unop(@_, "getpwuid") }
1926sub pp_ggrnam { unop(@_, "getgrnam") }
1927sub pp_ggrgid { unop(@_, "getgrgid") }
1928
1929sub pp_lock { unop(@_, "lock") }
1930
1931sub pp_continue { unop(@_, "continue"); }
1932sub pp_break { unop(@_, "break"); }
1933
1934sub givwhen {
1935 my $self = shift;
1936 my($op, $cx, $givwhen) = @_;
1937
1938 my $enterop = $op->first;
1939 my ($head, $block);
1940 if ($enterop->flags & OPf_SPECIAL) {
1941 $head = $self->keyword("default");
1942 $block = $self->deparse($enterop->first, 0);
1943 }
1944 else {
1945 my $cond = $enterop->first;
1946 my $cond_str = $self->deparse($cond, 1);
1947 $head = "$givwhen ($cond_str)";
1948 $block = $self->deparse($cond->sibling, 0);
1949 }
1950
1951 return "$head {\n".
1952 "\t$block\n".
1953 "\b}\cK";
1954}
1955
1956sub pp_leavegiven { givwhen(@_, $_[0]->keyword("given")); }
1957sub pp_leavewhen { givwhen(@_, $_[0]->keyword("when")); }
1958
1959sub pp_exists {
1960 my $self = shift;
1961 my($op, $cx) = @_;
1962 my $arg;
1963 if ($op->private & OPpEXISTS_SUB) {
1964 # Checking for the existence of a subroutine
1965 return $self->maybe_parens_func("exists",
1966 $self->pp_rv2cv($op->first, 16), $cx, 16);
1967 }
1968 if ($op->flags & OPf_SPECIAL) {
1969 # Array element, not hash element
1970 return $self->maybe_parens_func("exists",
1971 $self->pp_aelem($op->first, 16), $cx, 16);
1972 }
1973 return $self->maybe_parens_func("exists", $self->pp_helem($op->first, 16),
1974 $cx, 16);
1975}
1976
1977sub pp_delete {
1978 my $self = shift;
1979 my($op, $cx) = @_;
1980 my $arg;
1981 if ($op->private & OPpSLICE) {
1982 if ($op->flags & OPf_SPECIAL) {
1983 # Deleting from an array, not a hash
1984 return $self->maybe_parens_func("delete",
1985 $self->pp_aslice($op->first, 16),
1986 $cx, 16);
1987 }
1988 return $self->maybe_parens_func("delete",
1989 $self->pp_hslice($op->first, 16),
1990 $cx, 16);
1991 } else {
1992 if ($op->flags & OPf_SPECIAL) {
1993 # Deleting from an array, not a hash
1994 return $self->maybe_parens_func("delete",
1995 $self->pp_aelem($op->first, 16),
1996 $cx, 16);
1997 }
1998 return $self->maybe_parens_func("delete",
1999 $self->pp_helem($op->first, 16),
2000 $cx, 16);
2001 }
2002}
2003
2004sub pp_require {
2005 my $self = shift;
2006 my($op, $cx) = @_;
2007 my $opname = $op->flags & OPf_SPECIAL ? 'CORE::require' : 'require';
2008 if (class($op) eq "UNOP" and $op->first->name eq "const"
2009 and $op->first->private & OPpCONST_BARE)
2010 {
2011 my $name = $self->const_sv($op->first)->PV;
2012 $name =~ s[/][::]g;
2013 $name =~ s/\.pm//g;
2014 return $self->maybe_parens("$opname $name", $cx, 16);
2015 } else {
2016 $self->unop(
2017 $op, $cx,
2018 $op->first->name eq 'const'
2019 && $op->first->private & OPpCONST_NOVER
2020 ? "no"
2021 : $opname,
2022 1, # llafr does not apply
2023 );
2024 }
2025}
2026
2027sub pp_scalar {
2028 my $self = shift;
2029 my($op, $cx) = @_;
2030 my $kid = $op->first;
2031 if (not null $kid->sibling) {
2032 # XXX Was a here-doc
2033 return $self->dquote($op);
2034 }
2035 $self->unop(@_, "scalar");
2036}
2037
2038
2039sub padval {
2040 my $self = shift;
2041 my $targ = shift;
2042 return $self->{'curcv'}->PADLIST->ARRAYelt(1)->ARRAYelt($targ);
2043}
2044
2045sub anon_hash_or_list {
2046 my $self = shift;
2047 my($op, $cx) = @_;
2048
2049 my($pre, $post) = @{{"anonlist" => ["[","]"],
2050 "anonhash" => ["{","}"]}->{$op->name}};
2051 my($expr, @exprs);
2052 $op = $op->first->sibling; # skip pushmark
2053 for (; !null($op); $op = $op->sibling) {
2054 $expr = $self->deparse($op, 6);
2055 push @exprs, $expr;
2056 }
2057 if ($pre eq "{" and $cx < 1) {
2058 # Disambiguate that it's not a block
2059 $pre = "+{";
2060 }
2061 return $pre . join(", ", @exprs) . $post;
2062}
2063
2064sub pp_anonlist {
2065 my $self = shift;
2066 my ($op, $cx) = @_;
2067 if ($op->flags & OPf_SPECIAL) {
2068 return $self->anon_hash_or_list($op, $cx);
2069 }
2070 warn "Unexpected op pp_" . $op->name() . " without OPf_SPECIAL";
2071 return 'XXX';
2072}
2073
2074*pp_anonhash = \&pp_anonlist;
2075
2076sub pp_refgen {
2077 my $self = shift;
2078 my($op, $cx) = @_;
2079 my $kid = $op->first;
2080 if ($kid->name eq "null") {
2081 $kid = $kid->first;
2082 if (!null($kid->sibling) and
2083 $kid->sibling->name eq "anoncode") {
2084 return $self->e_anoncode({ code => $self->padval($kid->sibling->targ) });
2085 } elsif ($kid->name eq "pushmark") {
2086 my $sib_name = $kid->sibling->name;
2087 if ($sib_name =~ /^(pad|rv2)[ah]v$/
2088 and not $kid->sibling->flags & OPf_REF)
2089 {
2090 # The @a in \(@a) isn't in ref context, but only when the
2091 # parens are there.
2092 return "\\(" . $self->pp_list($op->first) . ")";
2093 } elsif ($sib_name eq 'entersub') {
2094 my $text = $self->deparse($kid->sibling, 1);
2095 # Always show parens for \(&func()), but only with -p otherwise
2096 $text = "($text)" if $self->{'parens'}
2097 or $kid->sibling->private & OPpENTERSUB_AMPER;
2098 return "\\$text";
2099 }
2100 }
2101 }
2102 $self->pfixop($op, $cx, "\\", 20);
2103}
2104
2105sub e_anoncode {
2106 my ($self, $info) = @_;
2107 my $text = $self->deparse_sub($info->{code});
2108 return "sub " . $text;
2109}
2110
2111sub pp_srefgen { pp_refgen(@_) }
2112
2113sub pp_readline {
2114 my $self = shift;
2115 my($op, $cx) = @_;
2116 my $kid = $op->first;
2117 $kid = $kid->first if $kid->name eq "rv2gv"; # <$fh>
2118 return "<" . $self->deparse($kid, 1) . ">" if is_scalar($kid);
2119 return $self->unop($op, $cx, "readline");
2120}
2121
2122sub pp_rcatline {
2123 my $self = shift;
2124 my($op) = @_;
2125 return "<" . $self->gv_name($self->gv_or_padgv($op)) . ">";
2126}
2127
2128# Unary operators that can occur as pseudo-listops inside double quotes
2129sub dq_unop {
2130 my $self = shift;
2131 my($op, $cx, $name, $prec, $flags) = (@_, 0, 0);
2132 my $kid;
2133 if ($op->flags & OPf_KIDS) {
2134 $kid = $op->first;
2135 # If there's more than one kid, the first is an ex-pushmark.
2136 $kid = $kid->sibling if not null $kid->sibling;
2137 return $self->maybe_parens_unop($name, $kid, $cx);
2138 } else {
2139 return $name . ($op->flags & OPf_SPECIAL ? "()" : "");
2140 }
2141}
2142
2143sub pp_ucfirst { dq_unop(@_, "ucfirst") }
2144sub pp_lcfirst { dq_unop(@_, "lcfirst") }
2145sub pp_uc { dq_unop(@_, "uc") }
2146sub pp_lc { dq_unop(@_, "lc") }
2147sub pp_quotemeta { maybe_targmy(@_, \&dq_unop, "quotemeta") }
2148sub pp_fc { dq_unop(@_, "fc") }
2149
2150sub loopex {
2151 my $self = shift;
2152 my ($op, $cx, $name) = @_;
2153 if (class($op) eq "PVOP") {
2154 $name .= " " . $op->pv;
2155 } elsif (class($op) eq "OP") {
2156 # no-op
2157 } elsif (class($op) eq "UNOP") {
2158 (my $kid = $self->deparse($op->first, 7)) =~ s/^\cS//;
2159 $name .= " $kid";
2160 }
2161 return $self->maybe_parens($name, $cx, 7);
2162}
2163
2164sub pp_last { loopex(@_, "last") }
2165sub pp_next { loopex(@_, "next") }
2166sub pp_redo { loopex(@_, "redo") }
2167sub pp_goto { loopex(@_, "goto") }
2168sub pp_dump { loopex(@_, "CORE::dump") }
2169
2170sub ftst {
2171 my $self = shift;
2172 my($op, $cx, $name) = @_;
2173 if (class($op) eq "UNOP") {
2174 # Genuine '-X' filetests are exempt from the LLAFR, but not
2175 # l?stat()
2176 if ($name =~ /^-/) {
2177 (my $kid = $self->deparse($op->first, 16)) =~ s/^\cS//;
2178 return $self->maybe_parens("$name $kid", $cx, 16);
2179 }
2180 return $self->maybe_parens_unop($name, $op->first, $cx);
2181 } elsif (class($op) =~ /^(SV|PAD)OP$/) {
2182 return $self->maybe_parens_func($name, $self->pp_gv($op, 1), $cx, 16);
2183 } else { # I don't think baseop filetests ever survive ck_ftst, but...
2184 return $name;
2185 }
2186}
2187
2188sub pp_lstat { ftst(@_, "lstat") }
2189sub pp_stat { ftst(@_, "stat") }
2190sub pp_ftrread { ftst(@_, "-R") }
2191sub pp_ftrwrite { ftst(@_, "-W") }
2192sub pp_ftrexec { ftst(@_, "-X") }
2193sub pp_fteread { ftst(@_, "-r") }
2194sub pp_ftewrite { ftst(@_, "-w") }
2195sub pp_fteexec { ftst(@_, "-x") }
2196sub pp_ftis { ftst(@_, "-e") }
2197sub pp_fteowned { ftst(@_, "-O") }
2198sub pp_ftrowned { ftst(@_, "-o") }
2199sub pp_ftzero { ftst(@_, "-z") }
2200sub pp_ftsize { ftst(@_, "-s") }
2201sub pp_ftmtime { ftst(@_, "-M") }
2202sub pp_ftatime { ftst(@_, "-A") }
2203sub pp_ftctime { ftst(@_, "-C") }
2204sub pp_ftsock { ftst(@_, "-S") }
2205sub pp_ftchr { ftst(@_, "-c") }
2206sub pp_ftblk { ftst(@_, "-b") }
2207sub pp_ftfile { ftst(@_, "-f") }
2208sub pp_ftdir { ftst(@_, "-d") }
2209sub pp_ftpipe { ftst(@_, "-p") }
2210sub pp_ftlink { ftst(@_, "-l") }
2211sub pp_ftsuid { ftst(@_, "-u") }
2212sub pp_ftsgid { ftst(@_, "-g") }
2213sub pp_ftsvtx { ftst(@_, "-k") }
2214sub pp_fttty { ftst(@_, "-t") }
2215sub pp_fttext { ftst(@_, "-T") }
2216sub pp_ftbinary { ftst(@_, "-B") }
2217
2218sub SWAP_CHILDREN () { 1 }
2219sub ASSIGN () { 2 } # has OP= variant
2220sub LIST_CONTEXT () { 4 } # Assignment is in list context
2221
2222my(%left, %right);
2223
2224sub assoc_class {
2225 my $op = shift;
2226 my $name = $op->name;
2227 if ($name eq "concat" and $op->first->name eq "concat") {
2228 # avoid spurious '=' -- see comment in pp_concat
2229 return "concat";
2230 }
2231 if ($name eq "null" and class($op) eq "UNOP"
2232 and $op->first->name =~ /^(and|x?or)$/
2233 and null $op->first->sibling)
2234 {
2235 # Like all conditional constructs, OP_ANDs and OP_ORs are topped
2236 # with a null that's used as the common end point of the two
2237 # flows of control. For precedence purposes, ignore it.
2238 # (COND_EXPRs have these too, but we don't bother with
2239 # their associativity).
2240 return assoc_class($op->first);
2241 }
2242 return $name . ($op->flags & OPf_STACKED ? "=" : "");
2243}
2244
2245# Left associative operators, like '+', for which
2246# $a + $b + $c is equivalent to ($a + $b) + $c
2247
2248BEGIN {
2249 %left = ('multiply' => 19, 'i_multiply' => 19,
2250 'divide' => 19, 'i_divide' => 19,
2251 'modulo' => 19, 'i_modulo' => 19,
2252 'repeat' => 19,
2253 'add' => 18, 'i_add' => 18,
2254 'subtract' => 18, 'i_subtract' => 18,
2255 'concat' => 18,
2256 'left_shift' => 17, 'right_shift' => 17,
2257 'bit_and' => 13,
2258 'bit_or' => 12, 'bit_xor' => 12,
2259 'and' => 3,
2260 'or' => 2, 'xor' => 2,
2261 );
2262}
2263
2264sub deparse_binop_left {
2265 my $self = shift;
2266 my($op, $left, $prec) = @_;
2267 if ($left{assoc_class($op)} && $left{assoc_class($left)}
2268 and $left{assoc_class($op)} == $left{assoc_class($left)})
2269 {
2270 return $self->deparse($left, $prec - .00001);
2271 } else {
2272 return $self->deparse($left, $prec);
2273 }
2274}
2275
2276# Right associative operators, like '=', for which
2277# $a = $b = $c is equivalent to $a = ($b = $c)
2278
2279BEGIN {
2280 %right = ('pow' => 22,
2281 'sassign=' => 7, 'aassign=' => 7,
2282 'multiply=' => 7, 'i_multiply=' => 7,
2283 'divide=' => 7, 'i_divide=' => 7,
2284 'modulo=' => 7, 'i_modulo=' => 7,
2285 'repeat=' => 7,
2286 'add=' => 7, 'i_add=' => 7,
2287 'subtract=' => 7, 'i_subtract=' => 7,
2288 'concat=' => 7,
2289 'left_shift=' => 7, 'right_shift=' => 7,
2290 'bit_and=' => 7,
2291 'bit_or=' => 7, 'bit_xor=' => 7,
2292 'andassign' => 7,
2293 'orassign' => 7,
2294 );
2295}
2296
2297sub deparse_binop_right {
2298 my $self = shift;
2299 my($op, $right, $prec) = @_;
2300 if ($right{assoc_class($op)} && $right{assoc_class($right)}
2301 and $right{assoc_class($op)} == $right{assoc_class($right)})
2302 {
2303 return $self->deparse($right, $prec - .00001);
2304 } else {
2305 return $self->deparse($right, $prec);
2306 }
2307}
2308
2309sub binop {
2310 my $self = shift;
2311 my ($op, $cx, $opname, $prec, $flags) = (@_, 0);
2312 my $left = $op->first;
2313 my $right = $op->last;
2314 my $eq = "";
2315 if ($op->flags & OPf_STACKED && $flags & ASSIGN) {
2316 $eq = "=";
2317 $prec = 7;
2318 }
2319 if ($flags & SWAP_CHILDREN) {
2320 ($left, $right) = ($right, $left);
2321 }
2322 $left = $self->deparse_binop_left($op, $left, $prec);
2323 $left = "($left)" if $flags & LIST_CONTEXT
2324 && $left !~ /^(my|our|local|)[\@\(]/;
2325 $right = $self->deparse_binop_right($op, $right, $prec);
2326 return $self->maybe_parens("$left $opname$eq $right", $cx, $prec);
2327}
2328
2329sub pp_add { maybe_targmy(@_, \&binop, "+", 18, ASSIGN) }
2330sub pp_multiply { maybe_targmy(@_, \&binop, "*", 19, ASSIGN) }
2331sub pp_subtract { maybe_targmy(@_, \&binop, "-",18, ASSIGN) }
2332sub pp_divide { maybe_targmy(@_, \&binop, "/", 19, ASSIGN) }
2333sub pp_modulo { maybe_targmy(@_, \&binop, "%", 19, ASSIGN) }
2334sub pp_i_add { maybe_targmy(@_, \&binop, "+", 18, ASSIGN) }
2335sub pp_i_multiply { maybe_targmy(@_, \&binop, "*", 19, ASSIGN) }
2336sub pp_i_subtract { maybe_targmy(@_, \&binop, "-", 18, ASSIGN) }
2337sub pp_i_divide { maybe_targmy(@_, \&binop, "/", 19, ASSIGN) }
2338sub pp_i_modulo { maybe_targmy(@_, \&binop, "%", 19, ASSIGN) }
2339sub pp_pow { maybe_targmy(@_, \&binop, "**", 22, ASSIGN) }
2340
2341sub pp_left_shift { maybe_targmy(@_, \&binop, "<<", 17, ASSIGN) }
2342sub pp_right_shift { maybe_targmy(@_, \&binop, ">>", 17, ASSIGN) }
2343sub pp_bit_and { maybe_targmy(@_, \&binop, "&", 13, ASSIGN) }
2344sub pp_bit_or { maybe_targmy(@_, \&binop, "|", 12, ASSIGN) }
2345sub pp_bit_xor { maybe_targmy(@_, \&binop, "^", 12, ASSIGN) }
2346
2347sub pp_eq { binop(@_, "==", 14) }
2348sub pp_ne { binop(@_, "!=", 14) }
2349sub pp_lt { binop(@_, "<", 15) }
2350sub pp_gt { binop(@_, ">", 15) }
2351sub pp_ge { binop(@_, ">=", 15) }
2352sub pp_le { binop(@_, "<=", 15) }
2353sub pp_ncmp { binop(@_, "<=>", 14) }
2354sub pp_i_eq { binop(@_, "==", 14) }
2355sub pp_i_ne { binop(@_, "!=", 14) }
2356sub pp_i_lt { binop(@_, "<", 15) }
2357sub pp_i_gt { binop(@_, ">", 15) }
2358sub pp_i_ge { binop(@_, ">=", 15) }
2359sub pp_i_le { binop(@_, "<=", 15) }
2360sub pp_i_ncmp { binop(@_, "<=>", 14) }
2361
2362sub pp_seq { binop(@_, "eq", 14) }
2363sub pp_sne { binop(@_, "ne", 14) }
2364sub pp_slt { binop(@_, "lt", 15) }
2365sub pp_sgt { binop(@_, "gt", 15) }
2366sub pp_sge { binop(@_, "ge", 15) }
2367sub pp_sle { binop(@_, "le", 15) }
2368sub pp_scmp { binop(@_, "cmp", 14) }
2369
2370sub pp_sassign { binop(@_, "=", 7, SWAP_CHILDREN) }
2371sub pp_aassign { binop(@_, "=", 7, SWAP_CHILDREN | LIST_CONTEXT) }
2372
2373sub pp_smartmatch {
2374 my ($self, $op, $cx) = @_;
2375 if ($op->flags & OPf_SPECIAL) {
2376 return $self->deparse($op->last, $cx);
2377 }
2378 else {
2379 binop(@_, "~~", 14);
2380 }
2381}
2382
2383# '.' is special because concats-of-concats are optimized to save copying
2384# by making all but the first concat stacked. The effect is as if the
2385# programmer had written '($a . $b) .= $c', except legal.
2386sub pp_concat { maybe_targmy(@_, \&real_concat) }
2387sub real_concat {
2388 my $self = shift;
2389 my($op, $cx) = @_;
2390 my $left = $op->first;
2391 my $right = $op->last;
2392 my $eq = "";
2393 my $prec = 18;
2394 if ($op->flags & OPf_STACKED and $op->first->name ne "concat") {
2395 $eq = "=";
2396 $prec = 7;
2397 }
2398 $left = $self->deparse_binop_left($op, $left, $prec);
2399 $right = $self->deparse_binop_right($op, $right, $prec);
2400 return $self->maybe_parens("$left .$eq $right", $cx, $prec);
2401}
2402
2403# 'x' is weird when the left arg is a list
2404sub pp_repeat {
2405 my $self = shift;
2406 my($op, $cx) = @_;
2407 my $left = $op->first;
2408 my $right = $op->last;
2409 my $eq = "";
2410 my $prec = 19;
2411 if ($op->flags & OPf_STACKED) {
2412 $eq = "=";
2413 $prec = 7;
2414 }
2415 if (null($right)) { # list repeat; count is inside left-side ex-list
2416 my $kid = $left->first->sibling; # skip pushmark
2417 my @exprs;
2418 for (; !null($kid->sibling); $kid = $kid->sibling) {
2419 push @exprs, $self->deparse($kid, 6);
2420 }
2421 $right = $kid;
2422 $left = "(" . join(", ", @exprs). ")";
2423 } else {
2424 $left = $self->deparse_binop_left($op, $left, $prec);
2425 }
2426 $right = $self->deparse_binop_right($op, $right, $prec);
2427 return $self->maybe_parens("$left x$eq $right", $cx, $prec);
2428}
2429
2430sub range {
2431 my $self = shift;
2432 my ($op, $cx, $type) = @_;
2433 my $left = $op->first;
2434 my $right = $left->sibling;
2435 $left = $self->deparse($left, 9);
2436 $right = $self->deparse($right, 9);
2437 return $self->maybe_parens("$left $type $right", $cx, 9);
2438}
2439
2440sub pp_flop {
2441 my $self = shift;
2442 my($op, $cx) = @_;
2443 my $flip = $op->first;
2444 my $type = ($flip->flags & OPf_SPECIAL) ? "..." : "..";
2445 return $self->range($flip->first, $cx, $type);
2446}
2447
2448# one-line while/until is handled in pp_leave
2449
2450sub logop {
2451 my $self = shift;
2452 my ($op, $cx, $lowop, $lowprec, $highop, $highprec, $blockname) = @_;
2453 my $left = $op->first;
2454 my $right = $op->first->sibling;
2455 if ($cx < 1 and is_scope($right) and $blockname
2456 and $self->{'expand'} < 7)
2457 { # if ($a) {$b}
2458 $left = $self->deparse($left, 1);
2459 $right = $self->deparse($right, 0);
2460 return "$blockname ($left) {\n\t$right\n\b}\cK";
2461 } elsif ($cx < 1 and $blockname and not $self->{'parens'}
2462 and $self->{'expand'} < 7) { # $b if $a
2463 $right = $self->deparse($right, 1);
2464 $left = $self->deparse($left, 1);
2465 return "$right $blockname $left";
2466 } elsif ($cx > $lowprec and $highop) { # $a && $b
2467 $left = $self->deparse_binop_left($op, $left, $highprec);
2468 $right = $self->deparse_binop_right($op, $right, $highprec);
2469 return $self->maybe_parens("$left $highop $right", $cx, $highprec);
2470 } else { # $a and $b
2471 $left = $self->deparse_binop_left($op, $left, $lowprec);
2472 $right = $self->deparse_binop_right($op, $right, $lowprec);
2473 return $self->maybe_parens("$left $lowop $right", $cx, $lowprec);
2474 }
2475}
2476
2477sub pp_and { logop(@_, "and", 3, "&&", 11, "if") }
2478sub pp_or { logop(@_, "or", 2, "||", 10, "unless") }
2479sub pp_dor { logop(@_, "//", 10) }
2480
2481# xor is syntactically a logop, but it's really a binop (contrary to
2482# old versions of opcode.pl). Syntax is what matters here.
2483sub pp_xor { logop(@_, "xor", 2, "", 0, "") }
2484
2485sub logassignop {
2486 my $self = shift;
2487 my ($op, $cx, $opname) = @_;
2488 my $left = $op->first;
2489 my $right = $op->first->sibling->first; # skip sassign
2490 $left = $self->deparse($left, 7);
2491 $right = $self->deparse($right, 7);
2492 return $self->maybe_parens("$left $opname $right", $cx, 7);
2493}
2494
2495sub pp_andassign { logassignop(@_, "&&=") }
2496sub pp_orassign { logassignop(@_, "||=") }
2497sub pp_dorassign { logassignop(@_, "//=") }
2498
2499sub rv2gv_or_string {
2500 my($self,$op) = @_;
2501 if ($op->name eq "gv") { # could be open("open") or open("###")
2502 my($name,$quoted) =
2503 $self->stash_variable_name("", $self->gv_or_padgv($op));
2504 $quoted ? $name : "*$name";
2505 }
2506 else {
2507 $self->deparse($op, 6);
2508 }
2509}
2510
2511sub listop {
2512 my $self = shift;
2513 my($op, $cx, $name, $kid, $nollafr) = @_;
2514 my(@exprs);
2515 my $parens = ($cx >= 5) || $self->{'parens'};
2516 $kid ||= $op->first->sibling;
2517 # If there are no arguments, add final parentheses (or parenthesize the
2518 # whole thing if the llafr does not apply) to account for cases like
2519 # (return)+1 or setpgrp()+1. When the llafr does not apply, we use a
2520 # precedence of 6 (< comma), as "return, 1" does not need parentheses.
2521 if (null $kid) {
2522 return $nollafr
2523 ? $self->maybe_parens($self->keyword($name), $cx, 7)
2524 : $self->keyword($name) . '()' x (7 < $cx);
2525 }
2526 my $first;
2527 $name = "socketpair" if $name eq "sockpair";
2528 my $fullname = $self->keyword($name);
2529 my $proto = prototype("CORE::$name");
2530 if (defined $proto
2531 && $proto =~ /^;?\*/
2532 && $kid->name eq "rv2gv" && !($kid->private & OPpLVAL_INTRO)) {
2533 $first = $self->rv2gv_or_string($kid->first);
2534 }
2535 else {
2536 $first = $self->deparse($kid, 6);
2537 }
2538 if ($name eq "chmod" && $first =~ /^\d+$/) {
2539 $first = sprintf("%#o", $first);
2540 }
2541 $first = "+$first"
2542 if not $parens and not $nollafr and substr($first, 0, 1) eq "(";
2543 push @exprs, $first;
2544 $kid = $kid->sibling;
2545 if (defined $proto && $proto =~ /^\*\*/ && $kid->name eq "rv2gv"
2546 && !($kid->private & OPpLVAL_INTRO)) {
2547 push @exprs, $first = $self->rv2gv_or_string($kid->first);
2548 $kid = $kid->sibling;
2549 }
2550 for (; !null($kid); $kid = $kid->sibling) {
2551 push @exprs, $self->deparse($kid, 6);
2552 }
2553 if ($name eq "reverse" && ($op->private & OPpREVERSE_INPLACE)) {
2554 return "$exprs[0] = $fullname"
2555 . ($parens ? "($exprs[0])" : " $exprs[0]");
2556 }
2557 if ($parens && $nollafr) {
2558 return "($fullname " . join(", ", @exprs) . ")";
2559 } elsif ($parens) {
2560 return "$fullname(" . join(", ", @exprs) . ")";
2561 } else {
2562 return "$fullname " . join(", ", @exprs);
2563 }
2564}
2565
2566sub pp_bless { listop(@_, "bless") }
2567sub pp_atan2 { maybe_targmy(@_, \&listop, "atan2") }
2568sub pp_substr {
2569 my ($self,$op,$cx) = @_;
2570 if ($op->private & OPpSUBSTR_REPL_FIRST) {
2571 return
2572 listop($self, $op, 7, "substr", $op->first->sibling->sibling)
2573 . " = "
2574 . $self->deparse($op->first->sibling, 7);
2575 }
2576 maybe_local(@_, listop(@_, "substr"))
2577}
2578sub pp_vec { maybe_local(@_, listop(@_, "vec")) }
2579sub pp_index { maybe_targmy(@_, \&listop, "index") }
2580sub pp_rindex { maybe_targmy(@_, \&listop, "rindex") }
2581sub pp_sprintf { maybe_targmy(@_, \&listop, "sprintf") }
2582sub pp_formline { listop(@_, "formline") } # see also deparse_format
2583sub pp_crypt { maybe_targmy(@_, \&listop, "crypt") }
2584sub pp_unpack { listop(@_, "unpack") }
2585sub pp_pack { listop(@_, "pack") }
2586sub pp_join { maybe_targmy(@_, \&listop, "join") }
2587sub pp_splice { listop(@_, "splice") }
2588sub pp_push { maybe_targmy(@_, \&listop, "push") }
2589sub pp_unshift { maybe_targmy(@_, \&listop, "unshift") }
2590sub pp_reverse { listop(@_, "reverse") }
2591sub pp_warn { listop(@_, "warn") }
2592sub pp_die { listop(@_, "die") }
2593sub pp_return { listop(@_, "return", undef, 1) } # llafr does not apply
2594sub pp_open { listop(@_, "open") }
2595sub pp_pipe_op { listop(@_, "pipe") }
2596sub pp_tie { listop(@_, "tie") }
2597sub pp_binmode { listop(@_, "binmode") }
2598sub pp_dbmopen { listop(@_, "dbmopen") }
2599sub pp_sselect { listop(@_, "select") }
2600sub pp_select { listop(@_, "select") }
2601sub pp_read { listop(@_, "read") }
2602sub pp_sysopen { listop(@_, "sysopen") }
2603sub pp_sysseek { listop(@_, "sysseek") }
2604sub pp_sysread { listop(@_, "sysread") }
2605sub pp_syswrite { listop(@_, "syswrite") }
2606sub pp_send { listop(@_, "send") }
2607sub pp_recv { listop(@_, "recv") }
2608sub pp_seek { listop(@_, "seek") }
2609sub pp_fcntl { listop(@_, "fcntl") }
2610sub pp_ioctl { listop(@_, "ioctl") }
2611sub pp_flock { maybe_targmy(@_, \&listop, "flock") }
2612sub pp_socket { listop(@_, "socket") }
2613sub pp_sockpair { listop(@_, "sockpair") }
2614sub pp_bind { listop(@_, "bind") }
2615sub pp_connect { listop(@_, "connect") }
2616sub pp_listen { listop(@_, "listen") }
2617sub pp_accept { listop(@_, "accept") }
2618sub pp_shutdown { listop(@_, "shutdown") }
2619sub pp_gsockopt { listop(@_, "getsockopt") }
2620sub pp_ssockopt { listop(@_, "setsockopt") }
2621sub pp_chown { maybe_targmy(@_, \&listop, "chown") }
2622sub pp_unlink { maybe_targmy(@_, \&listop, "unlink") }
2623sub pp_chmod { maybe_targmy(@_, \&listop, "chmod") }
2624sub pp_utime { maybe_targmy(@_, \&listop, "utime") }
2625sub pp_rename { maybe_targmy(@_, \&listop, "rename") }
2626sub pp_link { maybe_targmy(@_, \&listop, "link") }
2627sub pp_symlink { maybe_targmy(@_, \&listop, "symlink") }
2628sub pp_mkdir { maybe_targmy(@_, \&listop, "mkdir") }
2629sub pp_open_dir { listop(@_, "opendir") }
2630sub pp_seekdir { listop(@_, "seekdir") }
2631sub pp_waitpid { maybe_targmy(@_, \&listop, "waitpid") }
2632sub pp_system { maybe_targmy(@_, \&listop, "system") }
2633sub pp_exec { maybe_targmy(@_, \&listop, "exec") }
2634sub pp_kill { maybe_targmy(@_, \&listop, "kill") }
2635sub pp_setpgrp { maybe_targmy(@_, \&listop, "setpgrp") }
2636sub pp_getpriority { maybe_targmy(@_, \&listop, "getpriority") }
2637sub pp_setpriority { maybe_targmy(@_, \&listop, "setpriority") }
2638sub pp_shmget { listop(@_, "shmget") }
2639sub pp_shmctl { listop(@_, "shmctl") }
2640sub pp_shmread { listop(@_, "shmread") }
2641sub pp_shmwrite { listop(@_, "shmwrite") }
2642sub pp_msgget { listop(@_, "msgget") }
2643sub pp_msgctl { listop(@_, "msgctl") }
2644sub pp_msgsnd { listop(@_, "msgsnd") }
2645sub pp_msgrcv { listop(@_, "msgrcv") }
2646sub pp_semget { listop(@_, "semget") }
2647sub pp_semctl { listop(@_, "semctl") }
2648sub pp_semop { listop(@_, "semop") }
2649sub pp_ghbyaddr { listop(@_, "gethostbyaddr") }
2650sub pp_gnbyaddr { listop(@_, "getnetbyaddr") }
2651sub pp_gpbynumber { listop(@_, "getprotobynumber") }
2652sub pp_gsbyname { listop(@_, "getservbyname") }
2653sub pp_gsbyport { listop(@_, "getservbyport") }
2654sub pp_syscall { listop(@_, "syscall") }
2655
2656sub pp_glob {
2657 my $self = shift;
2658 my($op, $cx) = @_;
2659 my $text = $self->dq($op->first->sibling); # skip pushmark
2660 my $keyword =
2661 $op->flags & OPf_SPECIAL ? 'glob' : $self->keyword('glob');
2662 if ($text =~ /^\$?(\w|::|\`)+$/ # could look like a readline
2663 or $keyword =~ /^CORE::/
2664 or $text =~ /[<>]/) {
2665 return "$keyword(" . single_delim('qq', '"', $text) . ')';
2666 } else {
2667 return '<' . $text . '>';
2668 }
2669}
2670
2671# Truncate is special because OPf_SPECIAL makes a bareword first arg
2672# be a filehandle. This could probably be better fixed in the core
2673# by moving the GV lookup into ck_truc.
2674
2675sub pp_truncate {
2676 my $self = shift;
2677 my($op, $cx) = @_;
2678 my(@exprs);
2679 my $parens = ($cx >= 5) || $self->{'parens'};
2680 my $kid = $op->first->sibling;
2681 my $fh;
2682 if ($op->flags & OPf_SPECIAL) {
2683 # $kid is an OP_CONST
2684 $fh = $self->const_sv($kid)->PV;
2685 } else {
2686 $fh = $self->deparse($kid, 6);
2687 $fh = "+$fh" if not $parens and substr($fh, 0, 1) eq "(";
2688 }
2689 my $len = $self->deparse($kid->sibling, 6);
2690 my $name = $self->keyword('truncate');
2691 if ($parens) {
2692 return "$name($fh, $len)";
2693 } else {
2694 return "$name $fh, $len";
2695 }
2696}
2697
2698sub indirop {
2699 my $self = shift;
2700 my($op, $cx, $name) = @_;
2701 my($expr, @exprs);
2702 my $firstkid = my $kid = $op->first->sibling;
2703 my $indir = "";
2704 if ($op->flags & OPf_STACKED) {
2705 $indir = $kid;
2706 $indir = $indir->first; # skip rv2gv
2707 if (is_scope($indir)) {
2708 $indir = "{" . $self->deparse($indir, 0) . "}";
2709 $indir = "{;}" if $indir eq "{}";
2710 } elsif ($indir->name eq "const" && $indir->private & OPpCONST_BARE) {
2711 $indir = $self->const_sv($indir)->PV;
2712 } else {
2713 $indir = $self->deparse($indir, 24);
2714 }
2715 $indir = $indir . " ";
2716 $kid = $kid->sibling;
2717 }
2718 if ($name eq "sort" && $op->private & (OPpSORT_NUMERIC | OPpSORT_INTEGER)) {
2719 $indir = ($op->private & OPpSORT_DESCEND) ? '{$b <=> $a} '
2720 : '{$a <=> $b} ';
2721 }
2722 elsif ($name eq "sort" && $op->private & OPpSORT_DESCEND) {
2723 $indir = '{$b cmp $a} ';
2724 }
2725 for (; !null($kid); $kid = $kid->sibling) {
2726 $expr = $self->deparse($kid, !$indir && $kid == $firstkid && $name eq "sort" && $firstkid->name eq "entersub" ? 16 : 6);
2727 push @exprs, $expr;
2728 }
2729 my $name2;
2730 if ($name eq "sort" && $op->private & OPpSORT_REVERSE) {
2731 $name2 = $self->keyword('reverse') . ' ' . $self->keyword('sort');
2732 }
2733 else { $name2 = $self->keyword($name) }
2734 if ($name eq "sort" && ($op->private & OPpSORT_INPLACE)) {
2735 return "$exprs[0] = $name2 $indir $exprs[0]";
2736 }
2737
2738 my $args = $indir . join(", ", @exprs);
2739 if ($indir ne "" && $name eq "sort") {
2740 # We don't want to say "sort(f 1, 2, 3)", since perl -w will
2741 # give bareword warnings in that case. Therefore if context
2742 # requires, we'll put parens around the outside "(sort f 1, 2,
2743 # 3)". Unfortunately, we'll currently think the parens are
2744 # necessary more often that they really are, because we don't
2745 # distinguish which side of an assignment we're on.
2746 if ($cx >= 5) {
2747 return "($name2 $args)";
2748 } else {
2749 return "$name2 $args";
2750 }
2751 } elsif (
2752 !$indir && $name eq "sort"
2753 && $op->first->sibling->name eq 'entersub'
2754 ) {
2755 # We cannot say sort foo(bar), as foo will be interpreted as a
2756 # comparison routine. We have to say sort(...) in that case.
2757 return "$name2($args)";
2758 } else {
2759 return $self->maybe_parens_func($name2, $args, $cx, 5);
2760 }
2761
2762}
2763
2764sub pp_prtf { indirop(@_, "printf") }
2765sub pp_print { indirop(@_, "print") }
2766sub pp_say { indirop(@_, "say") }
2767sub pp_sort { indirop(@_, "sort") }
2768
2769sub mapop {
2770 my $self = shift;
2771 my($op, $cx, $name) = @_;
2772 my($expr, @exprs);
2773 my $kid = $op->first; # this is the (map|grep)start
2774 $kid = $kid->first->sibling; # skip a pushmark
2775 my $code = $kid->first; # skip a null
2776 if (is_scope $code) {
2777 $code = "{" . $self->deparse($code, 0) . "} ";
2778 } else {
2779 $code = $self->deparse($code, 24) . ", ";
2780 }
2781 $kid = $kid->sibling;
2782 for (; !null($kid); $kid = $kid->sibling) {
2783 $expr = $self->deparse($kid, 6);
2784 push @exprs, $expr if defined $expr;
2785 }
2786 return $self->maybe_parens_func($name, $code . join(", ", @exprs), $cx, 5);
2787}
2788
2789sub pp_mapwhile { mapop(@_, "map") }
2790sub pp_grepwhile { mapop(@_, "grep") }
2791sub pp_mapstart { baseop(@_, "map") }
2792sub pp_grepstart { baseop(@_, "grep") }
2793
2794sub pp_list {
2795 my $self = shift;
2796 my($op, $cx) = @_;
2797 my($expr, @exprs);
2798 my $kid = $op->first->sibling; # skip pushmark
2799 return '' if class($kid) eq 'NULL';
2800 my $lop;
2801 my $local = "either"; # could be local(...), my(...), state(...) or our(...)
2802 for ($lop = $kid; !null($lop); $lop = $lop->sibling) {
2803 # This assumes that no other private flags equal 128, and that
2804 # OPs that store things other than flags in their op_private,
2805 # like OP_AELEMFAST, won't be immediate children of a list.
2806 #
2807 # OP_ENTERSUB can break this logic, so check for it.
2808 # I suspect that open and exit can too.
2809
2810 if (!($lop->private & (OPpLVAL_INTRO|OPpOUR_INTRO)
2811 or $lop->name eq "undef")
2812 or $lop->name eq "entersub"
2813 or $lop->name eq "exit"
2814 or $lop->name eq "open")
2815 {
2816 $local = ""; # or not
2817 last;
2818 }
2819 if ($lop->name =~ /^pad[ash]v$/) {
2820 if ($lop->private & OPpPAD_STATE) { # state()
2821 ($local = "", last) if $local =~ /^(?:local|our|my)$/;
2822 $local = "state";
2823 } else { # my()
2824 ($local = "", last) if $local =~ /^(?:local|our|state)$/;
2825 $local = "my";
2826 }
2827 } elsif ($lop->name =~ /^(gv|rv2)[ash]v$/
2828 && $lop->private & OPpOUR_INTRO
2829 or $lop->name eq "null" && $lop->first->name eq "gvsv"
2830 && $lop->first->private & OPpOUR_INTRO) { # our()
2831 ($local = "", last) if $local =~ /^(?:my|local|state)$/;
2832 $local = "our";
2833 } elsif ($lop->name ne "undef"
2834 # specifically avoid the "reverse sort" optimisation,
2835 # where "reverse" is nullified
2836 && !($lop->name eq 'sort' && ($lop->flags & OPpSORT_REVERSE)))
2837 {
2838 # local()
2839 ($local = "", last) if $local =~ /^(?:my|our|state)$/;
2840 $local = "local";
2841 }
2842 }
2843 $local = "" if $local eq "either"; # no point if it's all undefs
2844 return $self->deparse($kid, $cx) if null $kid->sibling and not $local;
2845 for (; !null($kid); $kid = $kid->sibling) {
2846 if ($local) {
2847 if (class($kid) eq "UNOP" and $kid->first->name eq "gvsv") {
2848 $lop = $kid->first;
2849 } else {
2850 $lop = $kid;
2851 }
2852 $self->{'avoid_local'}{$$lop}++;
2853 $expr = $self->deparse($kid, 6);
2854 delete $self->{'avoid_local'}{$$lop};
2855 } else {
2856 $expr = $self->deparse($kid, 6);
2857 }
2858 push @exprs, $expr;
2859 }
2860 if ($local) {
2861 return "$local(" . join(", ", @exprs) . ")";
2862 } else {
2863 return $self->maybe_parens( join(", ", @exprs), $cx, 6);
2864 }
2865}
2866
2867sub is_ifelse_cont {
2868 my $op = shift;
2869 return ($op->name eq "null" and class($op) eq "UNOP"
2870 and $op->first->name =~ /^(and|cond_expr)$/
2871 and is_scope($op->first->first->sibling));
2872}
2873
2874sub pp_cond_expr {
2875 my $self = shift;
2876 my($op, $cx) = @_;
2877 my $cond = $op->first;
2878 my $true = $cond->sibling;
2879 my $false = $true->sibling;
2880 my $cuddle = $self->{'cuddle'};
2881 unless ($cx < 1 and (is_scope($true) and $true->name ne "null") and
2882 (is_scope($false) || is_ifelse_cont($false))
2883 and $self->{'expand'} < 7) {
2884 $cond = $self->deparse($cond, 8);
2885 $true = $self->deparse($true, 6);
2886 $false = $self->deparse($false, 8);
2887 return $self->maybe_parens("$cond ? $true : $false", $cx, 8);
2888 }
2889
2890 $cond = $self->deparse($cond, 1);
2891 $true = $self->deparse($true, 0);
2892 my $head = "if ($cond) {\n\t$true\n\b}";
2893 my @elsifs;
2894 while (!null($false) and is_ifelse_cont($false)) {
2895 my $newop = $false->first;
2896 my $newcond = $newop->first;
2897 my $newtrue = $newcond->sibling;
2898 $false = $newtrue->sibling; # last in chain is OP_AND => no else
2899 if ($newcond->name eq "lineseq")
2900 {
2901 # lineseq to ensure correct line numbers in elsif()
2902 # Bug #37302 fixed by change #33710.
2903 $newcond = $newcond->first->sibling;
2904 }
2905 $newcond = $self->deparse($newcond, 1);
2906 $newtrue = $self->deparse($newtrue, 0);
2907 push @elsifs, "elsif ($newcond) {\n\t$newtrue\n\b}";
2908 }
2909 if (!null($false)) {
2910 $false = $cuddle . "else {\n\t" .
2911 $self->deparse($false, 0) . "\n\b}\cK";
2912 } else {
2913 $false = "\cK";
2914 }
2915 return $head . join($cuddle, "", @elsifs) . $false;
2916}
2917
2918sub pp_once {
2919 my ($self, $op, $cx) = @_;
2920 my $cond = $op->first;
2921 my $true = $cond->sibling;
2922
2923 return $self->deparse($true, $cx);
2924}
2925
2926sub loop_common {
2927 my $self = shift;
2928 my($op, $cx, $init) = @_;
2929 my $enter = $op->first;
2930 my $kid = $enter->sibling;
2931 local(@$self{qw'curstash warnings hints hinthash'})
2932 = @$self{qw'curstash warnings hints hinthash'};
2933 my $head = "";
2934 my $bare = 0;
2935 my $body;
2936 my $cond = undef;
2937 if ($kid->name eq "lineseq") { # bare or infinite loop
2938 if ($kid->last->name eq "unstack") { # infinite
2939 $head = "while (1) "; # Can't use for(;;) if there's a continue
2940 $cond = "";
2941 } else {
2942 $bare = 1;
2943 }
2944 $body = $kid;
2945 } elsif ($enter->name eq "enteriter") { # foreach
2946 my $ary = $enter->first->sibling; # first was pushmark
2947 my $var = $ary->sibling;
2948 if ($ary->name eq 'null' and $enter->private & OPpITER_REVERSED) {
2949 # "reverse" was optimised away
2950 $ary = listop($self, $ary->first->sibling, 1, 'reverse');
2951 } elsif ($enter->flags & OPf_STACKED
2952 and not null $ary->first->sibling->sibling)
2953 {
2954 $ary = $self->deparse($ary->first->sibling, 9) . " .. " .
2955 $self->deparse($ary->first->sibling->sibling, 9);
2956 } else {
2957 $ary = $self->deparse($ary, 1);
2958 }
2959 if (null $var) {
2960 if (($enter->flags & OPf_SPECIAL) && ($] < 5.009)) {
2961 # thread special var, under 5005threads
2962 $var = $self->pp_threadsv($enter, 1);
2963 } else { # regular my() variable
2964 $var = $self->pp_padsv($enter, 1);
2965 }
2966 } elsif ($var->name eq "rv2gv") {
2967 $var = $self->pp_rv2sv($var, 1);
2968 if ($enter->private & OPpOUR_INTRO) {
2969 # our declarations don't have package names
2970 $var =~ s/^(.).*::/$1/;
2971 $var = "our $var";
2972 }
2973 } elsif ($var->name eq "gv") {
2974 $var = "\$" . $self->deparse($var, 1);
2975 }
2976 $body = $kid->first->first->sibling; # skip OP_AND and OP_ITER
2977 if (!is_state $body->first and $body->first->name !~ /^(?:stub|leave|scope)$/) {
2978 confess unless $var eq '$_';
2979 $body = $body->first;
2980 return $self->deparse($body, 2) . " foreach ($ary)";
2981 }
2982 $head = "foreach $var ($ary) ";
2983 } elsif ($kid->name eq "null") { # while/until
2984 $kid = $kid->first;
2985 my $name = {"and" => "while", "or" => "until"}->{$kid->name};
2986 $cond = $self->deparse($kid->first, 1);
2987 $head = "$name ($cond) ";
2988 $body = $kid->first->sibling;
2989 } elsif ($kid->name eq "stub") { # bare and empty
2990 return "{;}"; # {} could be a hashref
2991 }
2992 # If there isn't a continue block, then the next pointer for the loop
2993 # will point to the unstack, which is kid's last child, except
2994 # in a bare loop, when it will point to the leaveloop. When neither of
2995 # these conditions hold, then the second-to-last child is the continue
2996 # block (or the last in a bare loop).
2997 my $cont_start = $enter->nextop;
2998 my $cont;
2999 if ($$cont_start != $$op && ${$cont_start} != ${$body->last}) {
3000 if ($bare) {
3001 $cont = $body->last;
3002 } else {
3003 $cont = $body->first;
3004 while (!null($cont->sibling->sibling)) {
3005 $cont = $cont->sibling;
3006 }
3007 }
3008 my $state = $body->first;
3009 my $cuddle = $self->{'cuddle'};
3010 my @states;
3011 for (; $$state != $$cont; $state = $state->sibling) {
3012 push @states, $state;
3013 }
3014 $body = $self->lineseq(undef, @states);
3015 if (defined $cond and not is_scope $cont and $self->{'expand'} < 3) {
3016 $head = "for ($init; $cond; " . $self->deparse($cont, 1) .") ";
3017 $cont = "\cK";
3018 } else {
3019 $cont = $cuddle . "continue {\n\t" .
3020 $self->deparse($cont, 0) . "\n\b}\cK";
3021 }
3022 } else {
3023 return "" if !defined $body;
3024 if (length $init) {
3025 $head = "for ($init; $cond;) ";
3026 }
3027 $cont = "\cK";
3028 $body = $self->deparse($body, 0);
3029 }
3030 $body =~ s/;?$/;\n/;
3031
3032 return $head . "{\n\t" . $body . "\b}" . $cont;
3033}
3034
3035sub pp_leaveloop { shift->loop_common(@_, "") }
3036
3037sub for_loop {
3038 my $self = shift;
3039 my($op, $cx) = @_;
3040 my $init = $self->deparse($op, 1);
3041 my $s = $op->sibling;
3042 my $ll = $s->name eq "unstack" ? $s->sibling : $s->first->sibling;
3043 return $self->loop_common($ll, $cx, $init);
3044}
3045
3046sub pp_leavetry {
3047 my $self = shift;
3048 return "eval {\n\t" . $self->pp_leave(@_) . "\n\b}";
3049}
3050
3051BEGIN { for (qw[ const stringify rv2sv list glob ]) {
3052 eval "sub OP_\U$_ () { " . opnumber($_) . "}"
3053}}
3054
3055sub pp_null {
3056 my $self = shift;
3057 my($op, $cx) = @_;
3058 if (class($op) eq "OP") {
3059 # old value is lost
3060 return $self->{'ex_const'} if $op->targ == OP_CONST;
3061 } elsif ($op->first->name eq "pushmark") {
3062 return $self->pp_list($op, $cx);
3063 } elsif ($op->first->name eq "enter") {
3064 return $self->pp_leave($op, $cx);
3065 } elsif ($op->first->name eq "leave") {
3066 return $self->pp_leave($op->first, $cx);
3067 } elsif ($op->first->name eq "scope") {
3068 return $self->pp_scope($op->first, $cx);
3069 } elsif ($op->targ == OP_STRINGIFY) {
3070 return $self->dquote($op, $cx);
3071 } elsif ($op->targ == OP_GLOB) {
3072 return $self->pp_glob(
3073 $op->first # entersub
3074 ->first # ex-list
3075 ->first # pushmark
3076 ->sibling, # glob
3077 $cx
3078 );
3079 } elsif (!null($op->first->sibling) and
3080 $op->first->sibling->name eq "readline" and
3081 $op->first->sibling->flags & OPf_STACKED) {
3082 return $self->maybe_parens($self->deparse($op->first, 7) . " = "
3083 . $self->deparse($op->first->sibling, 7),
3084 $cx, 7);
3085 } elsif (!null($op->first->sibling) and
3086 $op->first->sibling->name eq "trans" and
3087 $op->first->sibling->flags & OPf_STACKED) {
3088 return $self->maybe_parens($self->deparse($op->first, 20) . " =~ "
3089 . $self->deparse($op->first->sibling, 20),
3090 $cx, 20);
3091 } elsif ($op->flags & OPf_SPECIAL && $cx < 1 && !$op->targ) {
3092 return "do {\n\t". $self->deparse($op->first, $cx) ."\n\b};";
3093 } elsif (!null($op->first->sibling) and
3094 $op->first->sibling->name eq "null" and
3095 class($op->first->sibling) eq "UNOP" and
3096 $op->first->sibling->first->flags & OPf_STACKED and
3097 $op->first->sibling->first->name eq "rcatline") {
3098 return $self->maybe_parens($self->deparse($op->first, 18) . " .= "
3099 . $self->deparse($op->first->sibling, 18),
3100 $cx, 18);
3101 } else {
3102 return $self->deparse($op->first, $cx);
3103 }
3104}
3105
3106sub padname {
3107 my $self = shift;
3108 my $targ = shift;
3109 return $self->padname_sv($targ)->PVX;
3110}
3111
3112sub padany {
3113 my $self = shift;
3114 my $op = shift;
3115 return substr($self->padname($op->targ), 1); # skip $/@/%
3116}
3117
3118sub pp_padsv {
3119 my $self = shift;
3120 my($op, $cx) = @_;
3121 return $self->maybe_my($op, $cx, $self->padname($op->targ));
3122}
3123
3124sub pp_padav { pp_padsv(@_) }
3125sub pp_padhv { pp_padsv(@_) }
3126
3127my @threadsv_names = B::threadsv_names;
3128sub pp_threadsv {
3129 my $self = shift;
3130 my($op, $cx) = @_;
3131 return $self->maybe_local($op, $cx, "\$" . $threadsv_names[$op->targ]);
3132}
3133
3134sub gv_or_padgv {
3135 my $self = shift;
3136 my $op = shift;
3137 if (class($op) eq "PADOP") {
3138 return $self->padval($op->padix);
3139 } else { # class($op) eq "SVOP"
3140 return $op->gv;
3141 }
3142}
3143
3144sub pp_gvsv {
3145 my $self = shift;
3146 my($op, $cx) = @_;
3147 my $gv = $self->gv_or_padgv($op);
3148 return $self->maybe_local($op, $cx, $self->stash_variable("\$",
3149 $self->gv_name($gv), $cx));
3150}
3151
3152sub pp_gv {
3153 my $self = shift;
3154 my($op, $cx) = @_;
3155 my $gv = $self->gv_or_padgv($op);
3156 return $self->gv_name($gv);
3157}
3158
3159sub pp_aelemfast_lex {
3160 my $self = shift;
3161 my($op, $cx) = @_;
3162 my $name = $self->padname($op->targ);
3163 $name =~ s/^@/\$/;
3164 return $name . "[" . ($op->private + $self->{'arybase'}) . "]";
3165}
3166
3167sub pp_aelemfast {
3168 my $self = shift;
3169 my($op, $cx) = @_;
3170 # optimised PADAV, pre 5.15
3171 return $self->pp_aelemfast_lex(@_) if ($op->flags & OPf_SPECIAL);
3172
3173 my $gv = $self->gv_or_padgv($op);
3174 my($name,$quoted) = $self->stash_variable_name('@',$gv);
3175 $name = $quoted ? "$name->" : '$' . $name;
3176 return $name . "[" . ($op->private + $self->{'arybase'}) . "]";
3177}
3178
3179sub rv2x {
3180 my $self = shift;
3181 my($op, $cx, $type) = @_;
3182
3183 if (class($op) eq 'NULL' || !$op->can("first")) {
3184 carp("Unexpected op in pp_rv2x");
3185 return 'XXX';
3186 }
3187 my $kid = $op->first;
3188 if ($kid->name eq "gv") {
3189 return $self->stash_variable($type, $self->deparse($kid, 0), $cx);
3190 } elsif (is_scalar $kid) {
3191 my $str = $self->deparse($kid, 0);
3192 if ($str =~ /^\$([^\w\d])\z/) {
3193 # "$$+" isn't a legal way to write the scalar dereference
3194 # of $+, since the lexer can't tell you aren't trying to
3195 # do something like "$$ + 1" to get one more than your
3196 # PID. Either "${$+}" or "$${+}" are workable
3197 # disambiguations, but if the programmer did the former,
3198 # they'd be in the "else" clause below rather than here.
3199 # It's not clear if this should somehow be unified with
3200 # the code in dq and re_dq that also adds lexer
3201 # disambiguation braces.
3202 $str = '$' . "{$1}"; #'
3203 }
3204 return $type . $str;
3205 } else {
3206 return $type . "{" . $self->deparse($kid, 0) . "}";
3207 }
3208}
3209
3210sub pp_rv2sv { maybe_local(@_, rv2x(@_, "\$")) }
3211sub pp_rv2hv { maybe_local(@_, rv2x(@_, "%")) }
3212sub pp_rv2gv { maybe_local(@_, rv2x(@_, "*")) }
3213
3214# skip rv2av
3215sub pp_av2arylen {
3216 my $self = shift;
3217 my($op, $cx) = @_;
3218 if ($op->first->name eq "padav") {
3219 return $self->maybe_local($op, $cx, '$#' . $self->padany($op->first));
3220 } else {
3221 return $self->maybe_local($op, $cx,
3222 $self->rv2x($op->first, $cx, '$#'));
3223 }
3224}
3225
3226# skip down to the old, ex-rv2cv
3227sub pp_rv2cv {
3228 my ($self, $op, $cx) = @_;
3229 if (!null($op->first) && $op->first->name eq 'null' &&
3230 $op->first->targ eq OP_LIST)
3231 {
3232 return $self->rv2x($op->first->first->sibling, $cx, "&")
3233 }
3234 else {
3235 return $self->rv2x($op, $cx, "")
3236 }
3237}
3238
3239sub list_const {
3240 my $self = shift;
3241 my($cx, @list) = @_;
3242 my @a = map $self->const($_, 6), @list;
3243 if (@a == 0) {
3244 return "()";
3245 } elsif (@a == 1) {
3246 return $a[0];
3247 } elsif ( @a > 2 and !grep(!/^-?\d+$/, @a)) {
3248 # collapse (-1,0,1,2) into (-1..2)
3249 my ($s, $e) = @a[0,-1];
3250 my $i = $s;
3251 return $self->maybe_parens("$s..$e", $cx, 9)
3252 unless grep $i++ != $_, @a;
3253 }
3254 return $self->maybe_parens(join(", ", @a), $cx, 6);
3255}
3256
3257sub pp_rv2av {
3258 my $self = shift;
3259 my($op, $cx) = @_;
3260 my $kid = $op->first;
3261 if ($kid->name eq "const") { # constant list
3262 my $av = $self->const_sv($kid);
3263 return $self->list_const($cx, $av->ARRAY);
3264 } else {
3265 return $self->maybe_local($op, $cx, $self->rv2x($op, $cx, "\@"));
3266 }
3267 }
3268
3269sub is_subscriptable {
3270 my $op = shift;
3271 if ($op->name =~ /^[ahg]elem/) {
3272 return 1;
3273 } elsif ($op->name eq "entersub") {
3274 my $kid = $op->first;
3275 return 0 unless null $kid->sibling;
3276 $kid = $kid->first;
3277 $kid = $kid->sibling until null $kid->sibling;
3278 return 0 if is_scope($kid);
3279 $kid = $kid->first;
3280 return 0 if $kid->name eq "gv";
3281 return 0 if is_scalar($kid);
3282 return is_subscriptable($kid);
3283 } else {
3284 return 0;
3285 }
3286}
3287
3288sub elem_or_slice_array_name
3289{
3290 my $self = shift;
3291 my ($array, $left, $padname, $allow_arrow) = @_;
3292
3293 if ($array->name eq $padname) {
3294 return $self->padany($array);
3295 } elsif (is_scope($array)) { # ${expr}[0]
3296 return "{" . $self->deparse($array, 0) . "}";
3297 } elsif ($array->name eq "gv") {
3298 ($array, my $quoted) =
3299 $self->stash_variable_name(
3300 $left eq '[' ? '@' : '%', $self->gv_or_padgv($array)
3301 );
3302 if (!$allow_arrow && $quoted) {
3303 # This cannot happen.
3304 die "Invalid variable name $array for slice";
3305 }
3306 return $quoted ? "$array->" : $array;
3307 } elsif (!$allow_arrow || is_scalar $array) { # $x[0], $$x[0], ...
3308 return $self->deparse($array, 24);
3309 } else {
3310 return undef;
3311 }
3312}
3313
3314sub elem_or_slice_single_index
3315{
3316 my $self = shift;
3317 my ($idx) = @_;
3318
3319 $idx = $self->deparse($idx, 1);
3320
3321 # Outer parens in an array index will confuse perl
3322 # if we're interpolating in a regular expression, i.e.
3323 # /$x$foo[(-1)]/ is *not* the same as /$x$foo[-1]/
3324 #
3325 # If $self->{parens}, then an initial '(' will
3326 # definitely be paired with a final ')'. If
3327 # !$self->{parens}, the misleading parens won't
3328 # have been added in the first place.
3329 #
3330 # [You might think that we could get "(...)...(...)"
3331 # where the initial and final parens do not match
3332 # each other. But we can't, because the above would
3333 # only happen if there's an infix binop between the
3334 # two pairs of parens, and *that* means that the whole
3335 # expression would be parenthesized as well.]
3336 #
3337 $idx =~ s/^\((.*)\)$/$1/ if $self->{'parens'};
3338
3339 # Hash-element braces will autoquote a bareword inside themselves.
3340 # We need to make sure that C<$hash{warn()}> doesn't come out as
3341 # C<$hash{warn}>, which has a quite different meaning. Currently
3342 # B::Deparse will always quote strings, even if the string was a
3343 # bareword in the original (i.e. the OPpCONST_BARE flag is ignored
3344 # for constant strings.) So we can cheat slightly here - if we see
3345 # a bareword, we know that it is supposed to be a function call.
3346 #
3347 $idx =~ s/^([A-Za-z_]\w*)$/$1()/;
3348
3349 return $idx;
3350}
3351
3352sub elem {
3353 my $self = shift;
3354 my ($op, $cx, $left, $right, $padname) = @_;
3355 my($array, $idx) = ($op->first, $op->first->sibling);
3356
3357 $idx = $self->elem_or_slice_single_index($idx);
3358
3359 unless ($array->name eq $padname) { # Maybe this has been fixed
3360 $array = $array->first; # skip rv2av (or ex-rv2av in _53+)
3361 }
3362 if (my $array_name=$self->elem_or_slice_array_name
3363 ($array, $left, $padname, 1)) {
3364 return ($array_name =~ /->\z/ ? $array_name : "\$" . $array_name)
3365 . $left . $idx . $right;
3366 } else {
3367 # $x[20][3]{hi} or expr->[20]
3368 my $arrow = is_subscriptable($array) ? "" : "->";
3369 return $self->deparse($array, 24) . $arrow . $left . $idx . $right;
3370 }
3371
3372}
3373
3374sub pp_aelem { maybe_local(@_, elem(@_, "[", "]", "padav")) }
3375sub pp_helem { maybe_local(@_, elem(@_, "{", "}", "padhv")) }
3376
3377sub pp_gelem {
3378 my $self = shift;
3379 my($op, $cx) = @_;
3380 my($glob, $part) = ($op->first, $op->last);
3381 $glob = $glob->first; # skip rv2gv
3382 $glob = $glob->first if $glob->name eq "rv2gv"; # this one's a bug
3383 my $scope = is_scope($glob);
3384 $glob = $self->deparse($glob, 0);
3385 $part = $self->deparse($part, 1);
3386 return "*" . ($scope ? "{$glob}" : $glob) . "{$part}";
3387}
3388
3389sub slice {
3390 my $self = shift;
3391 my ($op, $cx, $left, $right, $regname, $padname) = @_;
3392 my $last;
3393 my(@elems, $kid, $array, $list);
3394 if (class($op) eq "LISTOP") {
3395 $last = $op->last;
3396 } else { # ex-hslice inside delete()
3397 for ($kid = $op->first; !null $kid->sibling; $kid = $kid->sibling) {}
3398 $last = $kid;
3399 }
3400 $array = $last;
3401 $array = $array->first
3402 if $array->name eq $regname or $array->name eq "null";
3403 $array = $self->elem_or_slice_array_name($array,$left,$padname,0);
3404 $kid = $op->first->sibling; # skip pushmark
3405 if ($kid->name eq "list") {
3406 $kid = $kid->first->sibling; # skip list, pushmark
3407 for (; !null $kid; $kid = $kid->sibling) {
3408 push @elems, $self->deparse($kid, 6);
3409 }
3410 $list = join(", ", @elems);
3411 } else {
3412 $list = $self->elem_or_slice_single_index($kid);
3413 }
3414 return "\@" . $array . $left . $list . $right;
3415}
3416
3417sub pp_aslice { maybe_local(@_, slice(@_, "[", "]", "rv2av", "padav")) }
3418sub pp_hslice { maybe_local(@_, slice(@_, "{", "}", "rv2hv", "padhv")) }
3419
3420sub pp_lslice {
3421 my $self = shift;
3422 my($op, $cx) = @_;
3423 my $idx = $op->first;
3424 my $list = $op->last;
3425 my(@elems, $kid);
3426 $list = $self->deparse($list, 1);
3427 $idx = $self->deparse($idx, 1);
3428 return "($list)" . "[$idx]";
3429}
3430
3431sub want_scalar {
3432 my $op = shift;
3433 return ($op->flags & OPf_WANT) == OPf_WANT_SCALAR;
3434}
3435
3436sub want_list {
3437 my $op = shift;
3438 return ($op->flags & OPf_WANT) == OPf_WANT_LIST;
3439}
3440
3441sub _method {
3442 my $self = shift;
3443 my($op, $cx) = @_;
3444 my $kid = $op->first->sibling; # skip pushmark
3445 my($meth, $obj, @exprs);
3446 if ($kid->name eq "list" and want_list $kid) {
3447 # When an indirect object isn't a bareword but the args are in
3448 # parens, the parens aren't part of the method syntax (the LLAFR
3449 # doesn't apply), but they make a list with OPf_PARENS set that
3450 # doesn't get flattened by the append_elem that adds the method,
3451 # making a (object, arg1, arg2, ...) list where the object
3452 # usually is. This can be distinguished from
3453 # '($obj, $arg1, $arg2)->meth()' (which is legal if $arg2 is an
3454 # object) because in the later the list is in scalar context
3455 # as the left side of -> always is, while in the former
3456 # the list is in list context as method arguments always are.
3457 # (Good thing there aren't method prototypes!)
3458 $meth = $kid->sibling;
3459 $kid = $kid->first->sibling; # skip pushmark
3460 $obj = $kid;
3461 $kid = $kid->sibling;
3462 for (; not null $kid; $kid = $kid->sibling) {
3463 push @exprs, $kid;
3464 }
3465 } else {
3466 $obj = $kid;
3467 $kid = $kid->sibling;
3468 for (; !null ($kid->sibling) && $kid->name!~/^method(?:_named)?\z/;
3469 $kid = $kid->sibling) {
3470 push @exprs, $kid
3471 }
3472 $meth = $kid;
3473 }
3474
3475 if ($meth->name eq "method_named") {
3476 $meth = $self->const_sv($meth)->PV;
3477 } else {
3478 $meth = $meth->first;
3479 if ($meth->name eq "const") {
3480 # As of 5.005_58, this case is probably obsoleted by the
3481 # method_named case above
3482 $meth = $self->const_sv($meth)->PV; # needs to be bare
3483 }
3484 }
3485
3486 return { method => $meth, variable_method => ref($meth),
3487 object => $obj, args => \@exprs },
3488 $cx;
3489}
3490
3491# compat function only
3492sub method {
3493 my $self = shift;
3494 my $info = $self->_method(@_);
3495 return $self->e_method( $self->_method(@_) );
3496}
3497
3498sub e_method {
3499 my ($self, $info, $cx) = @_;
3500 my $obj = $self->deparse($info->{object}, 24);
3501
3502 my $meth = $info->{method};
3503 $meth = $self->deparse($meth, 1) if $info->{variable_method};
3504 my $args = join(", ", map { $self->deparse($_, 6) } @{$info->{args}} );
3505 if ($info->{object}->name eq 'scope' && want_list $info->{object}) {
3506 # method { $object }
3507 # This must be deparsed this way to preserve list context
3508 # of $object.
3509 my $need_paren = $cx >= 6;
3510 return '(' x $need_paren
3511 . $meth . substr($obj,2) # chop off the "do"
3512 . " $args"
3513 . ')' x $need_paren;
3514 }
3515 my $kid = $obj . "->" . $meth;
3516 if (length $args) {
3517 return $kid . "(" . $args . ")"; # parens mandatory
3518 } else {
3519 return $kid;
3520 }
3521}
3522
3523# returns "&" if the prototype doesn't match the args,
3524# or ("", $args_after_prototype_demunging) if it does.
3525sub check_proto {
3526 my $self = shift;
3527 return "&" if $self->{'noproto'};
3528 my($proto, @args) = @_;
3529 my($arg, $real);
3530 my $doneok = 0;
3531 my @reals;
3532 # An unbackslashed @ or % gobbles up the rest of the args
3533 1 while $proto =~ s/(?<!\\)([@%])[^\]]+$/$1/;
3534 while ($proto) {
3535 $proto =~ s/^(\\?[\$\@&%*_]|\\\[[\$\@&%*]+\]|;)//;
3536 my $chr = $1;
3537 if ($chr eq "") {
3538 return "&" if @args;
3539 } elsif ($chr eq ";") {
3540 $doneok = 1;
3541 } elsif ($chr eq "@" or $chr eq "%") {
3542 push @reals, map($self->deparse($_, 6), @args);
3543 @args = ();
3544 } else {
3545 $arg = shift @args;
3546 last unless $arg;
3547 if ($chr eq "\$" || $chr eq "_") {
3548 if (want_scalar $arg) {
3549 push @reals, $self->deparse($arg, 6);
3550 } else {
3551 return "&";
3552 }
3553 } elsif ($chr eq "&") {
3554 if ($arg->name =~ /^(s?refgen|undef)$/) {
3555 push @reals, $self->deparse($arg, 6);
3556 } else {
3557 return "&";
3558 }
3559 } elsif ($chr eq "*") {
3560 if ($arg->name =~ /^s?refgen$/
3561 and $arg->first->first->name eq "rv2gv")
3562 {
3563 $real = $arg->first->first; # skip refgen, null
3564 if ($real->first->name eq "gv") {
3565 push @reals, $self->deparse($real, 6);
3566 } else {
3567 push @reals, $self->deparse($real->first, 6);
3568 }
3569 } else {
3570 return "&";
3571 }
3572 } elsif (substr($chr, 0, 1) eq "\\") {
3573 $chr =~ tr/\\[]//d;
3574 if ($arg->name =~ /^s?refgen$/ and
3575 !null($real = $arg->first) and
3576 ($chr =~ /\$/ && is_scalar($real->first)
3577 or ($chr =~ /@/
3578 && class($real->first->sibling) ne 'NULL'
3579 && $real->first->sibling->name
3580 =~ /^(rv2|pad)av$/)
3581 or ($chr =~ /%/
3582 && class($real->first->sibling) ne 'NULL'
3583 && $real->first->sibling->name
3584 =~ /^(rv2|pad)hv$/)
3585 #or ($chr =~ /&/ # This doesn't work
3586 # && $real->first->name eq "rv2cv")
3587 or ($chr =~ /\*/
3588 && $real->first->name eq "rv2gv")))
3589 {
3590 push @reals, $self->deparse($real, 6);
3591 } else {
3592 return "&";
3593 }
3594 }
3595 }
3596 }
3597 return "&" if $proto and !$doneok; # too few args and no ';'
3598 return "&" if @args; # too many args
3599 return ("", join ", ", @reals);
3600}
3601
3602sub pp_entersub {
3603 my $self = shift;
3604 my($op, $cx) = @_;
3605 return $self->e_method($self->_method($op, $cx))
3606 unless null $op->first->sibling;
3607 my $prefix = "";
3608 my $amper = "";
3609 my($kid, @exprs);
3610 if ($op->flags & OPf_SPECIAL && !($op->flags & OPf_MOD)) {
3611 $prefix = "do ";
3612 } elsif ($op->private & OPpENTERSUB_AMPER) {
3613 $amper = "&";
3614 }
3615 $kid = $op->first;
3616 $kid = $kid->first->sibling; # skip ex-list, pushmark
3617 for (; not null $kid->sibling; $kid = $kid->sibling) {
3618 push @exprs, $kid;
3619 }
3620 my $simple = 0;
3621 my $proto = undef;
3622 if (is_scope($kid)) {
3623 $amper = "&";
3624 $kid = "{" . $self->deparse($kid, 0) . "}";
3625 } elsif ($kid->first->name eq "gv") {
3626 my $gv = $self->gv_or_padgv($kid->first);
3627 if (class($gv->CV) ne "SPECIAL") {
3628 $proto = $gv->CV->PV if $gv->CV->FLAGS & SVf_POK;
3629 }
3630 $simple = 1; # only calls of named functions can be prototyped
3631 $kid = $self->deparse($kid, 24);
3632 if (!$amper) {
3633 if ($kid eq 'main::') {
3634 $kid = '::';
3635 } elsif ($kid !~ /^(?:\w|::)(?:[\w\d]|::(?!\z))*\z/) {
3636 $kid = single_delim("q", "'", $kid) . '->';
3637 }
3638 }
3639 } elsif (is_scalar ($kid->first) && $kid->first->name ne 'rv2cv') {
3640 $amper = "&";
3641 $kid = $self->deparse($kid, 24);
3642 } else {
3643 $prefix = "";
3644 my $arrow = is_subscriptable($kid->first) ? "" : "->";
3645 $kid = $self->deparse($kid, 24) . $arrow;
3646 }
3647
3648 # Doesn't matter how many prototypes there are, if
3649 # they haven't happened yet!
3650 my $declared;
3651 {
3652 no strict 'refs';
3653 no warnings 'uninitialized';
3654 $declared = exists $self->{'subs_declared'}{$kid}
3655 || (
3656 defined &{ ${$self->{'curstash'}."::"}{$kid} }
3657 && !exists
3658 $self->{'subs_deparsed'}{$self->{'curstash'}."::".$kid}
3659 && defined prototype $self->{'curstash'}."::".$kid
3660 );
3661 if (!$declared && defined($proto)) {
3662 # Avoid "too early to check prototype" warning
3663 ($amper, $proto) = ('&');
3664 }
3665 }
3666
3667 my $args;
3668 if ($declared and defined $proto and not $amper) {
3669 ($amper, $args) = $self->check_proto($proto, @exprs);
3670 if ($amper eq "&") {
3671 $args = join(", ", map($self->deparse($_, 6), @exprs));
3672 }
3673 } else {
3674 $args = join(", ", map($self->deparse($_, 6), @exprs));
3675 }
3676 if ($prefix or $amper) {
3677 if ($kid eq '&') { $kid = "{$kid}" } # &{&} cannot be written as &&
3678 if ($op->flags & OPf_STACKED) {
3679 return $prefix . $amper . $kid . "(" . $args . ")";
3680 } else {
3681 return $prefix . $amper. $kid;
3682 }
3683 } else {
3684 # It's a syntax error to call CORE::GLOBAL::foo with a prefix,
3685 # so it must have been translated from a keyword call. Translate
3686 # it back.
3687 $kid =~ s/^CORE::GLOBAL:://;
3688
3689 my $dproto = defined($proto) ? $proto : "undefined";
3690 if (!$declared) {
3691 return "$kid(" . $args . ")";
3692 } elsif ($dproto eq "") {
3693 return $kid;
3694 } elsif ($dproto eq "\$" and is_scalar($exprs[0])) {
3695 # is_scalar is an excessively conservative test here:
3696 # really, we should be comparing to the precedence of the
3697 # top operator of $exprs[0] (ala unop()), but that would
3698 # take some major code restructuring to do right.
3699 return $self->maybe_parens_func($kid, $args, $cx, 16);
3700 } elsif ($dproto ne '$' and defined($proto) || $simple) { #'
3701 return $self->maybe_parens_func($kid, $args, $cx, 5);
3702 } else {
3703 return "$kid(" . $args . ")";
3704 }
3705 }
3706}
3707
3708sub pp_enterwrite { unop(@_, "write") }
3709
3710# escape things that cause interpolation in double quotes,
3711# but not character escapes
3712sub uninterp {
3713 my($str) = @_;
3714 $str =~ s/(^|\G|[^\\])((?:\\\\)*)([\$\@]|\\[uUlLQE])/$1$2\\$3/g;
3715 return $str;
3716}
3717
3718{
3719my $bal;
3720BEGIN {
3721 use re "eval";
3722 # Matches any string which is balanced with respect to {braces}
3723 $bal = qr(
3724 (?:
3725 [^\\{}]
3726 | \\\\
3727 | \\[{}]
3728 | \{(??{$bal})\}
3729 )*
3730 )x;
3731}
3732
3733# the same, but treat $|, $), $( and $ at the end of the string differently
3734sub re_uninterp {
3735 my($str) = @_;
3736
3737 $str =~ s/
3738 ( ^|\G # $1
3739 | [^\\]
3740 )
3741
3742 ( # $2
3743 (?:\\\\)*
3744 )
3745
3746 ( # $3
3747 (\(\?\??\{$bal\}\)) # $4
3748 | [\$\@]
3749 (?!\||\)|\(|$)
3750 | \\[uUlLQE]
3751 )
3752
3753 /defined($4) && length($4) ? "$1$2$4" : "$1$2\\$3"/xeg;
3754
3755 return $str;
3756}
3757
3758# This is for regular expressions with the /x modifier
3759# We have to leave comments unmangled.
3760sub re_uninterp_extended {
3761 my($str) = @_;
3762
3763 $str =~ s/
3764 ( ^|\G # $1
3765 | [^\\]
3766 )
3767
3768 ( # $2
3769 (?:\\\\)*
3770 )
3771
3772 ( # $3
3773 ( \(\?\??\{$bal\}\) # $4 (skip over (?{}) and (??{}) blocks)
3774 | \#[^\n]* # (skip over comments)
3775 )
3776 | [\$\@]
3777 (?!\||\)|\(|$|\s)
3778 | \\[uUlLQE]
3779 )
3780
3781 /defined($4) && length($4) ? "$1$2$4" : "$1$2\\$3"/xeg;
3782
3783 return $str;
3784}
3785}
3786
3787my %unctrl = # portable to to EBCDIC
3788 (
3789 "\c@" => '\c@', # unused
3790 "\cA" => '\cA',
3791 "\cB" => '\cB',
3792 "\cC" => '\cC',
3793 "\cD" => '\cD',
3794 "\cE" => '\cE',
3795 "\cF" => '\cF',
3796 "\cG" => '\cG',
3797 "\cH" => '\cH',
3798 "\cI" => '\cI',
3799 "\cJ" => '\cJ',
3800 "\cK" => '\cK',
3801 "\cL" => '\cL',
3802 "\cM" => '\cM',
3803 "\cN" => '\cN',
3804 "\cO" => '\cO',
3805 "\cP" => '\cP',
3806 "\cQ" => '\cQ',
3807 "\cR" => '\cR',
3808 "\cS" => '\cS',
3809 "\cT" => '\cT',
3810 "\cU" => '\cU',
3811 "\cV" => '\cV',
3812 "\cW" => '\cW',
3813 "\cX" => '\cX',
3814 "\cY" => '\cY',
3815 "\cZ" => '\cZ',
3816 "\c[" => '\c[', # unused
3817 "\c\\" => '\c\\', # unused
3818 "\c]" => '\c]', # unused
3819 "\c_" => '\c_', # unused
3820 );
3821
3822# character escapes, but not delimiters that might need to be escaped
3823sub escape_str { # ASCII, UTF8
3824 my($str) = @_;
3825 $str =~ s/(.)/ord($1) > 255 ? sprintf("\\x{%x}", ord($1)) : $1/eg;
3826 $str =~ s/\a/\\a/g;
3827# $str =~ s/\cH/\\b/g; # \b means something different in a regex
3828 $str =~ s/\t/\\t/g;
3829 $str =~ s/\n/\\n/g;
3830 $str =~ s/\e/\\e/g;
3831 $str =~ s/\f/\\f/g;
3832 $str =~ s/\r/\\r/g;
3833 $str =~ s/([\cA-\cZ])/$unctrl{$1}/ge;
3834 $str =~ s/([[:^print:]])/sprintf("\\%03o", ord($1))/ge;
3835 return $str;
3836}
3837
3838# For regexes with the /x modifier.
3839# Leave whitespace unmangled.
3840sub escape_extended_re {
3841 my($str) = @_;
3842 $str =~ s/(.)/ord($1) > 255 ? sprintf("\\x{%x}", ord($1)) : $1/eg;
3843 $str =~ s/([[:^print:]])/
3844 ($1 =~ y! \t\n!!) ? $1 : sprintf("\\%03o", ord($1))/ge;
3845 $str =~ s/\n/\n\f/g;
3846 return $str;
3847}
3848
3849# Don't do this for regexen
3850sub unback {
3851 my($str) = @_;
3852 $str =~ s/\\/\\\\/g;
3853 return $str;
3854}
3855
3856# Remove backslashes which precede literal control characters,
3857# to avoid creating ambiguity when we escape the latter.
3858sub re_unback {
3859 my($str) = @_;
3860
3861 # the insane complexity here is due to the behaviour of "\c\"
3862 $str =~ s/(^|[^\\]|\\c\\)(?<!\\c)\\(\\\\)*(?=[[:^print:]])/$1$2/g;
3863 return $str;
3864}
3865
3866sub balanced_delim {
3867 my($str) = @_;
3868 my @str = split //, $str;
3869 my($ar, $open, $close, $fail, $c, $cnt, $last_bs);
3870 for $ar (['[',']'], ['(',')'], ['<','>'], ['{','}']) {
3871 ($open, $close) = @$ar;
3872 $fail = 0; $cnt = 0; $last_bs = 0;
3873 for $c (@str) {
3874 if ($c eq $open) {
3875 $fail = 1 if $last_bs;
3876 $cnt++;
3877 } elsif ($c eq $close) {
3878 $fail = 1 if $last_bs;
3879 $cnt--;
3880 if ($cnt < 0) {
3881 # qq()() isn't ")("
3882 $fail = 1;
3883 last;
3884 }
3885 }
3886 $last_bs = $c eq '\\';
3887 }
3888 $fail = 1 if $cnt != 0;
3889 return ($open, "$open$str$close") if not $fail;
3890 }
3891 return ("", $str);
3892}
3893
3894sub single_delim {
3895 my($q, $default, $str) = @_;
3896 return "$default$str$default" if $default and index($str, $default) == -1;
3897 if ($q ne 'qr') {
3898 (my $succeed, $str) = balanced_delim($str);
3899 return "$q$str" if $succeed;
3900 }
3901 for my $delim ('/', '"', '#') {
3902 return "$q$delim" . $str . $delim if index($str, $delim) == -1;
3903 }
3904 if ($default) {
3905 $str =~ s/$default/\\$default/g;
3906 return "$default$str$default";
3907 } else {
3908 $str =~ s[/][\\/]g;
3909 return "$q/$str/";
3910 }
3911}
3912
3913my $max_prec;
3914BEGIN { $max_prec = int(0.999 + 8*length(pack("F", 42))*log(2)/log(10)); }
3915
3916# Split a floating point number into an integer mantissa and a binary
3917# exponent. Assumes you've already made sure the number isn't zero or
3918# some weird infinity or NaN.
3919sub split_float {
3920 my($f) = @_;
3921 my $exponent = 0;
3922 if ($f == int($f)) {
3923 while ($f % 2 == 0) {
3924 $f /= 2;
3925 $exponent++;
3926 }
3927 } else {
3928 while ($f != int($f)) {
3929 $f *= 2;
3930 $exponent--;
3931 }
3932 }
3933 my $mantissa = sprintf("%.0f", $f);
3934 return ($mantissa, $exponent);
3935}
3936
3937sub const {
3938 my $self = shift;
3939 my($sv, $cx) = @_;
3940 if ($self->{'use_dumper'}) {
3941 return $self->const_dumper($sv, $cx);
3942 }
3943 if (class($sv) eq "SPECIAL") {
3944 # sv_undef, sv_yes, sv_no
3945 return ('undef', '1', $self->maybe_parens("!1", $cx, 21))[$$sv-1];
3946 }
3947 if (class($sv) eq "NULL") {
3948 return 'undef';
3949 }
3950 # convert a version object into the "v1.2.3" string in its V magic
3951 if ($sv->FLAGS & SVs_RMG) {
3952 for (my $mg = $sv->MAGIC; $mg; $mg = $mg->MOREMAGIC) {
3953 return $mg->PTR if $mg->TYPE eq 'V';
3954 }
3955 }
3956
3957 if ($sv->FLAGS & SVf_IOK) {
3958 my $str = $sv->int_value;
3959 $str = $self->maybe_parens($str, $cx, 21) if $str < 0;
3960 return $str;
3961 } elsif ($sv->FLAGS & SVf_NOK) {
3962 my $nv = $sv->NV;
3963 if ($nv == 0) {
3964 if (pack("F", $nv) eq pack("F", 0)) {
3965 # positive zero
3966 return "0";
3967 } else {
3968 # negative zero
3969 return $self->maybe_parens("-.0", $cx, 21);
3970 }
3971 } elsif (1/$nv == 0) {
3972 if ($nv > 0) {
3973 # positive infinity
3974 return $self->maybe_parens("9**9**9", $cx, 22);
3975 } else {
3976 # negative infinity
3977 return $self->maybe_parens("-9**9**9", $cx, 21);
3978 }
3979 } elsif ($nv != $nv) {
3980 # NaN
3981 if (pack("F", $nv) eq pack("F", sin(9**9**9))) {
3982 # the normal kind
3983 return "sin(9**9**9)";
3984 } elsif (pack("F", $nv) eq pack("F", -sin(9**9**9))) {
3985 # the inverted kind
3986 return $self->maybe_parens("-sin(9**9**9)", $cx, 21);
3987 } else {
3988 # some other kind
3989 my $hex = unpack("h*", pack("F", $nv));
3990 return qq'unpack("F", pack("h*", "$hex"))';
3991 }
3992 }
3993 # first, try the default stringification
3994 my $str = "$nv";
3995 if ($str != $nv) {
3996 # failing that, try using more precision
3997 $str = sprintf("%.${max_prec}g", $nv);
3998# if (pack("F", $str) ne pack("F", $nv)) {
3999 if ($str != $nv) {
4000 # not representable in decimal with whatever sprintf()
4001 # and atof() Perl is using here.
4002 my($mant, $exp) = split_float($nv);
4003 return $self->maybe_parens("$mant * 2**$exp", $cx, 19);
4004 }
4005 }
4006 $str = $self->maybe_parens($str, $cx, 21) if $nv < 0;
4007 return $str;
4008 } elsif ($sv->FLAGS & SVf_ROK && $sv->can("RV")) {
4009 my $ref = $sv->RV;
4010 if (class($ref) eq "AV") {
4011 return "[" . $self->list_const(2, $ref->ARRAY) . "]";
4012 } elsif (class($ref) eq "HV") {
4013 my %hash = $ref->ARRAY;
4014 my @elts;
4015 for my $k (sort keys %hash) {
4016 push @elts, "$k => " . $self->const($hash{$k}, 6);
4017 }
4018 return "{" . join(", ", @elts) . "}";
4019 } elsif (class($ref) eq "CV") {
4020 BEGIN {
4021 if ($] > 5.0150051) {
4022 require overloading;
4023 unimport overloading;
4024 }
4025 }
4026 if ($] > 5.0150051 && $self->{curcv} &&
4027 $self->{curcv}->object_2svref == $ref->object_2svref) {
4028 return $self->keyword("__SUB__");
4029 }
4030 return "sub " . $self->deparse_sub($ref);
4031 }
4032 if ($ref->FLAGS & SVs_SMG) {
4033 for (my $mg = $ref->MAGIC; $mg; $mg = $mg->MOREMAGIC) {
4034 if ($mg->TYPE eq 'r') {
4035 my $re = re_uninterp(escape_str(re_unback($mg->precomp)));
4036 return single_delim("qr", "", $re);
4037 }
4038 }
4039 }
4040
4041 return $self->maybe_parens("\\" . $self->const($ref, 20), $cx, 20);
4042 } elsif ($sv->FLAGS & SVf_POK) {
4043 my $str = $sv->PV;
4044 if ($str =~ /[[:^print:]]/) {
4045 return single_delim("qq", '"', uninterp escape_str unback $str);
4046 } else {
4047 return single_delim("q", "'", unback $str);
4048 }
4049 } else {
4050 return "undef";
4051 }
4052}
4053
4054sub const_dumper {
4055 my $self = shift;
4056 my($sv, $cx) = @_;
4057 my $ref = $sv->object_2svref();
4058 my $dumper = Data::Dumper->new([$$ref], ['$v']);
4059 $dumper->Purity(1)->Terse(1)->Deparse(1)->Indent(0)->Useqq(1)->Sortkeys(1);
4060 my $str = $dumper->Dump();
4061 if ($str =~ /^\$v/) {
4062 return '${my ' . $str . ' \$v}';
4063 } else {
4064 return $str;
4065 }
4066}
4067
4068sub const_sv {
4069 my $self = shift;
4070 my $op = shift;
4071 my $sv = $op->sv;
4072 # the constant could be in the pad (under useithreads)
4073 $sv = $self->padval($op->targ) unless $$sv;
4074 return $sv;
4075}
4076
4077sub pp_const {
4078 my $self = shift;
4079 my($op, $cx) = @_;
4080 if ($op->private & OPpCONST_ARYBASE) {
4081 return '$[';
4082 }
4083# if ($op->private & OPpCONST_BARE) { # trouble with '=>' autoquoting
4084# return $self->const_sv($op)->PV;
4085# }
4086 my $sv = $self->const_sv($op);
4087 return $self->const($sv, $cx);
4088}
4089
4090sub dq {
4091 my $self = shift;
4092 my $op = shift;
4093 my $type = $op->name;
4094 if ($type eq "const") {
4095 return '$[' if $op->private & OPpCONST_ARYBASE;
4096 return uninterp(escape_str(unback($self->const_sv($op)->as_string)));
4097 } elsif ($type eq "concat") {
4098 my $first = $self->dq($op->first);
4099 my $last = $self->dq($op->last);
4100
4101 # Disambiguate "${foo}bar", "${foo}{bar}", "${foo}[1]", "$foo\::bar"
4102 ($last =~ /^[A-Z\\\^\[\]_?]/ &&
4103 $first =~ s/([\$@])\^$/${1}{^}/) # "${^}W" etc
4104 || ($last =~ /^[:'{\[\w_]/ && #'
4105 $first =~ s/([\$@])([A-Za-z_]\w*)$/${1}{$2}/);
4106
4107 return $first . $last;
4108 } elsif ($type eq "uc") {
4109 return '\U' . $self->dq($op->first->sibling) . '\E';
4110 } elsif ($type eq "lc") {
4111 return '\L' . $self->dq($op->first->sibling) . '\E';
4112 } elsif ($type eq "ucfirst") {
4113 return '\u' . $self->dq($op->first->sibling);
4114 } elsif ($type eq "lcfirst") {
4115 return '\l' . $self->dq($op->first->sibling);
4116 } elsif ($type eq "quotemeta") {
4117 return '\Q' . $self->dq($op->first->sibling) . '\E';
4118 } elsif ($type eq "fc") {
4119 return '\F' . $self->dq($op->first->sibling) . '\E';
4120 } elsif ($type eq "join") {
4121 return $self->deparse($op->last, 26); # was join($", @ary)
4122 } else {
4123 return $self->deparse($op, 26);
4124 }
4125}
4126
4127sub pp_backtick {
4128 my $self = shift;
4129 my($op, $cx) = @_;
4130 # skip pushmark if it exists (readpipe() vs ``)
4131 my $child = $op->first->sibling->isa('B::NULL')
4132 ? $op->first : $op->first->sibling;
4133 if ($self->pure_string($child)) {
4134 return single_delim("qx", '`', $self->dq($child, 1));
4135 }
4136 unop($self, @_, "readpipe");
4137}
4138
4139sub dquote {
4140 my $self = shift;
4141 my($op, $cx) = @_;
4142 my $kid = $op->first->sibling; # skip ex-stringify, pushmark
4143 return $self->deparse($kid, $cx) if $self->{'unquote'};
4144 $self->maybe_targmy($kid, $cx,
4145 sub {single_delim("qq", '"', $self->dq($_[1]))});
4146}
4147
4148# OP_STRINGIFY is a listop, but it only ever has one arg
4149sub pp_stringify { maybe_targmy(@_, \&dquote) }
4150
4151# tr/// and s/// (and tr[][], tr[]//, tr###, etc)
4152# note that tr(from)/to/ is OK, but not tr/from/(to)
4153sub double_delim {
4154 my($from, $to) = @_;
4155 my($succeed, $delim);
4156 if ($from !~ m[/] and $to !~ m[/]) {
4157 return "/$from/$to/";
4158 } elsif (($succeed, $from) = balanced_delim($from) and $succeed) {
4159 if (($succeed, $to) = balanced_delim($to) and $succeed) {
4160 return "$from$to";
4161 } else {
4162 for $delim ('/', '"', '#') { # note no "'" -- s''' is special
4163 return "$from$delim$to$delim" if index($to, $delim) == -1;
4164 }
4165 $to =~ s[/][\\/]g;
4166 return "$from/$to/";
4167 }
4168 } else {
4169 for $delim ('/', '"', '#') { # note no '
4170 return "$delim$from$delim$to$delim"
4171 if index($to . $from, $delim) == -1;
4172 }
4173 $from =~ s[/][\\/]g;
4174 $to =~ s[/][\\/]g;
4175 return "/$from/$to/";
4176 }
4177}
4178
4179# Only used by tr///, so backslashes hyphens
4180sub pchr { # ASCII
4181 my($n) = @_;
4182 if ($n == ord '\\') {
4183 return '\\\\';
4184 } elsif ($n == ord "-") {
4185 return "\\-";
4186 } elsif ($n >= ord(' ') and $n <= ord('~')) {
4187 return chr($n);
4188 } elsif ($n == ord "\a") {
4189 return '\\a';
4190 } elsif ($n == ord "\b") {
4191 return '\\b';
4192 } elsif ($n == ord "\t") {
4193 return '\\t';
4194 } elsif ($n == ord "\n") {
4195 return '\\n';
4196 } elsif ($n == ord "\e") {
4197 return '\\e';
4198 } elsif ($n == ord "\f") {
4199 return '\\f';
4200 } elsif ($n == ord "\r") {
4201 return '\\r';
4202 } elsif ($n >= ord("\cA") and $n <= ord("\cZ")) {
4203 return '\\c' . chr(ord("@") + $n);
4204 } else {
4205# return '\x' . sprintf("%02x", $n);
4206 return '\\' . sprintf("%03o", $n);
4207 }
4208}
4209
4210sub collapse {
4211 my(@chars) = @_;
4212 my($str, $c, $tr) = ("");
4213 for ($c = 0; $c < @chars; $c++) {
4214 $tr = $chars[$c];
4215 $str .= pchr($tr);
4216 if ($c <= $#chars - 2 and $chars[$c + 1] == $tr + 1 and
4217 $chars[$c + 2] == $tr + 2)
4218 {
4219 for (; $c <= $#chars-1 and $chars[$c + 1] == $chars[$c] + 1; $c++)
4220 {}
4221 $str .= "-";
4222 $str .= pchr($chars[$c]);
4223 }
4224 }
4225 return $str;
4226}
4227
4228sub tr_decode_byte {
4229 my($table, $flags) = @_;
4230 my(@table) = unpack("s*", $table);
4231 splice @table, 0x100, 1; # Number of subsequent elements
4232 my($c, $tr, @from, @to, @delfrom, $delhyphen);
4233 if ($table[ord "-"] != -1 and
4234 $table[ord("-") - 1] == -1 || $table[ord("-") + 1] == -1)
4235 {
4236 $tr = $table[ord "-"];
4237 $table[ord "-"] = -1;
4238 if ($tr >= 0) {
4239 @from = ord("-");
4240 @to = $tr;
4241 } else { # -2 ==> delete
4242 $delhyphen = 1;
4243 }
4244 }
4245 for ($c = 0; $c < @table; $c++) {
4246 $tr = $table[$c];
4247 if ($tr >= 0) {
4248 push @from, $c; push @to, $tr;
4249 } elsif ($tr == -2) {
4250 push @delfrom, $c;
4251 }
4252 }
4253 @from = (@from, @delfrom);
4254 if ($flags & OPpTRANS_COMPLEMENT) {
4255 my @newfrom = ();
4256 my %from;
4257 @from{@from} = (1) x @from;
4258 for ($c = 0; $c < 256; $c++) {
4259 push @newfrom, $c unless $from{$c};
4260 }
4261 @from = @newfrom;
4262 }
4263 unless ($flags & OPpTRANS_DELETE || !@to) {
4264 pop @to while $#to and $to[$#to] == $to[$#to -1];
4265 }
4266 my($from, $to);
4267 $from = collapse(@from);
4268 $to = collapse(@to);
4269 $from .= "-" if $delhyphen;
4270 return ($from, $to);
4271}
4272
4273sub tr_chr {
4274 my $x = shift;
4275 if ($x == ord "-") {
4276 return "\\-";
4277 } elsif ($x == ord "\\") {
4278 return "\\\\";
4279 } else {
4280 return chr $x;
4281 }
4282}
4283
4284# XXX This doesn't yet handle all cases correctly either
4285
4286sub tr_decode_utf8 {
4287 my($swash_hv, $flags) = @_;
4288 my %swash = $swash_hv->ARRAY;
4289 my $final = undef;
4290 $final = $swash{'FINAL'}->IV if exists $swash{'FINAL'};
4291 my $none = $swash{"NONE"}->IV;
4292 my $extra = $none + 1;
4293 my(@from, @delfrom, @to);
4294 my $line;
4295 foreach $line (split /\n/, $swash{'LIST'}->PV) {
4296 my($min, $max, $result) = split(/\t/, $line);
4297 $min = hex $min;
4298 if (length $max) {
4299 $max = hex $max;
4300 } else {
4301 $max = $min;
4302 }
4303 $result = hex $result;
4304 if ($result == $extra) {
4305 push @delfrom, [$min, $max];
4306 } else {
4307 push @from, [$min, $max];
4308 push @to, [$result, $result + $max - $min];
4309 }
4310 }
4311 for my $i (0 .. $#from) {
4312 if ($from[$i][0] == ord '-') {
4313 unshift @from, splice(@from, $i, 1);
4314 unshift @to, splice(@to, $i, 1);
4315 last;
4316 } elsif ($from[$i][1] == ord '-') {
4317 $from[$i][1]--;
4318 $to[$i][1]--;
4319 unshift @from, ord '-';
4320 unshift @to, ord '-';
4321 last;
4322 }
4323 }
4324 for my $i (0 .. $#delfrom) {
4325 if ($delfrom[$i][0] == ord '-') {
4326 push @delfrom, splice(@delfrom, $i, 1);
4327 last;
4328 } elsif ($delfrom[$i][1] == ord '-') {
4329 $delfrom[$i][1]--;
4330 push @delfrom, ord '-';
4331 last;
4332 }
4333 }
4334 if (defined $final and $to[$#to][1] != $final) {
4335 push @to, [$final, $final];
4336 }
4337 push @from, @delfrom;
4338 if ($flags & OPpTRANS_COMPLEMENT) {
4339 my @newfrom;
4340 my $next = 0;
4341 for my $i (0 .. $#from) {
4342 push @newfrom, [$next, $from[$i][0] - 1];
4343 $next = $from[$i][1] + 1;
4344 }
4345 @from = ();
4346 for my $range (@newfrom) {
4347 if ($range->[0] <= $range->[1]) {
4348 push @from, $range;
4349 }
4350 }
4351 }
4352 my($from, $to, $diff);
4353 for my $chunk (@from) {
4354 $diff = $chunk->[1] - $chunk->[0];
4355 if ($diff > 1) {
4356 $from .= tr_chr($chunk->[0]) . "-" . tr_chr($chunk->[1]);
4357 } elsif ($diff == 1) {
4358 $from .= tr_chr($chunk->[0]) . tr_chr($chunk->[1]);
4359 } else {
4360 $from .= tr_chr($chunk->[0]);
4361 }
4362 }
4363 for my $chunk (@to) {
4364 $diff = $chunk->[1] - $chunk->[0];
4365 if ($diff > 1) {
4366 $to .= tr_chr($chunk->[0]) . "-" . tr_chr($chunk->[1]);
4367 } elsif ($diff == 1) {
4368 $to .= tr_chr($chunk->[0]) . tr_chr($chunk->[1]);
4369 } else {
4370 $to .= tr_chr($chunk->[0]);
4371 }
4372 }
4373 #$final = sprintf("%04x", $final) if defined $final;
4374 #$none = sprintf("%04x", $none) if defined $none;
4375 #$extra = sprintf("%04x", $extra) if defined $extra;
4376 #print STDERR "final: $final\n none: $none\nextra: $extra\n";
4377 #print STDERR $swash{'LIST'}->PV;
4378 return (escape_str($from), escape_str($to));
4379}
4380
4381sub pp_trans {
4382 my $self = shift;
4383 my($op, $cx) = @_;
4384 my($from, $to);
4385 my $class = class($op);
4386 my $priv_flags = $op->private;
4387 if ($class eq "PVOP") {
4388 ($from, $to) = tr_decode_byte($op->pv, $priv_flags);
4389 } elsif ($class eq "PADOP") {
4390 ($from, $to)
4391 = tr_decode_utf8($self->padval($op->padix)->RV, $priv_flags);
4392 } else { # class($op) eq "SVOP"
4393 ($from, $to) = tr_decode_utf8($op->sv->RV, $priv_flags);
4394 }
4395 my $flags = "";
4396 $flags .= "c" if $priv_flags & OPpTRANS_COMPLEMENT;
4397 $flags .= "d" if $priv_flags & OPpTRANS_DELETE;
4398 $to = "" if $from eq $to and $flags eq "";
4399 $flags .= "s" if $priv_flags & OPpTRANS_SQUASH;
4400 return "tr" . double_delim($from, $to) . $flags;
4401}
4402
4403sub pp_transr { &pp_trans . 'r' }
4404
4405sub re_dq_disambiguate {
4406 my ($first, $last) = @_;
4407 # Disambiguate "${foo}bar", "${foo}{bar}", "${foo}[1]"
4408 ($last =~ /^[A-Z\\\^\[\]_?]/ &&
4409 $first =~ s/([\$@])\^$/${1}{^}/) # "${^}W" etc
4410 || ($last =~ /^[{\[\w_]/ &&
4411 $first =~ s/([\$@])([A-Za-z_]\w*)$/${1}{$2}/);
4412 return $first . $last;
4413}
4414
4415# Like dq(), but different
4416sub re_dq {
4417 my $self = shift;
4418 my ($op, $extended) = @_;
4419
4420 my $type = $op->name;
4421 if ($type eq "const") {
4422 return '$[' if $op->private & OPpCONST_ARYBASE;
4423 my $unbacked = re_unback($self->const_sv($op)->as_string);
4424 return re_uninterp_extended(escape_extended_re($unbacked))
4425 if $extended;
4426 return re_uninterp(escape_str($unbacked));
4427 } elsif ($type eq "concat") {
4428 my $first = $self->re_dq($op->first, $extended);
4429 my $last = $self->re_dq($op->last, $extended);
4430 return re_dq_disambiguate($first, $last);
4431 } elsif ($type eq "uc") {
4432 return '\U' . $self->re_dq($op->first->sibling, $extended) . '\E';
4433 } elsif ($type eq "lc") {
4434 return '\L' . $self->re_dq($op->first->sibling, $extended) . '\E';
4435 } elsif ($type eq "ucfirst") {
4436 return '\u' . $self->re_dq($op->first->sibling, $extended);
4437 } elsif ($type eq "lcfirst") {
4438 return '\l' . $self->re_dq($op->first->sibling, $extended);
4439 } elsif ($type eq "quotemeta") {
4440 return '\Q' . $self->re_dq($op->first->sibling, $extended) . '\E';
4441 } elsif ($type eq "fc") {
4442 return '\F' . $self->re_dq($op->first->sibling, $extended) . '\E';
4443 } elsif ($type eq "join") {
4444 return $self->deparse($op->last, 26); # was join($", @ary)
4445 } else {
4446 my $ret = $self->deparse($op, 26);
4447 $ret =~ s/^\$([(|)])\z/\${$1}/; # $( $| $) need braces
4448 return $ret;
4449 }
4450}
4451
4452sub pure_string {
4453 my ($self, $op) = @_;
4454 return 0 if null $op;
4455 my $type = $op->name;
4456
4457 if ($type eq 'const' || $type eq 'av2arylen') {
4458 return 1;
4459 }
4460 elsif ($type =~ /^(?:[ul]c(first)?|fc)$/ || $type eq 'quotemeta') {
4461 return $self->pure_string($op->first->sibling);
4462 }
4463 elsif ($type eq 'join') {
4464 my $join_op = $op->first->sibling; # Skip pushmark
4465 return 0 unless $join_op->name eq 'null' && $join_op->targ eq OP_RV2SV;
4466
4467 my $gvop = $join_op->first;
4468 return 0 unless $gvop->name eq 'gvsv';
4469 return 0 unless '"' eq $self->gv_name($self->gv_or_padgv($gvop));
4470
4471 return 0 unless ${$join_op->sibling} eq ${$op->last};
4472 return 0 unless $op->last->name =~ /^(?:[ah]slice|(?:rv2|pad)av)$/;
4473 }
4474 elsif ($type eq 'concat') {
4475 return $self->pure_string($op->first)
4476 && $self->pure_string($op->last);
4477 }
4478 elsif (is_scalar($op) || $type =~ /^[ah]elem$/) {
4479 return 1;
4480 }
4481 elsif ($type eq "null" and $op->can('first') and not null $op->first and
4482 ($op->first->name eq "null" and $op->first->can('first')
4483 and not null $op->first->first and
4484 $op->first->first->name eq "aelemfast"
4485 or
4486 $op->first->name =~ /^aelemfast(?:_lex)?\z/
4487 )) {
4488 return 1;
4489 }
4490 else {
4491 return 0;
4492 }
4493
4494 return 1;
4495}
4496
4497sub regcomp {
4498 my $self = shift;
4499 my($op, $cx, $extended) = @_;
4500 my $kid = $op->first;
4501 $kid = $kid->first if $kid->name eq "regcmaybe";
4502 $kid = $kid->first if $kid->name eq "regcreset";
4503 if ($kid->name eq "null" and !null($kid->first)
4504 and $kid->first->name eq 'pushmark')
4505 {
4506 my $str = '';
4507 $kid = $kid->first->sibling;
4508 while (!null($kid)) {
4509 my $first = $str;
4510 my $last = $self->re_dq($kid, $extended);
4511 $str = re_dq_disambiguate($first, $last);
4512 $kid = $kid->sibling;
4513 }
4514 return $str, 1;
4515 }
4516
4517 return ($self->re_dq($kid, $extended), 1) if $self->pure_string($kid);
4518 return ($self->deparse($kid, $cx), 0);
4519}
4520
4521sub pp_regcomp {
4522 my ($self, $op, $cx) = @_;
4523 return (($self->regcomp($op, $cx, 0))[0]);
4524}
4525
4526sub re_flags {
4527 my ($self, $op) = @_;
4528 my $flags = '';
4529 my $pmflags = $op->pmflags;
4530 $flags .= "g" if $pmflags & PMf_GLOBAL;
4531 $flags .= "i" if $pmflags & PMf_FOLD;
4532 $flags .= "m" if $pmflags & PMf_MULTILINE;
4533 $flags .= "o" if $pmflags & PMf_KEEP;
4534 $flags .= "s" if $pmflags & PMf_SINGLELINE;
4535 $flags .= "x" if $pmflags & PMf_EXTENDED;
4536 $flags .= "p" if $pmflags & RXf_PMf_KEEPCOPY;
4537 if (my $charset = $pmflags & RXf_PMf_CHARSET) {
4538 # Hardcoding this is fragile, but B does not yet export the
4539 # constants we need.
4540 $flags .= qw(d l u a aa)[$charset >> 5]
4541 }
4542 # The /d flag is indicated by 0; only show it if necessary.
4543 elsif ($self->{hinthash} and
4544 $self->{hinthash}{reflags_charset}
4545 || $self->{hinthash}{feature_unicode}
4546 or $self->{hints} & $feature::hint_mask
4547 && ($self->{hints} & $feature::hint_mask)
4548 != $feature::hint_mask
4549 && do {
4550 $self->{hints} & $feature::hint_uni8bit;
4551 }
4552 ) {
4553 $flags .= 'd';
4554 }
4555 $flags;
4556}
4557
4558# osmic acid -- see osmium tetroxide
4559
4560my %matchwords;
4561map($matchwords{join "", sort split //, $_} = $_, 'cig', 'cog', 'cos', 'cogs',
4562 'cox', 'go', 'is', 'ism', 'iso', 'mig', 'mix', 'osmic', 'ox', 'sic',
4563 'sig', 'six', 'smog', 'so', 'soc', 'sog', 'xi');
4564
4565sub matchop {
4566 my $self = shift;
4567 my($op, $cx, $name, $delim) = @_;
4568 my $kid = $op->first;
4569 my ($binop, $var, $re) = ("", "", "");
4570 if ($op->flags & OPf_STACKED) {
4571 $binop = 1;
4572 $var = $self->deparse($kid, 20);
4573 $kid = $kid->sibling;
4574 }
4575 my $quote = 1;
4576 my $pmflags = $op->pmflags;
4577 my $extended = ($pmflags & PMf_EXTENDED);
4578 my $rhs_bound_to_defsv;
4579 if (null $kid) {
4580 my $unbacked = re_unback($op->precomp);
4581 if ($extended) {
4582 $re = re_uninterp_extended(escape_extended_re($unbacked));
4583 } else {
4584 $re = re_uninterp(escape_str(re_unback($op->precomp)));
4585 }
4586 } elsif ($kid->name ne 'regcomp') {
4587 carp("found ".$kid->name." where regcomp expected");
4588 } else {
4589 ($re, $quote) = $self->regcomp($kid, 21, $extended);
4590 my $matchop = $kid->first;
4591 if ($matchop->name eq 'regcrest') {
4592 $matchop = $matchop->first;
4593 }
4594 if ($matchop->name =~ /^(?:match|transr?|subst)\z/
4595 && $matchop->flags & OPf_SPECIAL) {
4596 $rhs_bound_to_defsv = 1;
4597 }
4598 }
4599 my $flags = "";
4600 $flags .= "c" if $pmflags & PMf_CONTINUE;
4601 $flags .= $self->re_flags($op);
4602 $flags = join '', sort split //, $flags;
4603 $flags = $matchwords{$flags} if $matchwords{$flags};
4604 if ($pmflags & PMf_ONCE) { # only one kind of delimiter works here
4605 $re =~ s/\?/\\?/g;
4606 $re = "?$re?";
4607 } elsif ($quote) {
4608 $re = single_delim($name, $delim, $re);
4609 }
4610 $re = $re . $flags if $quote;
4611 if ($binop) {
4612 return
4613 $self->maybe_parens(
4614 $rhs_bound_to_defsv
4615 ? "$var =~ (\$_ =~ $re)"
4616 : "$var =~ $re",
4617 $cx, 20
4618 );
4619 } else {
4620 return $re;
4621 }
4622}
4623
4624sub pp_match { matchop(@_, "m", "/") }
4625sub pp_pushre { matchop(@_, "m", "/") }
4626sub pp_qr { matchop(@_, "qr", "") }
4627
4628sub pp_runcv { unop(@_, "__SUB__"); }
4629
4630sub pp_split {
4631 my $self = shift;
4632 my($op, $cx) = @_;
4633 my($kid, @exprs, $ary, $expr);
4634 $kid = $op->first;
4635
4636 # For our kid (an OP_PUSHRE), pmreplroot is never actually the
4637 # root of a replacement; it's either empty, or abused to point to
4638 # the GV for an array we split into (an optimization to save
4639 # assignment overhead). Depending on whether we're using ithreads,
4640 # this OP* holds either a GV* or a PADOFFSET. Luckily, B.xs
4641 # figures out for us which it is.
4642 my $replroot = $kid->pmreplroot;
4643 my $gv = 0;
4644 if (ref($replroot) eq "B::GV") {
4645 $gv = $replroot;
4646 } elsif (!ref($replroot) and $replroot > 0) {
4647 $gv = $self->padval($replroot);
4648 }
4649 $ary = $self->stash_variable('@', $self->gv_name($gv), $cx) if $gv;
4650
4651 for (; !null($kid); $kid = $kid->sibling) {
4652 push @exprs, $self->deparse($kid, 6);
4653 }
4654
4655 # handle special case of split(), and split(' ') that compiles to /\s+/
4656 # Under 5.10, the reflags may be undef if the split regexp isn't a constant
4657 $kid = $op->first;
4658 if ( $kid->flags & OPf_SPECIAL
4659 and ( $] < 5.009 ? $kid->pmflags & PMf_SKIPWHITE()
4660 : ($kid->reflags || 0) & RXf_SKIPWHITE() ) ) {
4661 $exprs[0] = "' '";
4662 }
4663
4664 $expr = "split(" . join(", ", @exprs) . ")";
4665 if ($ary) {
4666 return $self->maybe_parens("$ary = $expr", $cx, 7);
4667 } else {
4668 return $expr;
4669 }
4670}
4671
4672# oxime -- any of various compounds obtained chiefly by the action of
4673# hydroxylamine on aldehydes and ketones and characterized by the
4674# bivalent grouping C=NOH [Webster's Tenth]
4675
4676my %substwords;
4677map($substwords{join "", sort split //, $_} = $_, 'ego', 'egoism', 'em',
4678 'es', 'ex', 'exes', 'gee', 'go', 'goes', 'ie', 'ism', 'iso', 'me',
4679 'meese', 'meso', 'mig', 'mix', 'os', 'ox', 'oxime', 'see', 'seem',
4680 'seg', 'sex', 'sig', 'six', 'smog', 'sog', 'some', 'xi', 'rogue',
4681 'sir', 'rise', 'smore', 'more', 'seer', 'rome', 'gore', 'grim', 'grime',
4682 'or', 'rose', 'rosie');
4683
4684sub pp_subst {
4685 my $self = shift;
4686 my($op, $cx) = @_;
4687 my $kid = $op->first;
4688 my($binop, $var, $re, $repl) = ("", "", "", "");
4689 if ($op->flags & OPf_STACKED) {
4690 $binop = 1;
4691 $var = $self->deparse($kid, 20);
4692 $kid = $kid->sibling;
4693 }
4694 my $flags = "";
4695 my $pmflags = $op->pmflags;
4696 if (null($op->pmreplroot)) {
4697 $repl = $self->dq($kid);
4698 $kid = $kid->sibling;
4699 } else {
4700 $repl = $op->pmreplroot->first; # skip substcont
4701 while ($repl->name eq "entereval") {
4702 $repl = $repl->first;
4703 $flags .= "e";
4704 }
4705 if ($pmflags & PMf_EVAL) {
4706 $repl = $self->deparse($repl->first, 0);
4707 } else {
4708 $repl = $self->dq($repl);
4709 }
4710 }
4711 my $extended = ($pmflags & PMf_EXTENDED);
4712 if (null $kid) {
4713 my $unbacked = re_unback($op->precomp);
4714 if ($extended) {
4715 $re = re_uninterp_extended(escape_extended_re($unbacked));
4716 }
4717 else {
4718 $re = re_uninterp(escape_str($unbacked));
4719 }
4720 } else {
4721 ($re) = $self->regcomp($kid, 1, $extended);
4722 }
4723 $flags .= "r" if $pmflags & PMf_NONDESTRUCT;
4724 $flags .= "e" if $pmflags & PMf_EVAL;
4725 $flags .= $self->re_flags($op);
4726 $flags = join '', sort split //, $flags;
4727 $flags = $substwords{$flags} if $substwords{$flags};
4728 if ($binop) {
4729 return $self->maybe_parens("$var =~ s"
4730 . double_delim($re, $repl) . $flags,
4731 $cx, 20);
4732 } else {
4733 return "s". double_delim($re, $repl) . $flags;
4734 }
4735}
4736
47371;
4738__END__
4739
4740=head1 NAME
4741
4742B::Deparse - Perl compiler backend to produce perl code
4743
4744=head1 SYNOPSIS
4745
4746B<perl> B<-MO=Deparse>[B<,-d>][B<,-f>I<FILE>][B<,-p>][B<,-q>][B<,-l>]
4747 [B<,-s>I<LETTERS>][B<,-x>I<LEVEL>] I<prog.pl>
4748
4749=head1 DESCRIPTION
4750
4751B::Deparse is a backend module for the Perl compiler that generates
4752perl source code, based on the internal compiled structure that perl
4753itself creates after parsing a program. The output of B::Deparse won't
4754be exactly the same as the original source, since perl doesn't keep
4755track of comments or whitespace, and there isn't a one-to-one
4756correspondence between perl's syntactical constructions and their
4757compiled form, but it will often be close. When you use the B<-p>
4758option, the output also includes parentheses even when they are not
4759required by precedence, which can make it easy to see if perl is
4760parsing your expressions the way you intended.
4761
4762While B::Deparse goes to some lengths to try to figure out what your
4763original program was doing, some parts of the language can still trip
4764it up; it still fails even on some parts of Perl's own test suite. If
4765you encounter a failure other than the most common ones described in
4766the BUGS section below, you can help contribute to B::Deparse's
4767ongoing development by submitting a bug report with a small
4768example.
4769
4770=head1 OPTIONS
4771
4772As with all compiler backend options, these must follow directly after
4773the '-MO=Deparse', separated by a comma but not any white space.
4774
4775=over 4
4776
4777=item B<-d>
4778
4779Output data values (when they appear as constants) using Data::Dumper.
4780Without this option, B::Deparse will use some simple routines of its
4781own for the same purpose. Currently, Data::Dumper is better for some
4782kinds of data (such as complex structures with sharing and
4783self-reference) while the built-in routines are better for others
4784(such as odd floating-point values).
4785
4786=item B<-f>I<FILE>
4787
4788Normally, B::Deparse deparses the main code of a program, and all the subs
4789defined in the same file. To include subs defined in
4790other files, pass the B<-f> option with the filename.
4791You can pass the B<-f> option several times, to
4792include more than one secondary file. (Most of the time you don't want to
4793use it at all.) You can also use this option to include subs which are
4794defined in the scope of a B<#line> directive with two parameters.
4795
4796=item B<-l>
4797
4798Add '#line' declarations to the output based on the line and file
4799locations of the original code.
4800
4801=item B<-p>
4802
4803Print extra parentheses. Without this option, B::Deparse includes
4804parentheses in its output only when they are needed, based on the
4805structure of your program. With B<-p>, it uses parentheses (almost)
4806whenever they would be legal. This can be useful if you are used to
4807LISP, or if you want to see how perl parses your input. If you say
4808
4809 if ($var & 0x7f == 65) {print "Gimme an A!"}
4810 print ($which ? $a : $b), "\n";
4811 $name = $ENV{USER} or "Bob";
4812
4813C<B::Deparse,-p> will print
4814
4815 if (($var & 0)) {
4816 print('Gimme an A!')
4817 };
4818 (print(($which ? $a : $b)), '???');
4819 (($name = $ENV{'USER'}) or '???')
4820
4821which probably isn't what you intended (the C<'???'> is a sign that
4822perl optimized away a constant value).
4823
4824=item B<-P>
4825
4826Disable prototype checking. With this option, all function calls are
4827deparsed as if no prototype was defined for them. In other words,
4828
4829 perl -MO=Deparse,-P -e 'sub foo (\@) { 1 } foo @x'
4830
4831will print
4832
4833 sub foo (\@) {
4834 1;
4835 }
4836 &foo(\@x);
4837
4838making clear how the parameters are actually passed to C<foo>.
4839
4840=item B<-q>
4841
4842Expand double-quoted strings into the corresponding combinations of
4843concatenation, uc, ucfirst, lc, lcfirst, quotemeta, and join. For
4844instance, print
4845
4846 print "Hello, $world, @ladies, \u$gentlemen\E, \u\L$me!";
4847
4848as
4849
4850 print 'Hello, ' . $world . ', ' . join($", @ladies) . ', '
4851 . ucfirst($gentlemen) . ', ' . ucfirst(lc $me . '!');
4852
4853Note that the expanded form represents the way perl handles such
4854constructions internally -- this option actually turns off the reverse
4855translation that B::Deparse usually does. On the other hand, note that
4856C<$x = "$y"> is not the same as C<$x = $y>: the former makes the value
4857of $y into a string before doing the assignment.
4858
4859=item B<-s>I<LETTERS>
4860
4861Tweak the style of B::Deparse's output. The letters should follow
4862directly after the 's', with no space or punctuation. The following
4863options are available:
4864
4865=over 4
4866
4867=item B<C>
4868
4869Cuddle C<elsif>, C<else>, and C<continue> blocks. For example, print
4870
4871 if (...) {
4872 ...
4873 } else {
4874 ...
4875 }
4876
4877instead of
4878
4879 if (...) {
4880 ...
4881 }
4882 else {
4883 ...
4884 }
4885
4886The default is not to cuddle.
4887
4888=item B<i>I<NUMBER>
4889
4890Indent lines by multiples of I<NUMBER> columns. The default is 4 columns.
4891
4892=item B<T>
4893
4894Use tabs for each 8 columns of indent. The default is to use only spaces.
4895For instance, if the style options are B<-si4T>, a line that's indented
48963 times will be preceded by one tab and four spaces; if the options were
4897B<-si8T>, the same line would be preceded by three tabs.
4898
4899=item B<v>I<STRING>B<.>
4900
4901Print I<STRING> for the value of a constant that can't be determined
4902because it was optimized away (mnemonic: this happens when a constant
4903is used in B<v>oid context). The end of the string is marked by a period.
4904The string should be a valid perl expression, generally a constant.
4905Note that unless it's a number, it probably needs to be quoted, and on
4906a command line quotes need to be protected from the shell. Some
4907conventional values include 0, 1, 42, '', 'foo', and
4908'Useless use of constant omitted' (which may need to be
4909B<-sv"'Useless use of constant omitted'.">
4910or something similar depending on your shell). The default is '???'.
4911If you're using B::Deparse on a module or other file that's require'd,
4912you shouldn't use a value that evaluates to false, since the customary
4913true constant at the end of a module will be in void context when the
4914file is compiled as a main program.
4915
4916=back
4917
4918=item B<-x>I<LEVEL>
4919
4920Expand conventional syntax constructions into equivalent ones that expose
4921their internal operation. I<LEVEL> should be a digit, with higher values
4922meaning more expansion. As with B<-q>, this actually involves turning off
4923special cases in B::Deparse's normal operations.
4924
4925If I<LEVEL> is at least 3, C<for> loops will be translated into equivalent
4926while loops with continue blocks; for instance
4927
4928 for ($i = 0; $i < 10; ++$i) {
4929 print $i;
4930 }
4931
4932turns into
4933
4934 $i = 0;
4935 while ($i < 10) {
4936 print $i;
4937 } continue {
4938 ++$i
4939 }
4940
4941Note that in a few cases this translation can't be perfectly carried back
4942into the source code -- if the loop's initializer declares a my variable,
4943for instance, it won't have the correct scope outside of the loop.
4944
4945If I<LEVEL> is at least 5, C<use> declarations will be translated into
4946C<BEGIN> blocks containing calls to C<require> and C<import>; for
4947instance,
4948
4949 use strict 'refs';
4950
4951turns into
4952
4953 sub BEGIN {
4954 require strict;
4955 do {
4956 'strict'->import('refs')
4957 };
4958 }
4959
4960If I<LEVEL> is at least 7, C<if> statements will be translated into
4961equivalent expressions using C<&&>, C<?:> and C<do {}>; for instance
4962
4963 print 'hi' if $nice;
4964 if ($nice) {
4965 print 'hi';
4966 }
4967 if ($nice) {
4968 print 'hi';
4969 } else {
4970 print 'bye';
4971 }
4972
4973turns into
4974
4975 $nice and print 'hi';
4976 $nice and do { print 'hi' };
4977 $nice ? do { print 'hi' } : do { print 'bye' };
4978
4979Long sequences of elsifs will turn into nested ternary operators, which
4980B::Deparse doesn't know how to indent nicely.
4981
4982=back
4983
4984=head1 USING B::Deparse AS A MODULE
4985
4986=head2 Synopsis
4987
4988 use B::Deparse;
4989 $deparse = B::Deparse->new("-p", "-sC");
4990 $body = $deparse->coderef2text(\&func);
4991 eval "sub func $body"; # the inverse operation
4992
4993=head2 Description
4994
4995B::Deparse can also be used on a sub-by-sub basis from other perl
4996programs.
4997
4998=head2 new
4999
5000 $deparse = B::Deparse->new(OPTIONS)
5001
5002Create an object to store the state of a deparsing operation and any
5003options. The options are the same as those that can be given on the
5004command line (see L</OPTIONS>); options that are separated by commas
5005after B<-MO=Deparse> should be given as separate strings.
5006
5007=head2 ambient_pragmas
5008
5009 $deparse->ambient_pragmas(strict => 'all', '$[' => $[);
5010
5011The compilation of a subroutine can be affected by a few compiler
5012directives, B<pragmas>. These are:
5013
5014=over 4
5015
5016=item *
5017
5018use strict;
5019
5020=item *
5021
5022use warnings;
5023
5024=item *
5025
5026Assigning to the special variable $[
5027
5028=item *
5029
5030use integer;
5031
5032=item *
5033
5034use bytes;
5035
5036=item *
5037
5038use utf8;
5039
5040=item *
5041
5042use re;
5043
5044=back
5045
5046Ordinarily, if you use B::Deparse on a subroutine which has
5047been compiled in the presence of one or more of these pragmas,
5048the output will include statements to turn on the appropriate
5049directives. So if you then compile the code returned by coderef2text,
5050it will behave the same way as the subroutine which you deparsed.
5051
5052However, you may know that you intend to use the results in a
5053particular context, where some pragmas are already in scope. In
5054this case, you use the B<ambient_pragmas> method to describe the
5055assumptions you wish to make.
5056
5057Not all of the options currently have any useful effect. See
5058L</BUGS> for more details.
5059
5060The parameters it accepts are:
5061
5062=over 4
5063
5064=item strict
5065
5066Takes a string, possibly containing several values separated
5067by whitespace. The special values "all" and "none" mean what you'd
5068expect.
5069
5070 $deparse->ambient_pragmas(strict => 'subs refs');
5071
5072=item $[
5073
5074Takes a number, the value of the array base $[.
5075Cannot be non-zero on Perl 5.15.3 or later.
5076
5077=item bytes
5078
5079=item utf8
5080
5081=item integer
5082
5083If the value is true, then the appropriate pragma is assumed to
5084be in the ambient scope, otherwise not.
5085
5086=item re
5087
5088Takes a string, possibly containing a whitespace-separated list of
5089values. The values "all" and "none" are special. It's also permissible
5090to pass an array reference here.
5091
5092 $deparser->ambient_pragmas(re => 'eval');
5093
5094
5095=item warnings
5096
5097Takes a string, possibly containing a whitespace-separated list of
5098values. The values "all" and "none" are special, again. It's also
5099permissible to pass an array reference here.
5100
5101 $deparser->ambient_pragmas(warnings => [qw[void io]]);
5102
5103If one of the values is the string "FATAL", then all the warnings
5104in that list will be considered fatal, just as with the B<warnings>
5105pragma itself. Should you need to specify that some warnings are
5106fatal, and others are merely enabled, you can pass the B<warnings>
5107parameter twice:
5108
5109 $deparser->ambient_pragmas(
5110 warnings => 'all',
5111 warnings => [FATAL => qw/void io/],
5112 );
5113
5114See L<perllexwarn> for more information about lexical warnings.
5115
5116=item hint_bits
5117
5118=item warning_bits
5119
5120These two parameters are used to specify the ambient pragmas in
5121the format used by the special variables $^H and ${^WARNING_BITS}.
5122
5123They exist principally so that you can write code like:
5124
5125 { my ($hint_bits, $warning_bits);
5126 BEGIN {($hint_bits, $warning_bits) = ($^H, ${^WARNING_BITS})}
5127 $deparser->ambient_pragmas (
5128 hint_bits => $hint_bits,
5129 warning_bits => $warning_bits,
5130 '$[' => 0 + $[
5131 ); }
5132
5133which specifies that the ambient pragmas are exactly those which
5134are in scope at the point of calling.
5135
5136=item %^H
5137
5138This parameter is used to specify the ambient pragmas which are
5139stored in the special hash %^H.
5140
5141=back
5142
5143=head2 coderef2text
5144
5145 $body = $deparse->coderef2text(\&func)
5146 $body = $deparse->coderef2text(sub ($$) { ... })
5147
5148Return source code for the body of a subroutine (a block, optionally
5149preceded by a prototype in parens), given a reference to the
5150sub. Because a subroutine can have no names, or more than one name,
5151this method doesn't return a complete subroutine definition -- if you
5152want to eval the result, you should prepend "sub subname ", or "sub "
5153for an anonymous function constructor. Unless the sub was defined in
5154the main:: package, the code will include a package declaration.
5155
5156=head1 BUGS
5157
5158=over 4
5159
5160=item *
5161
5162The only pragmas to be completely supported are: C<use warnings>,
5163C<use strict>, C<use bytes>, C<use integer>
5164and C<use feature>. (C<$[>, which
5165behaves like a pragma, is also supported.)
5166
5167Excepting those listed above, we're currently unable to guarantee that
5168B::Deparse will produce a pragma at the correct point in the program.
5169(Specifically, pragmas at the beginning of a block often appear right
5170before the start of the block instead.)
5171Since the effects of pragmas are often lexically scoped, this can mean
5172that the pragma holds sway over a different portion of the program
5173than in the input file.
5174
5175=item *
5176
5177In fact, the above is a specific instance of a more general problem:
5178we can't guarantee to produce BEGIN blocks or C<use> declarations in
5179exactly the right place. So if you use a module which affects compilation
5180(such as by over-riding keywords, overloading constants or whatever)
5181then the output code might not work as intended.
5182
5183This is the most serious outstanding problem, and will require some help
5184from the Perl core to fix.
5185
5186=item *
5187
5188Some constants don't print correctly either with or without B<-d>.
5189For instance, neither B::Deparse nor Data::Dumper know how to print
5190dual-valued scalars correctly, as in:
5191
5192 use constant E2BIG => ($!=7); $y = E2BIG; print $y, 0+$y;
5193
5194 use constant H => { "#" => 1 }; H->{"#"};
5195
5196=item *
5197
5198An input file that uses source filtering probably won't be deparsed into
5199runnable code, because it will still include the B<use> declaration
5200for the source filtering module, even though the code that is
5201produced is already ordinary Perl which shouldn't be filtered again.
5202
5203=item *
5204
5205Optimised away statements are rendered as
5206'???'. This includes statements that
5207have a compile-time side-effect, such as the obscure
5208
5209 my $x if 0;
5210
5211which is not, consequently, deparsed correctly.
5212
5213 foreach my $i (@_) { 0 }
5214 =>
5215 foreach my $i (@_) { '???' }
5216
5217=item *
5218
5219Lexical (my) variables declared in scopes external to a subroutine
5220appear in code2ref output text as package variables. This is a tricky
5221problem, as perl has no native facility for referring to a lexical variable
5222defined within a different scope, although L<PadWalker> is a good start.
5223
5224=item *
5225
5226There are probably many more bugs on non-ASCII platforms (EBCDIC).
5227
5228=back
5229
5230=head1 AUTHOR
5231
5232Stephen McCamant <smcc@CSUA.Berkeley.EDU>, based on an earlier version
5233by Malcolm Beattie <mbeattie@sable.ox.ac.uk>, with contributions from
5234Gisle Aas, James Duncan, Albert Dvornik, Robin Houston, Dave Mitchell,
5235Hugo van der Sanden, Gurusamy Sarathy, Nick Ing-Simmons, and Rafael
5236Garcia-Suarez.
5237
5238=cut