blib/lib/B/DeparseTree/Common.pm untested

filter: Statementstmt 0.0% 0 / 1440 Branchbran 0.0% 0 / 636 Conditioncond 0.0% 0 / 481 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 176 Podpod 0.0% 0 / 159 totaltotal 0.0% 0 / 2892 CC 319 SCAR 50.3
CC
319
Cov
0%
const
930.0
stash_subs
380.0
compile
380.0
CRAP 153.3
1 # Copyright (c) 2015-2018 Rocky Bernstein
2 # Copyright (c) 1998-2000, 2002, 2003, 2004, 2005, 2006 Stephen McCamant.
3  
4 # All rights reserved.
5 # This module is free software; you can redistribute and/or modify
6 # it under the same terms as Perl itself.
7  
8 # This is based on the module B::Deparse by Stephen McCamant.
9 # It has been extended save tree structure, and is addressible
10 # by opcode address.
11  
12 # B::Parse in turn is based on the module of the same name by Malcolm Beattie,
13 # but essentially none of his code remains.
14 use strict; use warnings;
15  
16 package B::DeparseTree::Common;
17  
18 use B qw(class
19 CVf_LVALUE
20 CVf_METHOD
21 OPf_KIDS
22 OPf_SPECIAL
23 OPf_STACKED
24 OPpCONST_BARE
25 OPpLVAL_INTRO
26 OPpOUR_INTRO
27 OPpSORT_INTEGER
28 OPpSORT_NUMERIC
29 OPpSORT_REVERSE
30 OPpTARGET_MY
31 SVf_IOK
32 SVf_NOK
33 SVf_POK
34 SVf_ROK
35 SVs_PADTMP
36 SVs_RMG
37 SVs_SMG
38 main_cv main_root main_start
39 opnumber
40 perlstring
41 svref_2object
42 );
43  
44 use Carp;
45 use B::Deparse;
46 use B::DeparseTree::Node;
47  
48  
49 our($VERSION, @EXPORT, @ISA);
50 $VERSION = '1.1.0';
51 @ISA = qw(Exporter B::Deparse);
52 @EXPORT = qw(
53 %globalnames
54 %ignored_hints
55 %rev_feature
56 POSTFIX baseop mapop pfixop indirop
57 _features_from_bundle ambiant_pragmas maybe_qualify
58 balanced_delim
59 binop
60 const
61 declare_hinthash
62 declare_hints
63 declare_warnings
64 dedup_parens_func
65 deparse_sub
66 deparse_subname
67 dquote
68 gv_name
69 hint_pragmas
70 indent
71 indent_info
72 indent_list
73 info_from_list
74 info_from_text
75 is_miniwhile is_lexical_subs %strict_bits
76 is_scalar
77 is_scope
78 is_state
79 is_subscriptable
80 listop
81 logop
82 map_texts
83 maybe_parens
84 maybe_qualify
85 maybe_targmy
86 new WARN_MASK
87 next_todo
88 null
89 parens_test
90 pragmata
91 print_protos
92 re_unback
93 scopeop
94 seq_subs
95 single_delim
96 stash_variable_name
97 style_opts
98 unback
99 unop
100 );
101  
102 my $bal;
103 BEGIN {
104 use re "eval";
105 # Matches any string which is balanced with respect to {braces}
106 $bal = qr(
107 (?:
108 [^\\{}]
109 | \\\\
110 | \\[{}]
111 | \{(??{$bal})\}
112 )*
113 )x;
114 }
115  
116 # The BEGIN {} is used here because otherwise this code isn't executed
117 # when you run B::Deparse on itself.
118 my %globalnames;
119 BEGIN { map($globalnames{$_}++, "SIG", "STDIN", "STDOUT", "STDERR", "INC",
120 "ENV", "ARGV", "ARGVOUT", "_"); }
121  
122 my $max_prec;
123 BEGIN { $max_prec = int(0.999 + 8*length(pack("F", 42))*log(2)/log(10)); }
124  
125 BEGIN {
126 # List version-specific constants here.
127 # Easiest way to keep this code portable between version looks to
128 # be to fake up a dummy constant that will never actually be true.
129 foreach (qw(OPpSORT_INPLACE OPpSORT_DESCEND OPpITER_REVERSED
130 OPpCONST_NOVER OPpPAD_STATE PMf_SKIPWHITE RXf_SKIPWHITE
131 RXf_PMf_CHARSET RXf_PMf_KEEPCOPY
132 CVf_LOCKED OPpREVERSE_INPLACE OPpSUBSTR_REPL_FIRST
133 PMf_NONDESTRUCT OPpCONST_ARYBASE OPpEVAL_BYTES)) {
134 eval { import B $_ };
135 no strict 'refs';
136 *{$_} = sub () {0} unless *{$_}{CODE};
137 }
138 }
139  
140 sub new {
141 my $class = shift;
142 my $self = bless {}, $class;
143 $self->{'cuddle'} = "\n";
144 $self->{'curcop'} = undef;
145 $self->{'curstash'} = "main";
146 $self->{'ex_const'} = "'???'";
147 $self->{'expand'} = 0;
148 $self->{'files'} = {};
149 $self->{'indent_size'} = 4;
150 $self->{'opaddr'} = 0;
151 $self->{'linenums'} = 0;
152 $self->{'parens'} = 0;
153 $self->{'subs_todo'} = [];
154 $self->{'unquote'} = 0;
155 $self->{'use_dumper'} = 0;
156 $self->{'use_tabs'} = 0;
157  
158 $self->{'ambient_arybase'} = 0;
159 $self->{'ambient_warnings'} = undef; # Assume no lexical warnings
160 $self->{'ambient_hints'} = 0;
161 $self->{'ambient_hinthash'} = undef;
162  
163 # Given an opcode address, get the accumulated OP tree
164 # OP for that.
165 $self->{optree} = {};
166  
167 $self->init();
168  
169 while (my $arg = shift @_) {
170 if ($arg eq "-d") {
171 $self->{'use_dumper'} = 1;
172 require Data::Dumper;
173 } elsif ($arg =~ /^-f(.*)/) {
174 $self->{'files'}{$1} = 1;
175 } elsif ($arg eq "-l") {
176 $self->{'linenums'} = 1;
177 } elsif ($arg eq "-a") {
178 $self->{'linenums'} = 1;
179 $self->{'opaddr'} = 1;
180 } elsif ($arg eq "-p") {
181 $self->{'parens'} = 1;
182 } elsif ($arg eq "-P") {
183 $self->{'noproto'} = 1;
184 } elsif ($arg eq "-q") {
185 $self->{'unquote'} = 1;
186 } elsif (substr($arg, 0, 2) eq "-s") {
187 $self->style_opts(substr $arg, 2);
188 } elsif ($arg =~ /^-x(\d)$/) {
189 $self->{'expand'} = $1;
190 }
191 }
192 return $self;
193 }
194  
195 {
196 # Mask out the bits that L<warnings::register> uses
197 my $WARN_MASK;
198 BEGIN {
199 $WARN_MASK = $warnings::Bits{all} | $warnings::DeadBits{all};
200 }
201 sub WARN_MASK () {
202 return $WARN_MASK;
203 }
204 }
205  
206 # Initialise the contextual information, either from
207 # defaults provided with the ambient_pragmas method,
208 # or from Perl's own defaults otherwise.
209 sub init {
210 my $self = shift;
211  
212 $self->{'arybase'} = $self->{'ambient_arybase'};
213 $self->{'warnings'} = defined ($self->{'ambient_warnings'})
214 ? $self->{'ambient_warnings'} & WARN_MASK
215 : undef;
216 $self->{'hints'} = $self->{'ambient_hints'};
217 $self->{'hints'} &= 0xFF if $] < 5.009;
218 $self->{'hinthash'} = $self->{'ambient_hinthash'};
219  
220 # also a convenient place to clear out subs_declared
221 delete $self->{'subs_declared'};
222 }
223  
224 my %strict_bits = do {
225 local $^H;
226 map +($_ => strict::bits($_)), qw/refs subs vars/
227 };
228  
229 # FIXME: get from B::Deparse
230 sub is_scalar {
231 my $op = shift;
232 return ($op->name eq "rv2sv" or
233 $op->name eq "padsv" or
234 $op->name eq "gv" or # only in array/hash constructs
235 $op->flags & OPf_KIDS && !null($op->first)
236 && $op->first->name eq "gvsv");
237 }
238  
239 # FIXME: get from B::Deparse
240 sub is_subscriptable {
241 my $op = shift;
242 if ($op->name =~ /^([ahg]elem|multideref$)/) {
243 return 1;
244 } elsif ($op->name eq "entersub") {
245 my $kid = $op->first;
246 return 0 unless null $kid->sibling;
247 $kid = $kid->first;
248 $kid = $kid->sibling until null $kid->sibling;
249 return 0 if is_scope($kid);
250 $kid = $kid->first;
251 return 0 if $kid->name eq "gv" || $kid->name eq "padcv";
252 return 0 if is_scalar($kid);
253 return is_subscriptable($kid);
254 } else {
255 return 0;
256 }
257 }
258  
259 sub listop
260 {
261 my($self, $op, $cx, $name, $kid, $nollafr) = @_;
262 my(@exprs);
263 my $parens = ($cx >= 5) || $self->{'parens'};
264  
265 unless ($kid) {
266 $kid = $op->first->sibling;
267 }
268  
269 # If there are no arguments, add final parentheses (or parenthesize the
270 # whole thing if the llafr does not apply) to account for cases like
271 # (return)+1 or setpgrp()+1. When the llafr does not apply, we use a
272 # precedence of 6 (< comma), as "return, 1" does not need parentheses.
273 if (B::Deparse::null $kid) {
274 my $text = $nollafr
275 ? $self->maybe_parens($self->keyword($name), $cx, 7)
276 : $self->keyword($name) . '()' x (7 < $cx);
277 return info_from_text($op, $self, $text, 'null_listop', {});
278 }
279 my $first;
280 my $fullname = $self->keyword($name);
281 my $proto = prototype("CORE::$name");
282 if (
283 ( (defined $proto && $proto =~ /^;?\*/)
284 || $name eq 'select' # select(F) doesn't have a proto
285 )
286 && $kid->name eq "rv2gv"
287 && !($kid->private & OPpLVAL_INTRO)
288 ) {
289 $first = $self->rv2gv_or_string($kid->first, $op);
290 }
291 else {
292 $first = $self->deparse($kid, 6, $op);
293 }
294 if ($name eq "chmod" && $first->{text} =~ /^\d+$/) {
295 $first = info_from_text($first->{op}, $self, sprintf("%#o", $first->{text}), 'listop_chmod', {});
296 }
297 $first->{text} = "+" + $first->{text}
298 if not $parens and not $nollafr and substr($first->{text}, 0, 1) eq "(";
299 push @exprs, $first;
300 $kid = $kid->sibling;
301 if (defined $proto && $proto =~ /^\*\*/ && $kid->name eq "rv2gv"
302 && !($kid->private & OPpLVAL_INTRO)) {
303 $first = $self->rv2gv_or_string($kid->first, $op);
304 push @exprs, $first;
305 $kid = $kid->sibling;
306 }
307 for ( ; !null($kid); $kid = $kid->sibling) {
308 my $expr = $self->deparse($kid, 6, $op);
309 push @exprs, $expr;
310 }
311  
312 if ($name eq "reverse" && ($op->private & OPpREVERSE_INPLACE)) {
313 my $texts = [$exprs[0->{text}], '=',
314 $fullname . ($parens ? "($exprs[0]->{text})" : " $exprs[0]->{text}")];
315 return info_from_list($op, $self, $texts, ' ', 'listop_reverse', {});
316 }
317  
318 my $opts = {};
319 my @texts = @exprs;
320  
321 if ($name =~ /^(system|exec)$/
322 && ($op->flags & OPf_STACKED)
323 && @texts > 1)
324 {
325 # handle the "system(prog a1, a2, ...)" form
326 # where there is no ', ' between the first two arguments.
327 my $prog = shift @texts;
328 my $first_arg = shift @texts;
329 my @two_args = ($prog, $first_arg);
330 unshift @texts, info_from_list($prog->{op}, $self, [$prog, $first_arg],
331 ' ', 'system|exec', {});
332 }
333  
334 my $type;
335 if ($parens && $nollafr) {
336 @texts = ("($fullname ", $self->combine(', ', \@texts), ')');
337 $type = 'listop_parens_noallfr';
338 } elsif ($parens) {
339 @texts = ("$fullname(", $self->combine(", ", \@texts), ')');
340 $type = 'listop_parens';
341 } else {
342 @texts = ("$fullname ", $self->combine(', ', \@texts));
343 $type = 'listop';
344 }
345 return info_from_list($op, $self, \@texts, '', $type, $opts);
346 }
347  
348 sub pp_bless { listop(@_, "bless") }
349 sub pp_atan2 { maybe_targmy(@_, \&listop, "atan2") }
350 sub pp_substr {
351 my ($self,$op,$cx) = @_;
352 if ($op->private & OPpSUBSTR_REPL_FIRST) {
353 my $left = listop($self, $op, 7, "substr", $op->first->sibling->sibling);
354 my $right = $self->deparse($op->first->sibling, 7, $op);
355 return info_from_list($op, $self,[$left, '=', $right], ' ',
356 'substr_repl_first', {});
357 }
358 return maybe_local(@_, listop(@_, "substr"))
359 }
360 sub pp_vec { maybe_local(@_, listop(@_, "vec")) }
361 sub pp_index { maybe_targmy(@_, \&listop, "index") }
362 sub pp_rindex { maybe_targmy(@_, \&listop, "rindex") }
363 sub pp_sprintf { maybe_targmy(@_, \&listop, "sprintf") }
364 sub pp_formline { listop(@_, "formline") } # see also deparse_format
365 sub pp_crypt { maybe_targmy(@_, \&listop, "crypt") }
366 sub pp_unpack { listop(@_, "unpack") }
367 sub pp_pack { listop(@_, "pack") }
368 sub pp_join { maybe_targmy(@_, \&listop, "join") }
369 sub pp_splice { listop(@_, "splice") }
370 sub pp_push { maybe_targmy(@_, \&listop, "push") }
371 sub pp_unshift { maybe_targmy(@_, \&listop, "unshift") }
372 sub pp_reverse { listop(@_, "reverse") }
373 sub pp_warn { listop(@_, "warn") }
374 sub pp_die { listop(@_, "die") }
375 sub pp_return { listop(@_, "return", undef, 1) } # llafr does not apply
376 sub pp_open { listop(@_, "open") }
377 sub pp_pipe_op { listop(@_, "pipe") }
378 sub pp_tie { listop(@_, "tie") }
379 sub pp_binmode { listop(@_, "binmode") }
380 sub pp_dbmopen { listop(@_, "dbmopen") }
381 sub pp_sselect { listop(@_, "select") }
382 sub pp_select { listop(@_, "select") }
383 sub pp_read { listop(@_, "read") }
384 sub pp_sysopen { listop(@_, "sysopen") }
385 sub pp_sysseek { listop(@_, "sysseek") }
386 sub pp_sysread { listop(@_, "sysread") }
387 sub pp_syswrite { listop(@_, "syswrite") }
388 sub pp_send { listop(@_, "send") }
389 sub pp_recv { listop(@_, "recv") }
390 sub pp_seek { listop(@_, "seek") }
391 sub pp_fcntl { listop(@_, "fcntl") }
392 sub pp_ioctl { listop(@_, "ioctl") }
393 sub pp_flock { maybe_targmy(@_, \&listop, "flock") }
394 sub pp_socket { listop(@_, "socket") }
395 sub pp_sockpair { listop(@_, "socketpair") }
396 sub pp_bind { listop(@_, "bind") }
397 sub pp_connect { listop(@_, "connect") }
398 sub pp_listen { listop(@_, "listen") }
399 sub pp_accept { listop(@_, "accept") }
400 sub pp_shutdown { listop(@_, "shutdown") }
401 sub pp_gsockopt { listop(@_, "getsockopt") }
402 sub pp_ssockopt { listop(@_, "setsockopt") }
403 sub pp_chown { maybe_targmy(@_, \&listop, "chown") }
404 sub pp_unlink { maybe_targmy(@_, \&listop, "unlink") }
405 sub pp_chmod { maybe_targmy(@_, \&listop, "chmod") }
406 sub pp_utime { maybe_targmy(@_, \&listop, "utime") }
407 sub pp_rename { maybe_targmy(@_, \&listop, "rename") }
408 sub pp_link { maybe_targmy(@_, \&listop, "link") }
409 sub pp_symlink { maybe_targmy(@_, \&listop, "symlink") }
410 sub pp_mkdir { maybe_targmy(@_, \&listop, "mkdir") }
411 sub pp_open_dir { listop(@_, "opendir") }
412 sub pp_seekdir { listop(@_, "seekdir") }
413 sub pp_waitpid { maybe_targmy(@_, \&listop, "waitpid") }
414 sub pp_system { maybe_targmy(@_, \&listop, "system") }
415 sub pp_exec { maybe_targmy(@_, \&listop, "exec") }
416 sub pp_kill { maybe_targmy(@_, \&listop, "kill") }
417 sub pp_setpgrp { maybe_targmy(@_, \&listop, "setpgrp") }
418 sub pp_getpriority { maybe_targmy(@_, \&listop, "getpriority") }
419 sub pp_setpriority { maybe_targmy(@_, \&listop, "setpriority") }
420 sub pp_shmget { listop(@_, "shmget") }
421 sub pp_shmctl { listop(@_, "shmctl") }
422 sub pp_shmread { listop(@_, "shmread") }
423 sub pp_shmwrite { listop(@_, "shmwrite") }
424 sub pp_msgget { listop(@_, "msgget") }
425 sub pp_msgctl { listop(@_, "msgctl") }
426 sub pp_msgsnd { listop(@_, "msgsnd") }
427 sub pp_msgrcv { listop(@_, "msgrcv") }
428 sub pp_semget { listop(@_, "semget") }
429 sub pp_semctl { listop(@_, "semctl") }
430 sub pp_semop { listop(@_, "semop") }
431 sub pp_ghbyaddr { listop(@_, "gethostbyaddr") }
432 sub pp_gnbyaddr { listop(@_, "getnetbyaddr") }
433 sub pp_gpbynumber { listop(@_, "getprotobynumber") }
434 sub pp_gsbyname { listop(@_, "getservbyname") }
435 sub pp_gsbyport { listop(@_, "getservbyport") }
436 sub pp_syscall { listop(@_, "syscall") }
437  
438 sub pp_glob
439 {
440 my($self, $op, $cx) = @_;
441  
442 my $opts = {other_ops => [$op->first]};
443 my $kid = $op->first->sibling; # skip pushmark
444 my $keyword =
445 $op->flags & OPf_SPECIAL ? 'glob' : $self->keyword('glob');
446  
447 if ($keyword =~ /^CORE::/ or $kid->name ne 'const') {
448 my $kid_info = $self->dq($kid, $op);
449 my $body = [$kid_info];
450 my $text = $kid_info->{text};
451 if ($text =~ /^\$?(\w|::|\`)+$/ # could look like a readline
452 or $text =~ /[<>]/) {
453 $kid_info = $self->deparse($kid, 0, $op);
454 $body = [$kid_info];
455 $text = $kid_info->{text};
456 $opts->{body} = $body;
457 if ($cx >= 5 || $self->{'parens'}) {
458 return info_from_list($op, $self, [$keyword, '(', $text, ')'], '',
459 'glob_paren', $opts);
460 } else {
461 return info_from_list($op, $self, [$keyword, $text], ' ',
462 'glob_space', $opts);
463 }
464 } else {
465 return info_from_list($op, $self, ['<', $text, '>'], '', 'glob_angle', $opts);
466 }
467 }
468 return info_from_list($op, $self, ['<', '>'], '', 'glob_angle', $opts);
469 }
470  
471 # Truncate is special because OPf_SPECIAL makes a bareword first arg
472 # be a filehandle. This could probably be better fixed in the core
473 # by moving the GV lookup into ck_truc.
474  
475 sub pp_truncate
476 {
477 my($self, $op, $cx) = @_;
478 my(@exprs);
479 my $parens = ($cx >= 5) || $self->{'parens'};
480 my $kid = $op->first->sibling;
481 my $fh;
482 if ($op->flags & OPf_SPECIAL) {
483 # $kid is an OP_CONST
484 $fh = $self->const_sv($kid)->PV;
485 } else {
486 $fh = $self->deparse($kid, 6, $op);
487 $fh = "+$fh" if not $parens and substr($fh, 0, 1) eq "(";
488 }
489 my $len = $self->deparse($kid->sibling, 6, $op);
490 my $name = $self->keyword('truncate');
491 my $opts = {body => [$fh, $len]};
492 my $args = "$fh->{text}, $len->{text}";
493 if ($parens) {
494 return info_from_list($op, $self, [$name, '(', $args, ')'], '',
495 'truncate_parens', $opts);
496 return "$name($fh, $len)";
497 } else {
498 return info_from_list($op, $self, [$name, $args], '', 'truncate', $opts);
499 }
500 }
501  
502 sub pp_list
503 {
504 my($self, $op, $cx) = @_;
505 my($expr, @exprs);
506  
507 my $other_op = $op->first;
508 my $kid = $op->first->sibling; # skip a pushmark
509  
510 if (class($kid) eq 'NULL') {
511 return info_from_text($op, $self, '', 'list_null',
512 {other_ops => [$other_op]});
513 }
514 my $lop;
515 my $local = "either"; # could be local(...), my(...), state(...) or our(...)
516 for ($lop = $kid; !null($lop); $lop = $lop->sibling) {
517 # This assumes that no other private flags equal 128, and that
518 # OPs that store things other than flags in their op_private,
519 # like OP_AELEMFAST, won't be immediate children of a list.
520 #
521 # OP_ENTERSUB and OP_SPLIT can break this logic, so check for them.
522 # I suspect that open and exit can too.
523 # XXX This really needs to be rewritten to accept only those ops
524 # known to take the OPpLVAL_INTRO flag.
525  
526 if (!($lop->private & (OPpLVAL_INTRO|OPpOUR_INTRO)
527 or $lop->name eq "undef")
528 or $lop->name =~ /^(?:entersub|exit|open|split)\z/)
529 {
530 $local = ""; # or not
531 last;
532 }
533 if ($lop->name =~ /^pad[ash]v$/) {
534 if ($lop->private & OPpPAD_STATE) { # state()
535 ($local = "", last) if $local =~ /^(?:local|our|my)$/;
536 $local = "state";
537 } else { # my()
538 ($local = "", last) if $local =~ /^(?:local|our|state)$/;
539 $local = "my";
540 }
541 } elsif ($lop->name =~ /^(gv|rv2)[ash]v$/
542 && $lop->private & OPpOUR_INTRO
543 or $lop->name eq "null" && $lop->first->name eq "gvsv"
544 && $lop->first->private & OPpOUR_INTRO) { # our()
545 ($local = "", last) if $local =~ /^(?:my|local|state)$/;
546 $local = "our";
547 } elsif ($lop->name ne "undef"
548 # specifically avoid the "reverse sort" optimisation,
549 # where "reverse" is nullified
550 && !($lop->name eq 'sort' && ($lop->flags & OPpSORT_REVERSE)))
551 {
552 # local()
553 ($local = "", last) if $local =~ /^(?:my|our|state)$/;
554 $local = "local";
555 }
556 }
557 $local = "" if $local eq "either"; # no point if it's all undefs
558 if (B::Deparse::null $kid->sibling and not $local) {
559 my $info = $self->deparse($kid, $cx, $op);
560 my @other_ops = $info->{other_ops} ? @{$info->{other_ops}} : ();
561 push @other_ops, $other_op;
562 $info->{other_ops} = \@other_ops;
563 return $info;
564 }
565  
566 for (; !null($kid); $kid = $kid->sibling) {
567 if ($local) {
568 if (class($kid) eq "UNOP" and $kid->first->name eq "gvsv") {
569 $lop = $kid->first;
570 } else {
571 $lop = $kid;
572 }
573 $self->{'avoid_local'}{$$lop}++;
574 $expr = $self->deparse($kid, 6, $op);
575 delete $self->{'avoid_local'}{$$lop};
576 } else {
577 $expr = $self->deparse($kid, 6, $op);
578 }
579 push @exprs, $expr;
580 }
581  
582 my $type;
583 my @texts;
584 my $opts = {};
585 if ($local) {
586 $type = 'list_local';
587 @texts = ($local, '(', $self->combine(", ", \@exprs), ')');
588 } else {
589 $type = 'list';
590 @texts = ($self->combine(", ", \@exprs));
591 $opts->{maybe_parens} = [$self, $cx, 6];
592  
593 }
594 return info_from_list($op, $self, \@texts, '', $type, $opts);
595 }
596  
597 sub map_texts($$)
598 {
599 my ($self, $args) = @_;
600 my @result ;
601 foreach my $expr (@$args) {
602 if (ref $expr eq 'ARRAY' and scalar(@$expr) == 2) {
603 # First item is hash and second item is op address.
604 push @result, [$expr->[0]{text}, $expr->[1]];
605 } else {
606 push @result, [$expr->{text}, $expr->{addr}];
607 }
608 }
609 return @result;
610 }
611  
612  
613 sub maybe_qualify {
614 my ($self,$prefix,$name) = @_;
615 my $v = ($prefix eq '$#' ? '@' : $prefix) . $name;
616 return $name if !$prefix || $name =~ /::/;
617 return $self->{'curstash'}.'::'. $name
618 if
619 $name =~ /^(?!\d)\w/ # alphabetic
620 && $v !~ /^\$[ab]\z/ # not $a or $b
621 && !$globalnames{$name} # not a global name
622 && $self->{hints} & $strict_bits{vars} # strict vars
623 && !$self->lex_in_scope($v,1) # no "our"
624 or $self->lex_in_scope($v); # conflicts with "my" variable
625 return $name;
626 }
627  
628 sub combine($$$)
629 {
630 my ($self, $sep, $items) = @_;
631 # FIXME: loop over $item, testing type.
632 Carp::confess("should be a reference to a arry: is $items") unless
633 ref $items eq 'ARRAY';
634 my @result = ();
635 foreach my $item (@$items) {
636 my $add;
637 if (ref $item) {
638 if (ref $item eq 'ARRAY' and scalar(@$item) == 2) {
639 $add = [$item->[0], $item->[1]];
640 } elsif (eval{$item->isa("B::DeparseTree::Node")}) {
641 $add = [$item->{text}, $item->{addr}];
642 # First item is text and second item is op address.
643 } else {
644 Carp::confess("don't know what to do with $item");
645 }
646 } else {
647 $add = $item;
648 }
649 push @result, $sep if @result && $sep;
650 push @result, $add;
651 }
652 return @result;
653 }
654  
655 use Hash::Util qw[ lock_hash ];
656  
657 # Nonprinting characters with special meaning:
658 my %SPECIAL_SEPARATORS = (
659 '\cS' => 1, # steal parens (see maybe_parens_unop)
660 '\n' => 1, # newline and indent
661 '\b' => 1, # decrease indent ('outdent')
662 '\f' => 1, # flush left (no indent)
663 '\cK' => 1, # kill following semicolon, if any
664  
665 );
666 lock_hash %SPECIAL_SEPARATORS;
667  
668 sub info2str($$)
669 {
670 my ($self, $item) = @_;
671 my $result = '';
672 if (ref $item) {
673 if (ref $item eq 'ARRAY' and scalar(@$item) == 2) {
674 # First item is text and second item is op address.
675 $result = $item->[0];
676 } elsif (eval{$item->isa("B::DeparseTree::Node")}) {
677 $result = $self->combine2str($item->{sep},
678 $item->{texts});
679 } else {
680 Carp::confess("Invalid ref item ref($item)");
681 }
682 } else {
683 # FIXME: add this and remove errors
684 if (index($item, '@B::DeparseTree::Node') > 0) {
685 Carp::confess("\@B::DeparseTree::Node as an item is probably wrong");
686 }
687 $result = $item;
688 }
689 return $result;
690 }
691  
692 sub combine2str($$$)
693 {
694 my ($self, $sep, $items) = @_;
695 my $result = '';
696 foreach my $item (@$items) {
697 if ($result) {
698 my $expanded_sep = $sep;
699 if (exists $SPECIAL_SEPARATORS{$sep}) {
700 # FIXME: handle them
701 $expanded_sep = $sep;
702 }
703 $result .= $expanded_sep;
704 }
705 if (ref $item) {
706 if (ref $item eq 'ARRAY' and scalar(@$item) == 2) {
707 # First item is text and second item is op address.
708 $result .= $self->info2str($item->[0]);
709 } elsif (eval{$item->isa("B::DeparseTree::Node")}) {
710 $result .= $self->combine2str($item->{sep},
711 $item->{texts});
712 } else {
713 Carp::confess("Invalid ref item ref($item)");
714 }
715 } else {
716 # FIXME: add this and remove errors
717 if (index($item, '@B::DeparseTree::Node') > 0) {
718 Carp::confess("\@B::DeparseTree::Node as an item is probably wrong");
719 }
720 $result .= $item;
721 }
722 }
723 return $result;
724 }
725  
726  
727 BEGIN { for (qw[ pushmark ]) {
728 eval "sub OP_\U$_ () { " . opnumber($_) . "}"
729 }}
730  
731 sub main2info
732 {
733 my $self = shift;
734 $self->{'curcv'} = B::main_cv;
735 $self->pessimise(B::main_root, B::main_start);
736 return $self->deparse_root(B::main_root);
737 }
738  
739 # Don't do this for regexen
740 sub unback {
741 my($str) = @_;
742 $str =~ s/\\/\\\\/g;
743 return $str;
744 }
745  
746 # Remove backslashes which precede literal control characters,
747 # to avoid creating ambiguity when we escape the latter.
748 sub re_unback {
749 my($str) = @_;
750  
751 # the insane complexity here is due to the behaviour of "\c\"
752 $str =~ s/(^|[^\\]|\\c\\)(?<!\\c)\\(\\\\)*(?=[[:^print:]])/$1$2/g;
753 return $str;
754 }
755  
756 sub binop
757 {
758 my ($self, $op, $cx, $opname, $prec, $flags) = (@_, 0);
759 my $left = $op->first;
760 my $right = $op->last;
761 my $eq = "";
762 if ($op->flags & OPf_STACKED && $flags & B::Deparse::ASSIGN) {
763 $eq = "=";
764 $prec = 7;
765 }
766 if ($flags & B::Deparse::SWAP_CHILDREN) {
767 ($left, $right) = ($right, $left);
768 }
769 my $lhs = $self->deparse_binop_left($op, $left, $prec);
770 if ($flags & B::Deparse::LIST_CONTEXT
771 && $lhs->{text} !~ /^(my|our|local|)[\@\(]/) {
772 $lhs->{text} = "($lhs->{text})";
773 }
774  
775 my $rhs = $self->deparse_binop_right($op, $right, $prec);
776 my @texts = ($lhs, "$opname$eq", $rhs);
777 return info_from_list($op, $self, \@texts, ' ', "binary operator $opname$eq",
778 {maybe_parens_join => [$self, $cx, $prec]});
779 }
780  
781 sub coderef2info
782 {
783 my ($self, $coderef) = @_;
784 croak "Usage: ->coderef2info(CODEREF)" unless UNIVERSAL::isa($coderef, "CODE");
785 $self->init();
786 return $self->deparse_sub(svref_2object($coderef));
787 }
788  
789 sub coderef2text
790 {
791 my ($self, $func) = @_;
792 croak "Usage: ->coderef2text(CODEREF)" unless UNIVERSAL::isa($func, "CODE");
793  
794 $self->init();
795 my $info = $self->coderef2info($func);
796 return $self->indent($info->{text});
797 }
798  
799 sub const {
800 my $self = shift;
801 my($sv, $cx) = @_;
802 if ($self->{'use_dumper'}) {
803 return $self->const_dumper($sv, $cx);
804 }
805 if (class($sv) eq "SPECIAL") {
806 # sv_undef, sv_yes, sv_no
807 my $text = ('undef', '1', $self->maybe_parens("!1", $cx, 21))[$$sv-1];
808 return info_from_text($sv, $self, $text, 'const_special', {});
809 }
810 if (class($sv) eq "NULL") {
811 return info_from_text($sv, $self, 'undef', 'const_NULL', {});
812 }
813 # convert a version object into the "v1.2.3" string in its V magic
814 if ($sv->FLAGS & SVs_RMG) {
815 for (my $mg = $sv->MAGIC; $mg; $mg = $mg->MOREMAGIC) {
816 if ($mg->TYPE eq 'V') {
817 return info_from_text($sv, $self, $mg->PTR, 'const_magic', {});
818 }
819 }
820 }
821  
822 if ($sv->FLAGS & SVf_IOK) {
823 my $str = $sv->int_value;
824 $str = $self->maybe_parens($str, $cx, 21) if $str < 0;
825 return info_from_text($sv, $self, $str, 'integer constant', {});
826 } elsif ($sv->FLAGS & SVf_NOK) {
827 my $nv = $sv->NV;
828 if ($nv == 0) {
829 if (pack("F", $nv) eq pack("F", 0)) {
830 # positive zero
831 return info_from_text($sv, $self, "0", 'constant float positive 0', {});
832 } else {
833 # negative zero
834 return info_from_text($sv, $self, $self->maybe_parens("-.0", $cx, 21),
835 'constant float negative 0', {});
836 }
837 } elsif (1/$nv == 0) {
838 if ($nv > 0) {
839 # positive infinity
840 return info_from_text($sv, $self, $self->maybe_parens("9**9**9", $cx, 22),
841 'constant float +infinity', {});
842 } else {
843 # negative infinity
844 return info_from_text($sv, $self, $self->maybe_parens("-9**9**9", $cx, 21),
845 'constant float -infinity', {});
846 }
847 } elsif ($nv != $nv) {
848 # NaN
849 if (pack("F", $nv) eq pack("F", sin(9**9**9))) {
850 # the normal kind
851 return info_from_text($sv, $self, "sin(9**9**9)", 'const_Nan', {});
852 } elsif (pack("F", $nv) eq pack("F", -sin(9**9**9))) {
853 # the inverted kind
854 return info_from_text($sv, $self, $self->maybe_parens("-sin(9**9**9)", $cx, 21),
855 'constant float Nan invert', {});
856 } else {
857 # some other kind
858 my $hex = unpack("h*", pack("F", $nv));
859 return info_from_text($sv, $self, qq'unpack("F", pack("h*", "$hex"))',
860 'constant Na na na', {});
861 }
862 }
863 # first, try the default stringification
864 my $str = "$nv";
865 if ($str != $nv) {
866 # failing that, try using more precision
867 $str = sprintf("%.${max_prec}g", $nv);
868 # if (pack("F", $str) ne pack("F", $nv)) {
869 if ($str != $nv) {
870 # not representable in decimal with whatever sprintf()
871 # and atof() Perl is using here.
872 my($mant, $exp) = split_float($nv);
873 return info_from_text($sv, $self, $self->maybe_parens("$mant * 2**$exp", $cx, 19),
874 'constant float not-sprintf/atof-able', {});
875 }
876 }
877 $str = $self->maybe_parens($str, $cx, 21) if $nv < 0;
878 return info_from_text($sv, $self, $str, 'constant nv', {});
879 } elsif ($sv->FLAGS & SVf_ROK && $sv->can("RV")) {
880 my $ref = $sv->RV;
881 if (class($ref) eq "AV") {
882 my $list_info = $self->list_const($sv, 2, $ref->ARRAY);
883 return info_from_list($sv, $self, ['[', $list_info->{text}, ']'], '', 'const_av',
884 {body => [$list_info]});
885 } elsif (class($ref) eq "HV") {
886 my %hash = $ref->ARRAY;
887 my @elts;
888 for my $k (sort keys %hash) {
889 push @elts, "$k => " . $self->const($hash{$k}, 6);
890 }
891 return info_from_list($sv, $self, ["{", join(", ", @elts), "}"], '',
892 'constant hash value', {});
893 } elsif (class($ref) eq "CV") {
894 BEGIN {
895 if ($] > 5.0150051) {
896 require overloading;
897 unimport overloading;
898 }
899 }
900 if ($] > 5.0150051 && $self->{curcv} &&
901 $self->{curcv}->object_2svref == $ref->object_2svref) {
902 return info_from_text($sv, $self, $self->keyword("__SUB__"),
903 'constant sub', {});
904 }
905 my $sub_info = $self->deparse_sub($ref);
906 return info_from_list($sub_info->{op}, $self, ["sub ", $sub_info->{text}], '',
907 'constant sub 2',
908 {body => [$sub_info]});
909 }
910 if ($ref->FLAGS & SVs_SMG) {
911 for (my $mg = $ref->MAGIC; $mg; $mg = $mg->MOREMAGIC) {
912 if ($mg->TYPE eq 'r') {
913 my $re = B::Deparse::re_uninterp(B::Deparse::escape_str(re_unback($mg->precomp)));
914 return $self->single_delim($sv, "qr", "", $re);
915 }
916 }
917 }
918  
919 my $const = $self->const($ref, 20);
920 if ($self->{in_subst_repl} && $const =~ /^[0-9]/) {
921 $const = "($const)";
922 }
923 my @texts = ("\\", $const);
924 return info_from_list($sv, $self, \@texts, '', 'const_rv',
925 {maybe_parens => [$self, $cx, 20]});
926  
927 } elsif ($sv->FLAGS & SVf_POK) {
928 my $str = $sv->PV;
929 if ($str =~ /[[:^print:]]/) {
930 return $self->single_delim($sv, "qq", '"',
931 B::Deparse::uninterp B::Deparse::escape_str B::Deparse::unback $str);
932 } else {
933 return $self->single_delim($sv, "q", "'", unback $str);
934 }
935 } else {
936 return info_from_text($sv, $self, "undef", 'constant undef', {});
937 }
938 }
939  
940 sub const_dumper
941 {
942 my $self = shift;
943 my($sv, $cx) = @_;
944 my $ref = $sv->object_2svref();
945 my $dumper = Data::Dumper->new([$$ref], ['$v']);
946 $dumper->Purity(1)->Terse(1)->Deparse(1)->Indent(0)->Useqq(1)->Sortkeys(1);
947 my $str = $dumper->Dump();
948 if ($str =~ /^\$v/) {
949 return info_from_text($sv, $self, ['${my', $str, '\$v}'], 'const_dumper_my', {});
950 } else {
951 return info_from_text($sv, $self, $str, 'constant dumper', {});
952 }
953 }
954  
955 sub dedup_parens_func($$$)
956 {
957 my $self = shift;
958 my $sub_info = shift;
959 my ($args_ref) = @_;
960 my @args = @$args_ref;
961 if (scalar @args == 1 && substr($args[0], 0, 1) eq '(' &&
962 substr($args[0], -1, 1) eq ')') {
963 return ($sub_info, $self->combine(', ', \@args), );
964 } else {
965 return ($sub_info, '(', $self->combine(', ', \@args), ')', );
966 }
967 }
968  
969 # FIXME: how can we inherit this from B::Deparse?
970 sub null
971 {
972 my $op = shift;
973 return class($op) eq "NULL";
974 }
975  
976 # This is a special case of scopeop and lineseq, for the case of the
977 # main_root.
978 sub deparse_root {
979 my $self = shift;
980 my($op) = @_;
981 local(@$self{qw'curstash warnings hints hinthash'})
982 = @$self{qw'curstash warnings hints hinthash'};
983 my @ops;
984 return if null $op->first; # Can happen, e.g., for Bytecode without -k
985 for (my $kid = $op->first->sibling; !null($kid); $kid = $kid->sibling) {
986 push @ops, $kid;
987 }
988 my $fn = sub {
989 my ($exprs, $i, $info, $parent) = @_;
990 my $text = $info->{text};
991 my $op = $ops[$i];
992 $text =~ s/\f//;
993 $text =~ s/\n$//;
994 $text =~ s/;\n?\z//;
995 $text =~ s/^\((.+)\)$/$1/;
996 $info->{type} = $op->name;
997 $info->{op} = $op;
998 $self->{optree}{$$op} = $info;
999 $info->{text} = $text;
1000 $info->{parent} = $$parent if $parent;
1001 push @$exprs, $info;
1002 };
1003 my $info = $self->walk_lineseq($op, \@ops, $fn);
1004 my @other_ops;
1005 if (exists $info->{other_ops}) {
1006 @other_ops = @{$info->other_ops};
1007 push @other_ops, $op->first;
1008 } else {
1009 @other_ops = ($op->first);
1010 }
1011 $info->{other_ops} = \@other_ops;
1012 return $info;
1013  
1014 }
1015  
1016 sub is_state {
1017 my $name = $_[0]->name;
1018 return $name eq "nextstate" || $name eq "dbstate" || $name eq "setstate";
1019 }
1020  
1021 # Check if the op and its sibling are the initialization and the rest of a
1022 # for (..;..;..) { ... } loop
1023 sub is_for_loop($)
1024 {
1025 my $op = shift;
1026 # This OP might be almost anything, though it won't be a
1027 # nextstate. (It's the initialization, so in the canonical case it
1028 # will be an sassign.) The sibling is (old style) a lineseq whose
1029 # first child is a nextstate and whose second is a leaveloop, or
1030 # (new style) an unstack whose sibling is a leaveloop.
1031 my $lseq = $op->sibling;
1032 return 0 unless !is_state($op) and !null($lseq);
1033 if ($lseq->name eq "lineseq") {
1034 if ($lseq->first && !null($lseq->first) && is_state($lseq->first)
1035 && (my $sib = $lseq->first->sibling)) {
1036 return (!null($sib) && $sib->name eq "leaveloop");
1037 }
1038 } elsif ($lseq->name eq "unstack" && ($lseq->flags & OPf_SPECIAL)) {
1039 my $sib = $lseq->sibling;
1040 return $sib && !null($sib) && $sib->name eq "leaveloop";
1041 }
1042 return 0;
1043 }
1044  
1045 # Create an info structure from a list of strings
1046 # FIXME: $deparse (or rather $self) should be first
1047 sub info_from_list($$$$$$)
1048 {
1049 my ($op, $deparse, $texts, $sep, $type, $opts) = @_;
1050 my $text = '';
1051 my $info = B::DeparseTree::Node->new($op, $deparse, $texts, $sep, $type, $opts);
1052 foreach my $item (@$texts) {
1053 $text .= $sep if $text and $sep;
1054 if(ref($item) eq 'ARRAY'){
1055 $text .= $item->[0];
1056 } elsif (eval{$item->isa("B::DeparseTree::Node")}) {
1057 $text .= $item->{text};
1058 } else {
1059 $text .= $item;
1060 }
1061 }
1062 $info->{text} = $text;
1063 if ($opts->{maybe_parens}) {
1064 my ($self, $cx, $prec) = @{$opts->{maybe_parens}};
1065 $info->{text} = $self->maybe_parens($info->{text}, $cx, $prec);
1066 $info->{maybe_parens} = {context => $cx , precidence => $prec};
1067 }
1068 return $info
1069 }
1070  
1071 # Create an info structure from a single string
1072 # FIXME: $deparse (or rather $self) should be first
1073 sub info_from_text($$$$$)
1074 {
1075 my ($op, $deparse, $text, $type, $opts) = @_;
1076 return info_from_list($op, $deparse, [[$text, $$op]], '', $type, $opts)
1077 }
1078  
1079 sub walk_lineseq
1080 {
1081 my ($self, $op, $kids, $callback) = @_;
1082 my @kids = @$kids;
1083 my @body = ();
1084 my $expr;
1085 for (my $i = 0; $i < @kids; $i++) {
1086 if (is_state $kids[$i]) {
1087 $expr = ($self->deparse($kids[$i], 0, $op));
1088 $callback->(\@body, $i, $expr);
1089 $i++;
1090 if ($i > $#kids) {
1091 last;
1092 }
1093 }
1094 if (is_for_loop($kids[$i])) {
1095 my $loop_expr = $self->for_loop($kids[$i], 0);
1096 $loop_expr =~ s/\cK//;
1097 $callback->(\@body,
1098 $i += $kids[$i]->sibling->name eq "unstack" ? 2 : 1,
1099 $loop_expr);
1100 next;
1101 }
1102 $expr = $self->deparse($kids[$i], (@kids != 1)/2, $op);
1103 $callback->(\@body, $i, $expr, $op);
1104 }
1105  
1106 # Add semicolons between statements. Don't add them to blank lines,
1107 # or to comment lines, which we
1108 # assume will always be the last line in the text and start after a \n.
1109 # FIXME: not quite ideal when adding ';' because we record only the text
1110 # rather than the DeparseTree::Node.
1111 my @texts = map { $_->{text} =~ /(?:\n#)|^\s*$/ ?
1112 $_ : "$_->{text};" } @body;
1113 # $_ : ($_, ";") } @body;
1114 my $info = info_from_list($op, $self, \@texts, "\n", 'line sequence', {});
1115 $self->{optree}{$$op} = $info if $op;
1116 return $info;
1117 }
1118  
1119 # $root should be the op which represents the root of whatever
1120 # we're sequencing here. If it's undefined, then we don't append
1121 # any subroutine declarations to the deparsed ops, otherwise we
1122 # append appropriate declarations.
1123 sub lineseq {
1124 my($self, $root, $cx, @ops) = @_;
1125  
1126 my $out_cop = $self->{'curcop'};
1127 my $out_seq = defined($out_cop) ? $out_cop->cop_seq : undef;
1128 my $limit_seq;
1129 if (defined $root) {
1130 $limit_seq = $out_seq;
1131 my $nseq;
1132 $nseq = $self->find_scope_st($root->sibling) if ${$root->sibling};
1133 $limit_seq = $nseq if !defined($limit_seq)
1134 or defined($nseq) && $nseq < $limit_seq;
1135 }
1136 $limit_seq = $self->{'limit_seq'}
1137 if defined($self->{'limit_seq'})
1138 && (!defined($limit_seq) || $self->{'limit_seq'} < $limit_seq);
1139 local $self->{'limit_seq'} = $limit_seq;
1140  
1141 my $fn = sub {
1142 my ($exprs, $i, $info, $parent) = @_;
1143 my $text = $info->{text};
1144 my $op = $ops[$i];
1145 $text =~ s/\f//;
1146 $text =~ s/\n$//;
1147 $text =~ s/;\n?\z//;
1148 $info->{type} = $op->name;
1149 $info->{op} = $op;
1150 if ($parent) {
1151 Carp::confess("nonref parent, op: $op->name") if !ref($parent);
1152 $info->{parent} = $$parent ;
1153 }
1154 $self->{optree}{$$op} = $info;
1155 $info->{text} = $text;
1156 push @$exprs, $info;
1157 };
1158 return $self->walk_lineseq($root, \@ops, $fn);
1159 }
1160  
1161 sub dquote
1162 {
1163 my($self, $op, $cx) = @_;
1164 my $kid = $op->first->sibling; # skip ex-stringify, pushmark
1165 return $self->deparse($kid, $cx, $op) if $self->{'unquote'};
1166 $self->maybe_targmy($kid, $cx,
1167 sub {$self->single_delim($kid, '"', $self->dq($_[1])->{text})});
1168 }
1169  
1170 sub maybe_targmy
1171 {
1172 my($self, $op, $cx, $func, @args) = @_;
1173 if ($op->private & OPpTARGET_MY) {
1174 my $var = $self->padname($op->targ);
1175 my $val = $func->($self, $op, 7, @args);
1176 my @texts = ($var, '=', $val);
1177 return info_from_list($op, $self, \@texts,
1178 ' ', 'maybe_targmy',
1179 {maybe_parens => [$self, $cx, 7]});
1180 } else {
1181 my $info = $func->($self, $op, $cx, @args);
1182 return $info;
1183 }
1184 }
1185  
1186 sub parens_test($$)
1187 {
1188 my ($cx, $prec) = @_;
1189 return ($prec < $cx
1190 # unary ops nest just fine
1191 or $prec == $cx and $cx != 4 and $cx != 16 and $cx != 21)
1192 }
1193  
1194 # Possibly add () around $text depending on precidence $prec and
1195 # context $cx. We return a string.
1196 sub maybe_parens($$$$)
1197 {
1198 my($self, $text, $cx, $prec) = @_;
1199 if (parens_test($cx, $prec) or $self->{'parens'}) {
1200 $text = "($text)";
1201 # In a unop, let parent reuse our parens; see maybe_parens_unop
1202 $text = "\cS" . $text if $cx == 16;
1203 return $text;
1204 } else {
1205 return $text;
1206 }
1207 }
1208  
1209 sub todo
1210 {
1211 my $self = shift;
1212 my($cv, $is_form, $name) = @_;
1213 my $cvfile = $cv->FILE//'';
1214 return unless ($cvfile eq $0 || exists $self->{files}{$cvfile});
1215 my $seq;
1216 if ($cv->OUTSIDE_SEQ) {
1217 $seq = $cv->OUTSIDE_SEQ;
1218 } elsif (!null($cv->START) and is_state($cv->START)) {
1219 $seq = $cv->START->cop_seq;
1220 } else {
1221 $seq = 0;
1222 }
1223 push @{$self->{'subs_todo'}}, [$seq, $cv, $is_form, $name];
1224 }
1225  
1226 # _pessimise_walk(): recursively walk the optree of a sub,
1227 # possibly undoing optimisations along the way.
1228  
1229 sub _pessimise_walk {
1230 my ($self, $startop) = @_;
1231  
1232 return unless $$startop;
1233 my ($op, $prevop);
1234 for ($op = $startop; $$op; $prevop = $op, $op = $op->sibling) {
1235 my $ppname = $op->name;
1236  
1237 # pessimisations start here
1238  
1239 if ($ppname eq "padrange") {
1240 # remove PADRANGE:
1241 # the original optimisation either (1) changed this:
1242 # pushmark -> (various pad and list and null ops) -> the_rest
1243 # or (2), for the = @_ case, changed this:
1244 # pushmark -> gv[_] -> rv2av -> (pad stuff) -> the_rest
1245 # into this:
1246 # padrange ----------------------------------------> the_rest
1247 # so we just need to convert the padrange back into a
1248 # pushmark, and in case (1), set its op_next to op_sibling,
1249 # which is the head of the original chain of optimised-away
1250 # pad ops, or for (2), set it to sibling->first, which is
1251 # the original gv[_].
1252  
1253 $B::overlay->{$$op} = {
1254 type => OP_PUSHMARK,
1255 name => 'pushmark',
1256 private => ($op->private & OPpLVAL_INTRO),
1257 };
1258 }
1259  
1260 # pessimisations end here
1261  
1262 if (class($op) eq 'PMOP'
1263 && ref($op->pmreplroot)
1264 && ${$op->pmreplroot}
1265 && $op->pmreplroot->isa( 'B::OP' ))
1266 {
1267 $self-> _pessimise_walk($op->pmreplroot);
1268 }
1269  
1270 if ($op->flags & OPf_KIDS) {
1271 $self-> _pessimise_walk($op->first);
1272 }
1273  
1274 }
1275 }
1276  
1277  
1278 # _pessimise_walk_exe(): recursively walk the op_next chain of a sub,
1279 # possibly undoing optimisations along the way.
1280  
1281 sub _pessimise_walk_exe {
1282 my ($self, $startop, $visited) = @_;
1283  
1284 return unless $$startop;
1285 return if $visited->{$$startop};
1286 my ($op, $prevop);
1287 for ($op = $startop; $$op; $prevop = $op, $op = $op->next) {
1288 last if $visited->{$$op};
1289 $visited->{$$op} = 1;
1290 my $ppname = $op->name;
1291 if ($ppname =~
1292 /^((and|d?or)(assign)?|(map|grep)while|range|cond_expr|once)$/
1293 # entertry is also a logop, but its op_other invariably points
1294 # into the same chain as the main execution path, so we skip it
1295 ) {
1296 $self->_pessimise_walk_exe($op->other, $visited);
1297 }
1298 elsif ($ppname eq "subst") {
1299 $self->_pessimise_walk_exe($op->pmreplstart, $visited);
1300 }
1301 elsif ($ppname =~ /^(enter(loop|iter))$/) {
1302 # redoop and nextop will already be covered by the main block
1303 # of the loop
1304 $self->_pessimise_walk_exe($op->lastop, $visited);
1305 }
1306  
1307 # pessimisations start here
1308 }
1309 }
1310  
1311 # Go through an optree and "remove" some optimisations by using an
1312 # overlay to selectively modify or un-null some ops. Deparsing in the
1313 # absence of those optimisations is then easier.
1314 #
1315 # Note that older optimisations are not removed, as Deparse was already
1316 # written to recognise them before the pessimise/overlay system was added.
1317  
1318 sub pessimise {
1319 my ($self, $root, $start) = @_;
1320  
1321 no warnings 'recursion';
1322 # walk tree in root-to-branch order
1323 $self->_pessimise_walk($root);
1324  
1325 my %visited;
1326 # walk tree in execution order
1327 $self->_pessimise_walk_exe($start, \%visited);
1328 }
1329  
1330 sub stash_subs {
1331 my ($self, $pack, $seen) = @_;
1332 my (@ret, $stash);
1333 if (!defined $pack) {
1334 $pack = '';
1335 $stash = \%::;
1336 }
1337 else {
1338 $pack =~ s/(::)?$/::/;
1339 no strict 'refs';
1340 $stash = \%{"main::$pack"};
1341 }
1342 return
1343 if ($seen ||= {})->{
1344 $INC{"overload.pm"} ? overload::StrVal($stash) : $stash
1345 }++;
1346 my %stash = svref_2object($stash)->ARRAY;
1347 while (my ($key, $val) = each %stash) {
1348 my $flags = $val->FLAGS;
1349 if ($flags & SVf_ROK) {
1350 # A reference. Dump this if it is a reference to a CV. If it
1351 # is a constant acting as a proxy for a full subroutine, then
1352 # we may or may not have to dump it. If some form of perl-
1353 # space visible code must have created it, be it a use
1354 # statement, or some direct symbol-table manipulation code that
1355 # we will deparse, then we don’t want to dump it. If it is the
1356 # result of a declaration like sub f () { 42 } then we *do*
1357 # want to dump it. The only way to distinguish these seems
1358 # to be the SVs_PADTMP flag on the constant, which is admit-
1359 # tedly a hack.
1360 my $class = class(my $referent = $val->RV);
1361 if ($class eq "CV") {
1362 $self->todo($referent, 0);
1363 } elsif (
1364 $class !~ /^(AV|HV|CV|FM|IO|SPECIAL)\z/
1365 # A more robust way to write that would be this, but B does
1366 # not provide the SVt_ constants:
1367 # ($referent->FLAGS & B::SVTYPEMASK) < B::SVt_PVAV
1368 and $referent->FLAGS & SVs_PADTMP
1369 ) {
1370 push @{$self->{'protos_todo'}}, [$pack . $key, $val];
1371 }
1372 } elsif ($flags & (SVf_POK|SVf_IOK)) {
1373 # Just a prototype. As an ugly but fairly effective way
1374 # to find out if it belongs here is to see if the AUTOLOAD
1375 # (if any) for the stash was defined in one of our files.
1376 my $A = $stash{"AUTOLOAD"};
1377 if (defined ($A) && class($A) eq "GV" && defined($A->CV)
1378 && class($A->CV) eq "CV") {
1379 my $AF = $A->FILE;
1380 next unless $AF eq $0 || exists $self->{'files'}{$AF};
1381 }
1382 push @{$self->{'protos_todo'}},
1383 [$pack . $key, $flags & SVf_POK ? $val->PV: undef];
1384 } elsif (class($val) eq "GV") {
1385 if (class(my $cv = $val->CV) ne "SPECIAL") {
1386 next if $self->{'subs_done'}{$$val}++;
1387 next if $$val != ${$cv->GV}; # Ignore imposters
1388 $self->todo($cv, 0);
1389 }
1390 if (class(my $cv = $val->FORM) ne "SPECIAL") {
1391 next if $self->{'forms_done'}{$$val}++;
1392 next if $$val != ${$cv->GV}; # Ignore imposters
1393 $self->todo($cv, 1);
1394 }
1395 if (class($val->HV) ne "SPECIAL" && $key =~ /::$/) {
1396 $self->stash_subs($pack . $key, $seen);
1397 }
1398 }
1399 }
1400 }
1401  
1402 sub print_protos {
1403 my $self = shift;
1404 my $ar;
1405 my @ret;
1406 foreach $ar (@{$self->{'protos_todo'}}) {
1407 my $proto = defined $ar->[1]
1408 ? ref $ar->[1]
1409 ? " () {\n " . $self->const($ar->[1]->RV,0) . ";\n}"
1410 : " (". $ar->[1] . ");"
1411 : ";";
1412 push @ret, "sub " . $ar->[0] . "$proto\n";
1413 }
1414 delete $self->{'protos_todo'};
1415 return @ret;
1416 }
1417  
1418 sub style_opts
1419 {
1420 my ($self, $opts) = @_;
1421 my $opt;
1422 while (length($opt = substr($opts, 0, 1))) {
1423 if ($opt eq "C") {
1424 $self->{'cuddle'} = " ";
1425 $opts = substr($opts, 1);
1426 } elsif ($opt eq "i") {
1427 $opts =~ s/^i(\d+)//;
1428 $self->{'indent_size'} = $1;
1429 } elsif ($opt eq "T") {
1430 $self->{'use_tabs'} = 1;
1431 $opts = substr($opts, 1);
1432 } elsif ($opt eq "v") {
1433 $opts =~ s/^v([^.]*)(.|$)//;
1434 $self->{'ex_const'} = $1;
1435 }
1436 }
1437 }
1438  
1439 # This gets called automatically when option:
1440 # -MO="DeparseTree,sC" is added
1441 # Running this prints out the program text.
1442 sub compile {
1443 my(@args) = @_;
1444 return sub {
1445 my $self = B::DeparseTree->new(@args);
1446 # First deparse command-line args
1447 if (defined $^I) { # deparse -i
1448 print q(BEGIN { $^I = ).perlstring($^I).qq(; }\n);
1449 }
1450 if ($^W) { # deparse -w
1451 print qq(BEGIN { \$^W = $^W; }\n);
1452 }
1453 if ($/ ne "\n" or defined $O::savebackslash) { # deparse -l and -0
1454 my $fs = perlstring($/) || 'undef';
1455 my $bs = perlstring($O::savebackslash) || 'undef';
1456 print qq(BEGIN { \$/ = $fs; \$\\ = $bs; }\n);
1457 }
1458 my @BEGINs = B::begin_av->isa("B::AV") ? B::begin_av->ARRAY : ();
1459 my @UNITCHECKs = B::unitcheck_av->isa("B::AV")
1460 ? B::unitcheck_av->ARRAY
1461 : ();
1462 my @CHECKs = B::check_av->isa("B::AV") ? B::check_av->ARRAY : ();
1463 my @INITs = B::init_av->isa("B::AV") ? B::init_av->ARRAY : ();
1464 my @ENDs = B::end_av->isa("B::AV") ? B::end_av->ARRAY : ();
1465 if ($] < 5.020) {
1466 for my $block (@BEGINs, @UNITCHECKs, @CHECKs, @INITs, @ENDs) {
1467 $self->todo($block, 0);
1468 }
1469 } else {
1470 my @names = qw(BEGIN UNITCHECK CHECK INIT END);
1471 my @blocks = (\@BEGINs, \@UNITCHECKs, \@CHECKs, \@INITs, \@ENDs);
1472 while (@names) {
1473 my ($name, $blocks) = (shift @names, shift @blocks);
1474 for my $block (@$blocks) {
1475 $self->todo($block, 0, $name);
1476 }
1477 }
1478 }
1479 $self->stash_subs();
1480 local($SIG{"__DIE__"}) =
1481 sub {
1482 if ($self->{'curcop'}) {
1483 my $cop = $self->{'curcop'};
1484 my($line, $file) = ($cop->line, $cop->file);
1485 print STDERR "While deparsing $file near line $line,\n";
1486 }
1487 use Data::Printer;
1488 my @bt = caller(1);
1489 p @bt;
1490 };
1491 $self->{'curcv'} = main_cv;
1492 $self->{'curcvlex'} = undef;
1493 print $self->print_protos;
1494 @{$self->{'subs_todo'}} =
1495 sort {$a->[0] <=> $b->[0]} @{$self->{'subs_todo'}};
1496 my $root = main_root;
1497 local $B::overlay = {};
1498  
1499 if ($] < 5.021) {
1500 unless (null $root) {
1501 $self->pessimise($root, main_start);
1502 # Print deparsed program
1503 print $self->indent_info($self->deparse_root($root)), "\n";
1504 }
1505 } else {
1506 unless (null $root) {
1507 $self->pad_subs($self->{'curcv'});
1508 # Check for a stub-followed-by-ex-cop, resulting from a program
1509 # consisting solely of sub declarations. For backward-compati-
1510 # bility (and sane output) we don’t want to emit the stub.
1511 # leave
1512 # enter
1513 # stub
1514 # ex-nextstate (or ex-dbstate)
1515 my $kid;
1516 if ( $root->name eq 'leave'
1517 and ($kid = $root->first)->name eq 'enter'
1518 and !null($kid = $kid->sibling) and $kid->name eq 'stub'
1519 and !null($kid = $kid->sibling) and $kid->name eq 'null'
1520 and class($kid) eq 'COP' and null $kid->sibling )
1521 {
1522 # ignore deparsing routine
1523 } else {
1524 $self->pessimise($root, main_start);
1525 # Print deparsed program
1526 my $root_tree = $self->deparse_root($root);
1527 print $self->indent_info($root_tree), "\n";
1528 }
1529 }
1530 }
1531 my @text;
1532 while (scalar(@{$self->{'subs_todo'}})) {
1533 push @text, $self->next_todo->{text};
1534 }
1535 print $self->indent(join("", @text)), "\n" if @text;
1536  
1537 # Print __DATA__ section, if necessary
1538 no strict 'refs';
1539 my $laststash = defined $self->{'curcop'}
1540 ? $self->{'curcop'}->stash->NAME : $self->{'curstash'};
1541 if (defined *{$laststash."::DATA"}{IO}) {
1542 print $self->keyword("package") . " $laststash;\n"
1543 unless $laststash eq $self->{'curstash'};
1544 print $self->keyword("__DATA__") . "\n";
1545 print readline(*{$laststash."::DATA"});
1546 }
1547 }
1548 }
1549  
1550 # This method is the inner loop, so try to keep it simple
1551 sub deparse
1552 {
1553 my($self, $op, $cx, $parent) = @_;
1554  
1555 Carp::confess("Null op in deparse") if !defined($op)
1556 || class($op) eq "NULL";
1557  
1558 eval {
1559 my $meth = "pp_" . $op->name;
1560 };
1561 if ($@) {
1562 return;
1563 }
1564 my $meth = "pp_" . $op->name;
1565 # print "YYY $meth\n";
1566 my $info = $self->$meth($op, $cx);
1567 Carp::confess("nonref return for $meth deparse") if !ref($info);
1568 $info->{parent} = $$parent if $parent;
1569 $info->{cop} = $self->{'curcop'};
1570 my $got_op = $info->{op};
1571 if ($got_op) {
1572 if ($got_op != $op) {
1573 # Do something here?
1574 # printf("XX final op 0x%x is not requested 0x%x\n",
1575 # $$op, $$got_op);
1576 }
1577 } else {
1578 $info->{op} = $op;
1579 }
1580 $self->{optree}{$$op} = $info;
1581 if ($info->{other_ops}) {
1582 foreach my $other (@{$info->{other_ops}}) {
1583 if (!ref $other) {
1584 Carp::confess "Invalid $other";
1585 }
1586 $self->{optree}{$$other} = $info;
1587 }
1588 }
1589 return $info;
1590 }
1591  
1592 # Deparse a subroutine
1593 sub deparse_sub($$$)
1594 {
1595 my ($self, $cv, $parent) = @_;
1596 Carp::confess("NULL in deparse_sub") if !defined($cv) || $cv->isa("B::NULL");
1597 Carp::confess("SPECIAL in deparse_sub") if $cv->isa("B::SPECIAL");
1598 local $self->{'curcop'} = $self->{'curcop'};
1599 my $proto = '';
1600 if ($cv->FLAGS & SVf_POK) {
1601 $proto .= "(". $cv->PV . ") ";
1602 }
1603 if ($cv->CvFLAGS & (CVf_METHOD|CVf_LOCKED|CVf_LVALUE)) {
1604 $proto .= ": ";
1605 $proto .= "lvalue " if $cv->CvFLAGS & CVf_LVALUE;
1606 $proto .= "locked " if $cv->CvFLAGS & CVf_LOCKED;
1607 $proto .= "method " if $cv->CvFLAGS & CVf_METHOD;
1608 }
1609  
1610 local($self->{'curcv'}) = $cv;
1611 local($self->{'curcvlex'});
1612 local(@$self{qw'curstash warnings hints hinthash'})
1613 = @$self{qw'curstash warnings hints hinthash'};
1614  
1615 my $root = $cv->ROOT;
1616 my $body;
1617  
1618 my $info = {};
1619  
1620 local $B::overlay = {};
1621 if (not null $root) {
1622 $self->pessimise($root, $cv->START);
1623 my $lineseq = $root->first;
1624 if ($lineseq->name eq "lineseq") {
1625 my @ops;
1626 for(my $o=$lineseq->first; $$o; $o=$o->sibling) {
1627 push @ops, $o;
1628 }
1629 $body = $self->lineseq($root, 0, @ops);
1630 my $scope_en = $self->find_scope_en($lineseq);
1631 }
1632 else {
1633 $body = $self->deparse($root->first, 0, $root);
1634 }
1635 my @texts = ("{\n\t", $body, "\n\b}");
1636 unshift @texts, $proto if $proto;
1637 $info = info_from_list($root, $self, \@texts, '', 'sub',
1638 {other_ops =>[$lineseq]});
1639 $self->{optree}{$$lineseq} = $info;
1640  
1641 } else {
1642 my $sv = $cv->const_sv;
1643 if ($$sv) {
1644 # uh-oh. inlinable sub... format it differently
1645 my @texts = ("{", $self->const($sv, 0)->{text}, "}");
1646 unshift @texts, $proto if $proto;
1647 $info = info_from_list $sv, $self, \@texts, '', 'sub_const', {};
1648 } else { # XSUB? (or just a declaration)
1649 my @texts = ();
1650 @texts = push @texts, $proto if $proto;
1651 $info = info_from_list $root, $self, \@texts, ' ', 'sub_decl', {};
1652 }
1653 }
1654  
1655 $info->{op} = $root;
1656 $info->{cop} = undef;
1657 $info->{parent} = $parent if $parent;
1658 $self->{optree}{$$root} = $info;
1659 return $info;
1660 }
1661  
1662 sub next_todo
1663 {
1664 my ($self, $parent) = @_;
1665 my $ent = shift @{$self->{'subs_todo'}};
1666 my $cv = $ent->[1];
1667 my $gv = $cv->GV;
1668 my $name = $self->gv_name($gv);
1669 if ($ent->[2]) {
1670 my $info = $self->deparse_format($ent->[1], $cv);
1671 my $texts = ["format $name", "=", $info->{text} + "\n"];
1672 return {
1673 body => [$info],
1674 texts => $texts,
1675 type => 'format_todo',
1676 text => join(" ", @$texts),
1677 };
1678 } else {
1679 $self->{'subs_declared'}{$name} = 1;
1680 if ($name eq "BEGIN") {
1681 my $use_dec = $self->begin_is_use($cv);
1682 if (defined ($use_dec) and $self->{'expand'} < 5) {
1683 if (0 == length($use_dec)) {
1684 info_from_text($cv, $self, '', 'begin_todo', {});
1685 } else {
1686 info_from_text($cv, $self, $use_dec, 'begin_todo_use', {});
1687 }
1688 }
1689 }
1690 my $l = '';
1691 if ($self->{'linenums'}) {
1692 my $line = $gv->LINE;
1693 my $file = $gv->FILE;
1694 $l = "\n# line $line \"$file\"\n";
1695 }
1696 my $p = '';
1697 my @texts = ();
1698 if (class($cv->STASH) ne "SPECIAL") {
1699 my $stash = $cv->STASH->NAME;
1700 if ($stash ne $self->{'curstash'}) {
1701 push @texts, 'package', $stash, ';\n';
1702 $name = "$self->{'curstash'}::$name" unless $name =~ /::/;
1703 $self->{'curstash'} = $stash;
1704 }
1705 $name =~ s/^\Q$stash\E::(?!\z|.*::)//;
1706 push @texts, $name;
1707 }
1708 my $info = $self->deparse_sub($cv, $parent);
1709 push @texts, $info;
1710 return info_from_list($cv, $self, \@texts, ' ', 'sub_todo', {})
1711 }
1712 }
1713  
1714 # Deparse a subroutine by name
1715 sub deparse_subname($$$)
1716 {
1717 my ($self, $funcname, $parent) = @_;
1718 my $cv = svref_2object(\&$funcname);
1719 my $info = $self->deparse_sub($cv, $parent);
1720 return info_from_list($cv, $self, ['sub', $funcname, $info->{text}], ' ',
1721 'deparse_subname', {body=>[$info]})
1722 }
1723  
1724 sub indent_list($$)
1725 {
1726 my ($self, $lines_ref) = @_;
1727 my $leader = "";
1728 my $level = 0;
1729 for my $line (@{$lines_ref}) {
1730 my $cmd = substr($line, 0, 1);
1731 if ($cmd eq "\t" or $cmd eq "\b") {
1732 $level += ($cmd eq "\t" ? 1 : -1) * $self->{'indent_size'};
1733 if ($self->{'use_tabs'}) {
1734 $leader = "\t" x ($level / 8) . " " x ($level % 8);
1735 } else {
1736 $leader = " " x $level;
1737 }
1738 $line = substr($line, 1);
1739 }
1740 if (index($line, "\f") > 0) {
1741 $line =~ s/\f/\n/;
1742 }
1743 if (substr($line, 0, 1) eq "\f") {
1744 $line = substr($line, 1); # no indent
1745 } else {
1746 $line = $leader . $line;
1747 }
1748 $line =~ s/\cK;?//g;
1749 }
1750  
1751 my @lines = grep $_ !~ /^\s*$/, @$lines_ref;
1752 return join("\n", @lines)
1753 }
1754  
1755 sub indent($$)
1756 {
1757 my ($self, $text) = @_;
1758 my @lines = split(/\n/, $text);
1759 return $self->indent_list(\@lines);
1760 }
1761  
1762 # Like indent, but takes an info object and removes leading
1763 # parenthesis.
1764 sub indent_info($$)
1765 {
1766 my ($self, $info) = @_;
1767 my $text = $info->{text};
1768 if ($info->{maybe_parens} and
1769 substr($text, 0, 1) eq '(' and
1770 substr($text, -1) eq ')' ) {
1771 $text = substr($text, 1, length($text) -2)
1772 }
1773 return $self->indent($text);
1774 }
1775  
1776 sub is_lexical_subs {
1777 my (@ops) = shift;
1778 for my $op (@ops) {
1779 return 0 if $op->name !~ /\A(?:introcv|clonecv)\z/;
1780 }
1781 return 1;
1782 }
1783  
1784 sub is_miniwhile { # check for one-line loop ('foo() while $y--')
1785 my $op = shift;
1786 return (!null($op) and null($op->sibling)
1787 and $op->name eq "null" and class($op) eq "UNOP"
1788 and (($op->first->name =~ /^(and|or)$/
1789 and $op->first->first->sibling->name eq "lineseq")
1790 or ($op->first->name eq "lineseq"
1791 and not null $op->first->first->sibling
1792 and $op->first->first->sibling->name eq "unstack")
1793 ));
1794 }
1795  
1796 sub scopeop
1797 {
1798 my($real_block, $self, $op, $cx) = @_;
1799 my $kid;
1800 my @kids;
1801  
1802 local(@$self{qw'curstash warnings hints hinthash'})
1803 = @$self{qw'curstash warnings hints hinthash'} if $real_block;
1804 if ($real_block) {
1805 $kid = $op->first->sibling; # skip enter
1806 if (is_miniwhile($kid)) {
1807 my $top = $kid->first;
1808 my $name = $top->name;
1809 if ($name eq "and") {
1810 $name = $self->keyword("while");
1811 } elsif ($name eq "or") {
1812 $name = $self->keyword("until");
1813 } else { # no conditional -> while 1 or until 0
1814 my $body = $self->deparse($top->first, 1, $top);
1815 return info_from_list $op, $self, [$body, 'while', '1'],
1816 ' ', "$name 1", {};
1817 }
1818 my $cond = $top->first;
1819 my $other_ops = [$cond->sibling];
1820 my $body = $cond->sibling->first; # skip lineseq
1821 my $cond_info = $self->deparse($cond, 1, $top);
1822 my $body_info = $self->deparse($body, 1, $top);
1823 return info_from_list($op, $self,
1824 [$body_info, $name, $cond_info], ' ',
1825 "$name",
1826 {other_ops => $other_ops});
1827 }
1828 } else {
1829 $kid = $op->first;
1830 }
1831 for (; !null($kid); $kid = $kid->sibling) {
1832 push @kids, $kid;
1833 }
1834 if ($cx > 0) {
1835 # inside an expression, (a do {} while for lineseq)
1836 my $body = $self->lineseq($op, 0, @kids);
1837 my @texts = ($body->{text});
1838 my $text;
1839 my $type = 'scope expression';
1840 unless (is_lexical_subs(@kids)) {
1841 $type = 'scope do';
1842 @texts = ('do ', "{\n\t", @texts, "\n\b}");
1843 };
1844 return info_from_list($op, $self, \@texts, '', $type, {});
1845 } else {
1846 my $ls = $self->lineseq($op, $cx, @kids);
1847 return info_from_list($op, $self, [$ls], '', 'scope line sequence', {});
1848 }
1849 }
1850  
1851 # Return just the name, without the prefix. It may be returned as a quoted
1852 # string. The second return value is a boolean indicating that.
1853 sub stash_variable_name {
1854 my($self, $prefix, $gv) = @_;
1855 my $name = $self->gv_name($gv, 1);
1856 $name = $self->maybe_qualify($prefix,$name);
1857 if ($name =~ /^(?:\S|(?!\d)[\ca-\cz]?(?:\w|::)*|\d+)\z/) {
1858 $name =~ s/^([\ca-\cz])/'^' . $B::Deparse::unctrl{$1}/e;
1859 $name =~ /^(\^..|{)/ and $name = "{$name}";
1860 return $name, 0; # not quoted
1861 }
1862 else {
1863 $self->single_delim($gv, "q", "'", $name, $self), 1;
1864 }
1865 }
1866  
1867 sub balanced_delim
1868 {
1869 my($str) = @_;
1870 my @str = split //, $str;
1871 my($ar, $open, $close, $fail, $c, $cnt, $last_bs);
1872 for $ar (['[',']'], ['(',')'], ['<','>'], ['{','}']) {
1873 ($open, $close) = @$ar;
1874 $fail = 0; $cnt = 0; $last_bs = 0;
1875 for $c (@str) {
1876 if ($c eq $open) {
1877 $fail = 1 if $last_bs;
1878 $cnt++;
1879 } elsif ($c eq $close) {
1880 $fail = 1 if $last_bs;
1881 $cnt--;
1882 if ($cnt < 0) {
1883 # qq()() isn't ")("
1884 $fail = 1;
1885 last;
1886 }
1887 }
1888 $last_bs = $c eq '\\';
1889 }
1890 $fail = 1 if $cnt != 0;
1891 return ($open, "$open$str$close") if not $fail;
1892 }
1893 return ("", $str);
1894 }
1895  
1896 sub hint_pragmas {
1897 my ($bits) = @_;
1898 my (@pragmas, @strict);
1899 push @pragmas, "integer" if $bits & 0x1;
1900 for (sort keys %strict_bits) {
1901 push @strict, "'$_'" if $bits & $strict_bits{$_};
1902 }
1903 if (@strict == keys %strict_bits) {
1904 push @pragmas, "strict";
1905 }
1906 elsif (@strict) {
1907 push @pragmas, "strict " . join ', ', @strict;
1908 }
1909 push @pragmas, "bytes" if $bits & 0x8;
1910 return @pragmas;
1911 }
1912  
1913 sub declare_hints
1914 {
1915 my ($self, $from, $to) = @_;
1916 my $use = $to & ~$from;
1917 my $no = $from & ~$to;
1918 my $decls = "";
1919 for my $pragma (hint_pragmas($use)) {
1920 $decls .= $self->keyword("use") . " $pragma;\n";
1921 }
1922 for my $pragma (hint_pragmas($no)) {
1923 $decls .= $self->keyword("no") . " $pragma;\n";
1924 }
1925 return $decls;
1926 }
1927  
1928 # Internal implementation hints that the core sets automatically, so don't need
1929 # (or want) to be passed back to the user
1930 my %ignored_hints = (
1931 'open<' => 1,
1932 'open>' => 1,
1933 ':' => 1,
1934 'strict/refs' => 1,
1935 'strict/subs' => 1,
1936 'strict/vars' => 1,
1937 );
1938  
1939 my %rev_feature;
1940  
1941 sub declare_hinthash {
1942 my ($self, $from, $to, $indent, $hints) = @_;
1943 my $doing_features =
1944 ($hints & $feature::hint_mask) == $feature::hint_mask;
1945 my @decls;
1946 my @features;
1947 my @unfeatures; # bugs?
1948 for my $key (sort keys %$to) {
1949 next if $ignored_hints{$key};
1950 my $is_feature = $key =~ /^feature_/ && $^V ge 5.15.6;
1951 next if $is_feature and not $doing_features;
1952 if (!exists $from->{$key} or $from->{$key} ne $to->{$key}) {
1953 push(@features, $key), next if $is_feature;
1954 push @decls,
1955 qq(\$^H{) . single_delim($self, "q", "'", $key, "'") . qq(} = )
1956 . (
1957 defined $to->{$key}
1958 ? single_delim($self, "q", "'", $to->{$key}, "'")
1959 : 'undef'
1960 )
1961 . qq(;);
1962 }
1963 }
1964 for my $key (sort keys %$from) {
1965 next if $ignored_hints{$key};
1966 my $is_feature = $key =~ /^feature_/ && $^V ge 5.15.6;
1967 next if $is_feature and not $doing_features;
1968 if (!exists $to->{$key}) {
1969 push(@unfeatures, $key), next if $is_feature;
1970 push @decls, qq(delete \$^H{'$key'};);
1971 }
1972 }
1973 my @ret;
1974 if (@features || @unfeatures) {
1975 if (!%rev_feature) { %rev_feature = reverse %feature::feature }
1976 }
1977 if (@features) {
1978 push @ret, $self->keyword("use") . " feature "
1979 . join(", ", map "'$rev_feature{$_}'", @features) . ";\n";
1980 }
1981 if (@unfeatures) {
1982 push @ret, $self->keyword("no") . " feature "
1983 . join(", ", map "'$rev_feature{$_}'", @unfeatures)
1984 . ";\n";
1985 }
1986 @decls and
1987 push @ret,
1988 join("\n" . (" " x $indent), "BEGIN {", @decls) . "\n}\n\cK";
1989 return @ret;
1990 }
1991  
1992 sub _features_from_bundle
1993 {
1994 my ($hints, $hh) = @_;
1995 no warnings 'once';
1996 foreach (@{$feature::feature_bundle{@feature::hint_bundles[$hints >> $feature::hint_shift]}}) {
1997 $hh->{$feature::feature{$_}} = 1;
1998 }
1999 return $hh;
2000 }
2001  
2002 # generate any pragmas, 'package foo' etc needed to synchronise
2003 # with the given cop
2004  
2005 sub pragmata {
2006 my $self = shift;
2007 my($op) = @_;
2008  
2009 my @text;
2010  
2011 my $stash = $op->stashpv;
2012 if ($stash ne $self->{'curstash'}) {
2013 push @text, $self->keyword("package") . " $stash;\n";
2014 $self->{'curstash'} = $stash;
2015 }
2016  
2017 if (OPpCONST_ARYBASE && $self->{'arybase'} != $op->arybase) {
2018 push @text, '$[ = '. $op->arybase .";\n";
2019 $self->{'arybase'} = $op->arybase;
2020 }
2021  
2022 my $warnings = $op->warnings;
2023 my $warning_bits;
2024 if ($warnings->isa("B::SPECIAL") && $$warnings == 4) {
2025 $warning_bits = $warnings::Bits{"all"} & WARN_MASK;
2026 }
2027 elsif ($warnings->isa("B::SPECIAL") && $$warnings == 5) {
2028 $warning_bits = $warnings::NONE;
2029 }
2030 elsif ($warnings->isa("B::SPECIAL")) {
2031 $warning_bits = undef;
2032 }
2033 else {
2034 $warning_bits = $warnings->PV & WARN_MASK;
2035 }
2036  
2037 if (defined ($warning_bits) and
2038 !defined($self->{warnings}) || $self->{'warnings'} ne $warning_bits) {
2039 push @text,
2040 $self->declare_warnings($self->{'warnings'}, $warning_bits);
2041 $self->{'warnings'} = $warning_bits;
2042 }
2043  
2044 my $hints = $] < 5.008009 ? $op->private : $op->hints;
2045 my $old_hints = $self->{'hints'};
2046 if ($self->{'hints'} != $hints) {
2047 push @text, $self->declare_hints($self->{'hints'}, $hints);
2048 $self->{'hints'} = $hints;
2049 }
2050  
2051 my $newhh;
2052 if ($] > 5.009) {
2053 $newhh = $op->hints_hash->HASH;
2054 }
2055  
2056 if ($] >= 5.015006) {
2057 # feature bundle hints
2058 my $from = $old_hints & $feature::hint_mask;
2059 my $to = $ hints & $feature::hint_mask;
2060 if ($from != $to) {
2061 if ($to == $feature::hint_mask) {
2062 if ($self->{'hinthash'}) {
2063 delete $self->{'hinthash'}{$_}
2064 for grep /^feature_/, keys %{$self->{'hinthash'}};
2065 }
2066 else { $self->{'hinthash'} = {} }
2067 $self->{'hinthash'}
2068 = _features_from_bundle($from, $self->{'hinthash'});
2069 }
2070 else {
2071 my $bundle =
2072 $feature::hint_bundles[$to >> $feature::hint_shift];
2073 $bundle =~ s/(\d[13579])\z/$1+1/e; # 5.11 => 5.12
2074 push @text,
2075 $self->keyword("no") . " feature ':all';\n",
2076 $self->keyword("use") . " feature ':$bundle';\n";
2077 }
2078 }
2079 }
2080  
2081 if ($] > 5.009) {
2082 push @text, $self->declare_hinthash(
2083 $self->{'hinthash'}, $newhh,
2084 $self->{indent_size}, $self->{hints},
2085 );
2086 $self->{'hinthash'} = $newhh;
2087 }
2088  
2089 return join("", @text);
2090 }
2091  
2092  
2093 sub declare_warnings
2094 {
2095 my ($self, $from, $to) = @_;
2096 if (($to & WARN_MASK) eq (warnings::bits("all") & WARN_MASK)) {
2097 return $self->keyword("use") . " warnings;\n";
2098 }
2099 elsif (($to & WARN_MASK) eq ("\0"x length($to) & WARN_MASK)) {
2100 return $self->keyword("no") . " warnings;\n";
2101 }
2102 return "BEGIN {\${^WARNING_BITS} = \""
2103 . join("", map { sprintf("\\x%02x", ord $_) } split "", $to)
2104 . "\"}\n\cK";
2105 }
2106  
2107 sub is_scope {
2108 my $op = shift;
2109 return $op->name eq "leave" || $op->name eq "scope"
2110 || $op->name eq "lineseq"
2111 || ($op->name eq "null" && class($op) eq "UNOP"
2112 && (is_scope($op->first) || $op->first->name eq "enter"));
2113 }
2114  
2115 sub indirop
2116 {
2117 my($self, $op, $cx, $name) = @_;
2118 my($expr, @exprs);
2119 my $firstkid = my $kid = $op->first->sibling;
2120 my $indir_info;
2121 my @body = ();
2122 my $type = 'indirop';
2123 my @other_ops = ($op->first);
2124 my @indir = ();
2125  
2126 if ($op->flags & OPf_STACKED) {
2127 push @other_ops, $kid;
2128 my $indir_op = $kid->first; # skip rv2gv
2129 if (is_scope($indir_op)) {
2130 $indir_info = $self->deparse($indir_op, 0, $op);
2131 @indir = $indir_info->{text} eq '' ?
2132 ("{", ';', "}") : ("{", $indir_info->{texts}, "}");
2133  
2134 } elsif ($indir_op->name eq "const" && $indir_op->private & OPpCONST_BARE) {
2135 @indir = ($self->const_sv($indir_op)->PV);
2136 } else {
2137 $indir_info = $self->deparse($indir_op, 24, $op);
2138 @indir = @{$indir_info->{texts}};
2139 }
2140 push @body, $indir_info if $indir_info;
2141 $kid = $kid->sibling;
2142 }
2143 if ($name eq "sort" && $op->private & (OPpSORT_NUMERIC | OPpSORT_INTEGER)) {
2144 $type = 'sort_num_int';
2145 @indir = ($op->private & OPpSORT_DESCEND) ?
2146 ('{', '$b', ' <=> ', '$a', '}' ) : ('{', '$a', ' <=> ', '$b', '}' );
2147 }
2148 elsif ($name eq "sort" && $op->private & OPpSORT_DESCEND) {
2149 $type = 'sort_descend';
2150 @indir = ('{', '$b', ' cmp ', '$a', '}' );
2151 }
2152  
2153 for (; !null($kid); $kid = $kid->sibling) {
2154 my $cx = (!scalar(@indir) &&
2155 $kid == $firstkid && $name eq "sort" &&
2156 $firstkid->name eq "entersub")
2157 ? 16 : 6;
2158 $expr = $self->deparse($kid, $cx, $op);
2159 push @exprs, $expr;
2160 }
2161  
2162 push @body, @exprs;
2163 my $opts = {
2164 body => \@body,
2165 other_ops => \@other_ops
2166 };
2167  
2168 my $name2;
2169 if ($name eq "sort" && $op->private & OPpSORT_REVERSE) {
2170 $type = 'sort_reverse';
2171 $name2 = $self->keyword('reverse') . ' ' . $self->keyword('sort');
2172 } else {
2173 $name2 = $self->keyword($name);
2174 }
2175 my $indir = scalar @indir ? (join('', @indir) . ' ') : '';
2176 if ($name eq "sort" && ($op->private & OPpSORT_INPLACE)) {
2177 my @texts = ($exprs[0], '=', $name2, $indir, $exprs[0]);
2178 return info_from_list $op, $self, \@texts, '', 'sort_inplace', $opts;
2179 }
2180  
2181 my @texts;
2182 my $args = $indir . join(', ', map($_->{text}, @exprs));
2183 if ($indir ne "" && $name eq "sort") {
2184 # We don't want to say "sort(f 1, 2, 3)", since perl -w will
2185 # give bareword warnings in that case. Therefore if context
2186 # requires, we'll put parens around the outside "(sort f 1, 2,
2187 # 3)". Unfortunately, we'll currently think the parens are
2188 # necessary more often that they really are, because we don't
2189 # distinguish which side of an assignment we're on.
2190 if ($cx >= 5) {
2191 @texts = ('(', $name2, $args, ')');
2192 } else {
2193 @texts = ($name2, $args);
2194 }
2195 $type='sort1';
2196 } elsif (!$indir && $name eq "sort"
2197 && !null($op->first->sibling)
2198 && $op->first->sibling->name eq 'entersub' ) {
2199 # We cannot say sort foo(bar), as foo will be interpreted as a
2200 # comparison routine. We have to say sort(...) in that case.
2201 @texts = ($name2, '(', $args, ')');
2202 $type='sort2';
2203 } else {
2204 # indir
2205 if (length $args) {
2206 $type='indirop';
2207 @texts = ($self->maybe_parens_func($name2, $args, $cx, 5))
2208 } else {
2209 $type='indirop_noargs';
2210 @texts = ($name2);
2211 push(@texts, '(', ')') if (7 < $cx);
2212 }
2213 }
2214 return info_from_list($op, $self, \@texts, '', $type, $opts);
2215 }
2216  
2217 sub pp_unstack {
2218 my ($self, $op) = @_;
2219 # see also leaveloop
2220 return info_from_text($op, $self, '', 'unstack', {});
2221 }
2222  
2223 # Logical ops, if/until, &&, and
2224 # The one-line while/until is handled in pp_leave
2225 sub logop
2226 {
2227 my ($self, $op, $cx, $lowop, $lowprec, $highop,
2228 $highprec, $blockname) = @_;
2229 my $left = $op->first;
2230 my $right = $op->first->sibling;
2231 my ($lhs, $rhs, $texts, $text);
2232 my $type;
2233 my $sep;
2234 my $opts = {};
2235 if ($cx < 1 and is_scope($right) and $blockname
2236 and $self->{'expand'} < 7) {
2237 # if ($a) {$b}
2238 $lhs = $self->deparse($left, 1, $op);
2239 $rhs = $self->deparse($right, 0, $op);
2240 $sep = '';
2241 $texts = [$blockname, ' (', $lhs->{text}, ') ',
2242 "{\n\t", $rhs->{text}, "\n\b}\cK"];
2243 } elsif ($cx < 1 and $blockname and not $self->{'parens'}
2244 and $self->{'expand'} < 7) { # $b if $a
2245 $lhs = $self->deparse($left, 1, $op);
2246 $rhs = $self->deparse($right, 1, $op);
2247 $texts = [$rhs->{text}, $blockname, $lhs->{text}];
2248 $sep = ' ';
2249 } elsif ($cx > $lowprec and $highop) {
2250 # $a && $b
2251 $lhs = $self->deparse_binop_left($op, $left, $highprec);
2252 $rhs = $self->deparse_binop_right($op, $right, $highprec);
2253 $texts = [$lhs->{text}, $highop, $rhs->{text}];
2254 $sep = ' ';
2255 $opts = {maybe_parens => [$self, $cx, $highprec]};
2256 } else {
2257 # $a and $b
2258 $lhs = $self->deparse_binop_left($op, $left, $lowprec);
2259 $rhs = $self->deparse_binop_right($op, $right, $lowprec);
2260 $texts = [$lhs->{text}, $lowop, $rhs->{text}];
2261 $sep = ' ';
2262 $opts = {maybe_parens => [$self, $cx, $lowprec]};
2263 }
2264 $opts->{block} = [$lhs, $rhs];
2265 return info_from_list($op, $self, $texts, $sep, $type, $opts);
2266 }
2267  
2268 sub baseop
2269 {
2270 my($self, $op, $cx, $name) = @_;
2271 return info_from_text($op, $self, $self->keyword($name), 'baseop', {});
2272 }
2273  
2274 sub POSTFIX () { 1 }
2275  
2276 # This is the category of symbolic prefix and postfix unary operators,
2277 # e.g $x++, -r, +$x.
2278 sub pfixop
2279 {
2280 my $self = shift;
2281 my($op, $cx, $operator, $prec, $flags) = (@_, 0);
2282 my $operand = $self->deparse($op->first, $prec, $op);
2283 my $type;
2284 my @texts;
2285 if ($flags & POSTFIX) {
2286 @texts = ($operand, $operator);
2287 $type = 'prefix_op';
2288 } elsif ($operator eq '-' && $operand->{text} =~ /^[a-zA-Z](?!\w)/) {
2289 # avoid confusion with filetests
2290 $type = 'prefix_filetest';
2291 @texts = ($operand, '(', $operator, ')');
2292 } else {
2293 $type = 'postfix_op';
2294 @texts = ($operator, $operand);
2295 }
2296  
2297 return info_from_list $op, $self, \@texts, '', $type,
2298 {maybe_parens => [$self, $cx, $prec]} ;
2299 }
2300  
2301 sub mapop
2302 {
2303 my($self, $op, $cx, $name) = @_;
2304 my $kid = $op->first; # this is the (map|grep)start
2305  
2306 my @other_ops = ($kid, $kid->first);
2307 $kid = $kid->first->sibling; # skip a pushmark
2308  
2309 my $code = $kid->first; # skip a null
2310  
2311 my $code_info;
2312  
2313 my @block_texts = ();
2314 my @exprs_texts = ();
2315 if (is_scope $code) {
2316 $code_info = $self->deparse($code, 0, $op);
2317 (my $text = $code_info->{text})=~ s/^\n//; # remove first \n in block.
2318 @block_texts = ('{', $text, '}');
2319 } else {
2320 $code_info = $self->deparse($code, 24, $op);
2321 @exprs_texts = ($code_info->{text});
2322 }
2323 my @body = ($code_info);
2324  
2325 push @other_ops, $kid;
2326 $kid = $kid->sibling;
2327 my($expr, @exprs);
2328 for (; !null($kid); $kid = $kid->sibling) {
2329 $expr = $self->deparse($kid, 6, $op);
2330 push @exprs, $expr if defined $expr;
2331 }
2332 push @body, @exprs;
2333 push @exprs_texts, map $_->{text}, @exprs;
2334 my $opts = {
2335 body => \@body,
2336 other_ops => \@other_ops,
2337 };
2338 my $params = join(', ', @exprs_texts);
2339 $params = join(" ", @block_texts) . ' ' . $params if @block_texts;
2340 my @texts = $self->maybe_parens_func($name, $params, $cx, 5);
2341 return info_from_list $op, $self, \@texts, '', 'mapop', $opts;
2342 }
2343  
2344  
2345 sub seq_subs {
2346 my ($self, $seq) = @_;
2347 my @text;
2348 # push @text, "# ($seq)\n";
2349  
2350 return "" if !defined $seq;
2351 my $sep = "\n\nsub ";
2352 my @pending;
2353 while (scalar(@{$self->{'subs_todo'}})
2354 and $seq > $self->{'subs_todo'}[0][0]) {
2355 my $cv = $self->{'subs_todo'}[0][1];
2356 # Skip the OUTSIDE check for lexical subs. We may be deparsing a
2357 # cloned anon sub with lexical subs declared in it, in which case
2358 # the OUTSIDE pointer points to the anon protosub.
2359 my $lexical = ref $self->{'subs_todo'}[0][3];
2360 my $outside = !$lexical && $cv && $cv->OUTSIDE;
2361 if (!$lexical and $cv
2362 and ${$cv->OUTSIDE || \0} != ${$self->{'curcv'}})
2363 {
2364 push @pending, shift @{$self->{'subs_todo'}};
2365 next;
2366 }
2367 push @text, $sep if @text;
2368 push @text, $self->next_todo;
2369 }
2370 return @text;
2371 }
2372  
2373 sub single_delim($$$$$) {
2374 my($self, $op, $q, $default, $str) = @_;
2375  
2376 if (!defined($str)) {
2377 # FIXME: this is a workaround.
2378 $str = '"';
2379 }
2380 return info_from_list($op, $self, [$default, $str, $default], '',
2381 "single delimiter default $default", {})
2382 if $default and index($str, $default) == -1;
2383 if ($q ne 'qr') {
2384 (my $succeed, $str) = balanced_delim($str);
2385 return info_from_list($op, $self, [$q, $str], '', "single delimiter $q", {}) if $succeed;
2386 }
2387 for my $delim ('/', '"', '#') {
2388 return info_from_list($op, $self, [$q, $delim, $str,
2389 $delim], '', "single delimiter qr $delim", {})
2390 if index($str, $delim) == -1;
2391 }
2392 if ($default) {
2393 $str =~ s/$default/\\$default/g;
2394 return info_from_list($op, $self, [$default, $str, $default], '',
2395 "single delimiter qr escape $default", {});
2396 } else {
2397 $str =~ s[/][\\/]g;
2398 return info_from_list($op, $self, [$q, '/', $str, '/'], '',
2399 "single delimiter qr /", {});
2400 }
2401 }
2402  
2403 sub unop
2404 {
2405 my($self, $op, $cx, $name, $nollafr) = @_;
2406 my $kid;
2407 if ($op->flags & OPf_KIDS) {
2408 $kid = $op->first;
2409 if (not $name) {
2410 # this deals with 'boolkeys' right now
2411 return $self->deparse($kid, $cx, $op);
2412 }
2413 my $builtinname = $name;
2414 $builtinname =~ /^CORE::/ or $builtinname = "CORE::$name";
2415 if (defined prototype($builtinname)
2416 && $builtinname ne 'CORE::readline'
2417 && prototype($builtinname) =~ /^;?\*/
2418 && $kid->name eq "rv2gv") {
2419 $kid = $kid->first;
2420 }
2421  
2422 if ($nollafr) {
2423 $kid = $self->deparse($kid, 16, $op);
2424 ($kid->{text}) =~ s/^\cS//;
2425 my $opts = {
2426 body => [$kid],
2427 maybe_parens => [$self, $cx, 16],
2428 };
2429 return info_from_list($op, $self, [($self->keyword($name), $kid->{text})],
2430 ' ', 'unary operator noallafr', $opts);
2431 }
2432 return $self->maybe_parens_unop($name, $kid, $cx, $op);
2433 } else {
2434 my $opts = {maybe_parens => [$self, $cx, 16]};
2435 my @texts = ($self->keyword($name));
2436 push @texts, '()' if $op->flags & OPf_SPECIAL;
2437 return info_from_list($op, $self, \@texts, '', 'unary operator', $opts);
2438 }
2439 }
2440  
2441 # Demo code
2442 unless(caller) {
2443 my @texts = ('a', 'b', 'c');
2444 my $info; # = info_from_list('op', 'deparse',\@texts, ', ', 'test', {});
2445 use Data::Printer;
2446 # p $info;
2447 @texts = (['a', 1], ['b', 2], 'c');
2448 $info = info_from_list('op', 'deparse',\@texts, ', ', 'test', {});
2449 p $info;
2450 }
2451  
2452  
2453 1;