/
Deparse.pm
5762 lines (5210 loc) · 167 KB
/
Deparse.pm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# B::Deparse.pm
# Copyright (c) 1998-2000, 2002, 2003, 2004, 2005, 2006 Stephen McCamant.
# All rights reserved.
# This module is free software; you can redistribute and/or modify
# it under the same terms as Perl itself.
# This is based on the module of the same name by Malcolm Beattie,
# but essentially none of his code remains.
package B::Deparse;
use Carp;
use B qw(class main_root main_start main_cv svref_2object opnumber perlstring
OPf_WANT OPf_WANT_VOID OPf_WANT_SCALAR OPf_WANT_LIST
OPf_KIDS OPf_REF OPf_STACKED OPf_SPECIAL OPf_MOD OPf_PARENS
OPpLVAL_INTRO OPpOUR_INTRO OPpENTERSUB_AMPER OPpSLICE OPpCONST_BARE
OPpTRANS_SQUASH OPpTRANS_DELETE OPpTRANS_COMPLEMENT OPpTARGET_MY
OPpEXISTS_SUB OPpSORT_NUMERIC OPpSORT_INTEGER OPpREPEAT_DOLIST
OPpSORT_REVERSE
SVf_IOK SVf_NOK SVf_ROK SVf_POK SVpad_OUR SVf_FAKE SVs_RMG SVs_SMG
SVpad_TYPED
CVf_METHOD CVf_LVALUE
PMf_KEEP PMf_GLOBAL PMf_CONTINUE PMf_EVAL PMf_ONCE
PMf_MULTILINE PMf_SINGLELINE PMf_FOLD PMf_EXTENDED PMf_EXTENDED_MORE);
$VERSION = '1.30';
use strict;
use vars qw/$AUTOLOAD/;
use warnings ();
require feature;
BEGIN {
# List version-specific constants here.
# Easiest way to keep this code portable between version looks to
# be to fake up a dummy constant that will never actually be true.
foreach (qw(OPpSORT_INPLACE OPpSORT_DESCEND OPpITER_REVERSED OPpCONST_NOVER
OPpPAD_STATE PMf_SKIPWHITE RXf_SKIPWHITE
RXf_PMf_CHARSET RXf_PMf_KEEPCOPY
CVf_LOCKED OPpREVERSE_INPLACE OPpSUBSTR_REPL_FIRST
PMf_NONDESTRUCT OPpCONST_ARYBASE OPpEVAL_BYTES
OPpLVREF_TYPE OPpLVREF_SV OPpLVREF_AV OPpLVREF_HV
OPpLVREF_CV OPpLVREF_ELEM SVpad_STATE)) {
eval { import B $_ };
no strict 'refs';
*{$_} = sub () {0} unless *{$_}{CODE};
}
}
# Changes between 0.50 and 0.51:
# - fixed nulled leave with live enter in sort { }
# - fixed reference constants (\"str")
# - handle empty programs gracefully
# - handle infinite loops (for (;;) {}, while (1) {})
# - differentiate between 'for my $x ...' and 'my $x; for $x ...'
# - various minor cleanups
# - moved globals into an object
# - added '-u', like B::C
# - package declarations using cop_stash
# - subs, formats and code sorted by cop_seq
# Changes between 0.51 and 0.52:
# - added pp_threadsv (special variables under USE_5005THREADS)
# - added documentation
# Changes between 0.52 and 0.53:
# - many changes adding precedence contexts and associativity
# - added '-p' and '-s' output style options
# - various other minor fixes
# Changes between 0.53 and 0.54:
# - added support for new 'for (1..100)' optimization,
# thanks to Gisle Aas
# Changes between 0.54 and 0.55:
# - added support for new qr// construct
# - added support for new pp_regcreset OP
# Changes between 0.55 and 0.56:
# - tested on base/*.t, cmd/*.t, comp/*.t, io/*.t
# - fixed $# on non-lexicals broken in last big rewrite
# - added temporary fix for change in opcode of OP_STRINGIFY
# - fixed problem in 0.54's for() patch in 'for (@ary)'
# - fixed precedence in conditional of ?:
# - tweaked list paren elimination in 'my($x) = @_'
# - made continue-block detection trickier wrt. null ops
# - fixed various prototype problems in pp_entersub
# - added support for sub prototypes that never get GVs
# - added unquoting for special filehandle first arg in truncate
# - print doubled rv2gv (a bug) as '*{*GV}' instead of illegal '**GV'
# - added semicolons at the ends of blocks
# - added -l '#line' declaration option -- fixes cmd/subval.t 27,28
# Changes between 0.56 and 0.561:
# - fixed multiply-declared my var in pp_truncate (thanks to Sarathy)
# - used new B.pm symbolic constants (done by Nick Ing-Simmons)
# Changes between 0.561 and 0.57:
# - stylistic changes to symbolic constant stuff
# - handled scope in s///e replacement code
# - added unquote option for expanding "" into concats, etc.
# - split method and proto parts of pp_entersub into separate functions
# - various minor cleanups
# Changes after 0.57:
# - added parens in \&foo (patch by Albert Dvornik)
# Changes between 0.57 and 0.58:
# - fixed '0' statements that weren't being printed
# - added methods for use from other programs
# (based on patches from James Duncan and Hugo van der Sanden)
# - added -si and -sT to control indenting (also based on a patch from Hugo)
# - added -sv to print something else instead of '???'
# - preliminary version of utf8 tr/// handling
# Changes after 0.58:
# - uses of $op->ppaddr changed to new $op->name (done by Sarathy)
# - added support for Hugo's new OP_SETSTATE (like nextstate)
# Changes between 0.58 and 0.59
# - added support for Chip's OP_METHOD_NAMED
# - added support for Ilya's OPpTARGET_MY optimization
# - elided arrows before '()' subscripts when possible
# Changes between 0.59 and 0.60
# - support for method attributes was added
# - some warnings fixed
# - separate recognition of constant subs
# - rewrote continue block handling, now recognizing for loops
# - added more control of expanding control structures
# Changes between 0.60 and 0.61 (mostly by Robin Houston)
# - many bug-fixes
# - support for pragmas and 'use'
# - support for the little-used $[ variable
# - support for __DATA__ sections
# - UTF8 support
# - BEGIN, CHECK, INIT and END blocks
# - scoping of subroutine declarations fixed
# - compile-time output from the input program can be suppressed, so that the
# output is just the deparsed code. (a change to O.pm in fact)
# - our() declarations
# - *all* the known bugs are now listed in the BUGS section
# - comprehensive test mechanism (TEST -deparse)
# Changes between 0.62 and 0.63 (mostly by Rafael Garcia-Suarez)
# - bug-fixes
# - new switch -P
# - support for command-line switches (-l, -0, etc.)
# Changes between 0.63 and 0.64
# - support for //, CHECK blocks, and assertions
# - improved handling of foreach loops and lexicals
# - option to use Data::Dumper for constants
# - more bug fixes
# - discovered lots more bugs not yet fixed
#
# ...
#
# Changes between 0.72 and 0.73
# - support new switch constructs
# Todo:
# (See also BUGS section at the end of this file)
#
# - finish tr/// changes
# - add option for even more parens (generalize \&foo change)
# - left/right context
# - copy comments (look at real text with $^P?)
# - avoid semis in one-statement blocks
# - associativity of &&=, ||=, ?:
# - ',' => '=>' (auto-unquote?)
# - break long lines ("\r" as discretionary break?)
# - configurable syntax highlighting: ANSI color, HTML, TeX, etc.
# - more style options: brace style, hex vs. octal, quotes, ...
# - print big ints as hex/octal instead of decimal (heuristic?)
# - handle 'my $x if 0'?
# - version using op_next instead of op_first/sibling?
# - avoid string copies (pass arrays, one big join?)
# - here-docs?
# Current test.deparse failures
# comp/hints 6 - location of BEGIN blocks wrt. block openings
# run/switchI 1 - missing -I switches entirely
# perl -Ifoo -e 'print @INC'
# op/caller 2 - warning mask propagates backwards before warnings::register
# 'use warnings; BEGIN {${^WARNING_BITS} eq "U"x12;} use warnings::register'
# op/getpid 2 - can't assign to shared my() declaration (threads only)
# 'my $x : shared = 5'
# op/override 7 - parens on overridden require change v-string interpretation
# 'BEGIN{*CORE::GLOBAL::require=sub {}} require v5.6'
# c.f. 'BEGIN { *f = sub {0} }; f 2'
# op/pat 774 - losing Unicode-ness of Latin1-only strings
# 'use charnames ":short"; $x="\N{latin:a with acute}"'
# op/recurse 12 - missing parens on recursive call makes it look like method
# 'sub f { f($x) }'
# op/subst 90 - inconsistent handling of utf8 under "use utf8"
# op/taint 29 - "use re 'taint'" deparsed in the wrong place wrt. block open
# op/tiehandle compile - "use strict" deparsed in the wrong place
# uni/tr_ several
# ext/B/t/xref 11 - line numbers when we add newlines to one-line subs
# ext/Data/Dumper/t/dumper compile
# ext/DB_file/several
# ext/Encode/several
# ext/Ernno/Errno warnings
# ext/IO/lib/IO/t/io_sel 23
# ext/PerlIO/t/encoding compile
# ext/POSIX/t/posix 6
# ext/Socket/Socket 8
# ext/Storable/t/croak compile
# lib/Attribute/Handlers/t/multi compile
# lib/bignum/ several
# lib/charnames 35
# lib/constant 32
# lib/English 40
# lib/ExtUtils/t/bytes 4
# lib/File/DosGlob compile
# lib/Filter/Simple/t/data 1
# lib/Math/BigInt/t/constant 1
# lib/Net/t/config Deparse-warning
# lib/overload compile
# lib/Switch/ several
# lib/Symbol 4
# lib/Test/Simple several
# lib/Term/Complete
# lib/Tie/File/t/29_downcopy 5
# lib/vars 22
# Object fields (were globals):
#
# avoid_local:
# (local($a), local($b)) and local($a, $b) have the same internal
# representation but the short form looks better. We notice we can
# use a large-scale local when checking the list, but need to prevent
# individual locals too. This hash holds the addresses of OPs that
# have already had their local-ness accounted for. The same thing
# is done with my().
#
# curcv:
# CV for current sub (or main program) being deparsed
#
# curcvlex:
# Cached hash of lexical variables for curcv: keys are
# names prefixed with "m" or "o" (representing my/our), and
# each value is an array with two elements indicating the cop_seq
# of scopes in which a var of that name is valid and a third ele-
# ment referencing the pad name.
#
# curcop:
# COP for statement being deparsed
#
# curstash:
# name of the current package for deparsed code
#
# subs_todo:
# array of [cop_seq, CV, is_format?] for subs and formats we still
# want to deparse
#
# protos_todo:
# as above, but [name, prototype] for subs that never got a GV
#
# subs_done, forms_done:
# keys are addresses of GVs for subs and formats we've already
# deparsed (or at least put into subs_todo)
#
# subs_declared
# keys are names of subs for which we've printed declarations.
# That means we can omit parentheses from the arguments. It also means we
# need to put CORE:: on core functions of the same name.
#
# subs_deparsed
# Keeps track of fully qualified names of all deparsed subs.
#
# in_subst_repl
# True when deparsing the replacement part of a substitution.
#
# in_refgen
# True when deparsing the argument to \.
#
# parens: -p
# linenums: -l
# unquote: -q
# cuddle: ' ' or '\n', depending on -sC
# indent_size: -si
# use_tabs: -sT
# ex_const: -sv
# A little explanation of how precedence contexts and associativity
# work:
#
# deparse() calls each per-op subroutine with an argument $cx (short
# for context, but not the same as the cx* in the perl core), which is
# a number describing the op's parents in terms of precedence, whether
# they're inside an expression or at statement level, etc. (see
# chart below). When ops with children call deparse on them, they pass
# along their precedence. Fractional values are used to implement
# associativity ('($x + $y) + $z' => '$x + $y + $y') and related
# parentheses hacks. The major disadvantage of this scheme is that
# it doesn't know about right sides and left sides, so say if you
# assign a listop to a variable, it can't tell it's allowed to leave
# the parens off the listop.
# Precedences:
# 26 [TODO] inside interpolation context ("")
# 25 left terms and list operators (leftward)
# 24 left ->
# 23 nonassoc ++ --
# 22 right **
# 21 right ! ~ \ and unary + and -
# 20 left =~ !~
# 19 left * / % x
# 18 left + - .
# 17 left << >>
# 16 nonassoc named unary operators
# 15 nonassoc < > <= >= lt gt le ge
# 14 nonassoc == != <=> eq ne cmp
# 13 left &
# 12 left | ^
# 11 left &&
# 10 left ||
# 9 nonassoc .. ...
# 8 right ?:
# 7 right = += -= *= etc.
# 6 left , =>
# 5 nonassoc list operators (rightward)
# 4 right not
# 3 left and
# 2 left or xor
# 1 statement modifiers
# 0.5 statements, but still print scopes as do { ... }
# 0 statement level
# -1 format body
# Nonprinting characters with special meaning:
# \cS - steal parens (see maybe_parens_unop)
# \n - newline and indent
# \t - increase indent
# \b - decrease indent ('outdent')
# \f - flush left (no indent)
# \cK - kill following semicolon, if any
BEGIN { for (qw[ const stringify rv2sv list glob pushmark null aelem
custom ]) {
eval "sub OP_\U$_ () { " . opnumber($_) . "}"
}}
# _pessimise_walk(): recursively walk the optree of a sub,
# possibly undoing optimisations along the way.
sub _pessimise_walk {
my ($self, $startop) = @_;
return unless $$startop;
my ($op, $prevop);
for ($op = $startop; $$op; $prevop = $op, $op = $op->sibling) {
my $ppname = $op->name;
# pessimisations start here
if ($ppname eq "padrange") {
# remove PADRANGE:
# the original optimisation either (1) changed this:
# pushmark -> (various pad and list and null ops) -> the_rest
# or (2), for the = @_ case, changed this:
# pushmark -> gv[_] -> rv2av -> (pad stuff) -> the_rest
# into this:
# padrange ----------------------------------------> the_rest
# so we just need to convert the padrange back into a
# pushmark, and in case (1), set its op_next to op_sibling,
# which is the head of the original chain of optimised-away
# pad ops, or for (2), set it to sibling->first, which is
# the original gv[_].
$B::overlay->{$$op} = {
type => OP_PUSHMARK,
name => 'pushmark',
private => ($op->private & OPpLVAL_INTRO),
};
}
# pessimisations end here
if (class($op) eq 'PMOP'
&& ref($op->pmreplroot)
&& ${$op->pmreplroot}
&& $op->pmreplroot->isa( 'B::OP' ))
{
$self-> _pessimise_walk($op->pmreplroot);
}
if ($op->flags & OPf_KIDS) {
$self-> _pessimise_walk($op->first);
}
}
}
# _pessimise_walk_exe(): recursively walk the op_next chain of a sub,
# possibly undoing optimisations along the way.
sub _pessimise_walk_exe {
my ($self, $startop, $visited) = @_;
return unless $$startop;
return if $visited->{$$startop};
my ($op, $prevop);
for ($op = $startop; $$op; $prevop = $op, $op = $op->next) {
last if $visited->{$$op};
$visited->{$$op} = 1;
my $ppname = $op->name;
if ($ppname =~
/^((and|d?or)(assign)?|(map|grep)while|range|cond_expr|once)$/
# entertry is also a logop, but its op_other invariably points
# into the same chain as the main execution path, so we skip it
) {
$self->_pessimise_walk_exe($op->other, $visited);
}
elsif ($ppname eq "subst") {
$self->_pessimise_walk_exe($op->pmreplstart, $visited);
}
elsif ($ppname =~ /^(enter(loop|iter))$/) {
# redoop and nextop will already be covered by the main block
# of the loop
$self->_pessimise_walk_exe($op->lastop, $visited);
}
# pessimisations start here
}
}
# Go through an optree and "remove" some optimisations by using an
# overlay to selectively modify or un-null some ops. Deparsing in the
# absence of those optimisations is then easier.
#
# Note that older optimisations are not removed, as Deparse was already
# written to recognise them before the pessimise/overlay system was added.
sub pessimise {
my ($self, $root, $start) = @_;
# walk tree in root-to-branch order
$self->_pessimise_walk($root);
my %visited;
# walk tree in execution order
$self->_pessimise_walk_exe($start, \%visited);
}
sub null {
my $op = shift;
return class($op) eq "NULL";
}
sub todo {
my $self = shift;
my($cv, $is_form) = @_;
return unless ($cv->FILE eq $0 || exists $self->{files}{$cv->FILE});
my $seq;
if ($cv->OUTSIDE_SEQ) {
$seq = $cv->OUTSIDE_SEQ;
} elsif (!null($cv->START) and is_state($cv->START)) {
$seq = $cv->START->cop_seq;
} else {
$seq = 0;
}
push @{$self->{'subs_todo'}}, [$seq, $cv, $is_form];
unless ($is_form || class($cv->STASH) eq 'SPECIAL') {
$self->{'subs_deparsed'}{$cv->STASH->NAME."::".$cv->GV->NAME} = 1;
}
}
sub next_todo {
my $self = shift;
my $ent = shift @{$self->{'subs_todo'}};
my $cv = $ent->[1];
my $gv = $cv->GV;
my $name = $self->gv_name($gv);
if ($ent->[2]) {
return $self->keyword("format") . " $name =\n"
. $self->deparse_format($ent->[1]). "\n";
} else {
$self->{'subs_declared'}{$name} = 1;
if ($name eq "BEGIN") {
my $use_dec = $self->begin_is_use($cv);
if (defined ($use_dec) and $self->{'expand'} < 5) {
return () if 0 == length($use_dec);
$use_dec =~ s/^(use|no)\b/$self->keyword($1)/e;
return $use_dec;
}
}
my $l = '';
if ($self->{'linenums'}) {
my $line = $gv->LINE;
my $file = $gv->FILE;
$l = "\n\f#line $line \"$file\"\n";
}
my $p = '';
if (class($cv->STASH) ne "SPECIAL") {
my $stash = $cv->STASH->NAME;
if ($stash ne $self->{'curstash'}) {
$p = $self->keyword("package") . " $stash;\n";
$name = "$self->{'curstash'}::$name" unless $name =~ /::/;
$self->{'curstash'} = $stash;
}
$name =~ s/^\Q$stash\E::(?!\z|.*::)//;
}
return "${p}${l}" . $self->keyword("sub") . " $name "
. $self->deparse_sub($cv);
}
}
# Return a "use" declaration for this BEGIN block, if appropriate
sub begin_is_use {
my ($self, $cv) = @_;
my $root = $cv->ROOT;
local @$self{qw'curcv curcvlex'} = ($cv);
local $B::overlay = {};
$self->pessimise($root, $cv->START);
#require B::Debug;
#B::walkoptree($cv->ROOT, "debug");
my $lineseq = $root->first;
return if $lineseq->name ne "lineseq";
my $req_op = $lineseq->first->sibling;
return if $req_op->name ne "require";
my $module;
if ($req_op->first->private & OPpCONST_BARE) {
# Actually it should always be a bareword
$module = $self->const_sv($req_op->first)->PV;
$module =~ s[/][::]g;
$module =~ s/.pm$//;
}
else {
$module = $self->const($self->const_sv($req_op->first), 6);
}
my $version;
my $version_op = $req_op->sibling;
return if class($version_op) eq "NULL";
if ($version_op->name eq "lineseq") {
# We have a version parameter; skip nextstate & pushmark
my $constop = $version_op->first->next->next;
return unless $self->const_sv($constop)->PV eq $module;
$constop = $constop->sibling;
$version = $self->const_sv($constop);
if (class($version) eq "IV") {
$version = $version->int_value;
} elsif (class($version) eq "NV") {
$version = $version->NV;
} elsif (class($version) ne "PVMG") {
# Includes PVIV and PVNV
$version = $version->PV;
} else {
# version specified as a v-string
$version = 'v'.join '.', map ord, split //, $version->PV;
}
$constop = $constop->sibling;
return if $constop->name ne "method_named";
return if $self->meth_sv($constop)->PV ne "VERSION";
}
$lineseq = $version_op->sibling;
return if $lineseq->name ne "lineseq";
my $entersub = $lineseq->first->sibling;
if ($entersub->name eq "stub") {
return "use $module $version ();\n" if defined $version;
return "use $module ();\n";
}
return if $entersub->name ne "entersub";
# See if there are import arguments
my $args = '';
my $svop = $entersub->first->sibling; # Skip over pushmark
return unless $self->const_sv($svop)->PV eq $module;
# Pull out the arguments
for ($svop=$svop->sibling; $svop->name ne "method_named";
$svop = $svop->sibling) {
$args .= ", " if length($args);
$args .= $self->deparse($svop, 6);
}
my $use = 'use';
my $method_named = $svop;
return if $method_named->name ne "method_named";
my $method_name = $self->meth_sv($method_named)->PV;
if ($method_name eq "unimport") {
$use = 'no';
}
# Certain pragmas are dealt with using hint bits,
# so we ignore them here
if ($module eq 'strict' || $module eq 'integer'
|| $module eq 'bytes' || $module eq 'warnings'
|| $module eq 'feature') {
return "";
}
if (defined $version && length $args) {
return "$use $module $version ($args);\n";
} elsif (defined $version) {
return "$use $module $version;\n";
} elsif (length $args) {
return "$use $module ($args);\n";
} else {
return "$use $module;\n";
}
}
sub stash_subs {
my ($self, $pack, $seen) = @_;
my (@ret, $stash);
if (!defined $pack) {
$pack = '';
$stash = \%::;
}
else {
$pack =~ s/(::)?$/::/;
no strict 'refs';
$stash = \%{"main::$pack"};
}
return
if ($seen ||= {})->{
$INC{"overload.pm"} ? overload::StrVal($stash) : $stash
}++;
my %stash = svref_2object($stash)->ARRAY;
while (my ($key, $val) = each %stash) {
my $class = class($val);
if ($class eq "PV") {
# Just a prototype. As an ugly but fairly effective way
# to find out if it belongs here is to see if the AUTOLOAD
# (if any) for the stash was defined in one of our files.
my $A = $stash{"AUTOLOAD"};
if (defined ($A) && class($A) eq "GV" && defined($A->CV)
&& class($A->CV) eq "CV") {
my $AF = $A->FILE;
next unless $AF eq $0 || exists $self->{'files'}{$AF};
}
push @{$self->{'protos_todo'}}, [$pack . $key, $val->PV];
} elsif ($class eq "IV" && !($val->FLAGS & SVf_ROK)) {
# Just a name. As above.
# But skip proxy constant subroutines, as some form of perl-space
# visible code must have created them, be it a use statement, or
# some direct symbol-table manipulation code that we will Deparse
my $A = $stash{"AUTOLOAD"};
if (defined ($A) && class($A) eq "GV" && defined($A->CV)
&& class($A->CV) eq "CV") {
my $AF = $A->FILE;
next unless $AF eq $0 || exists $self->{'files'}{$AF};
}
push @{$self->{'protos_todo'}}, [$pack . $key, undef];
} elsif ($class eq "IV") {
# A reference. Dump this if it is a reference to a CV.
if (class(my $cv = $val->RV) eq "CV") {
$self->todo($cv, 0);
}
} elsif ($class eq "GV") {
if (class(my $cv = $val->CV) ne "SPECIAL") {
next if $self->{'subs_done'}{$$val}++;
next if $$val != ${$cv->GV}; # Ignore imposters
$self->todo($cv, 0);
}
if (class(my $cv = $val->FORM) ne "SPECIAL") {
next if $self->{'forms_done'}{$$val}++;
next if $$val != ${$cv->GV}; # Ignore imposters
$self->todo($cv, 1);
}
if (class($val->HV) ne "SPECIAL" && $key =~ /::$/) {
$self->stash_subs($pack . $key, $seen);
}
}
}
}
sub print_protos {
my $self = shift;
my $ar;
my @ret;
foreach $ar (@{$self->{'protos_todo'}}) {
my $proto = (defined $ar->[1] ? " (". $ar->[1] . ")" : "");
push @ret, "sub " . $ar->[0] . "$proto;\n";
}
delete $self->{'protos_todo'};
return @ret;
}
sub style_opts {
my $self = shift;
my $opts = shift;
my $opt;
while (length($opt = substr($opts, 0, 1))) {
if ($opt eq "C") {
$self->{'cuddle'} = " ";
$opts = substr($opts, 1);
} elsif ($opt eq "i") {
$opts =~ s/^i(\d+)//;
$self->{'indent_size'} = $1;
} elsif ($opt eq "T") {
$self->{'use_tabs'} = 1;
$opts = substr($opts, 1);
} elsif ($opt eq "v") {
$opts =~ s/^v([^.]*)(.|$)//;
$self->{'ex_const'} = $1;
}
}
}
sub new {
my $class = shift;
my $self = bless {}, $class;
$self->{'cuddle'} = "\n";
$self->{'curcop'} = undef;
$self->{'curstash'} = "main";
$self->{'ex_const'} = "'???'";
$self->{'expand'} = 0;
$self->{'files'} = {};
$self->{'indent_size'} = 4;
$self->{'linenums'} = 0;
$self->{'parens'} = 0;
$self->{'subs_todo'} = [];
$self->{'unquote'} = 0;
$self->{'use_dumper'} = 0;
$self->{'use_tabs'} = 0;
$self->{'ambient_arybase'} = 0;
$self->{'ambient_warnings'} = undef; # Assume no lexical warnings
$self->{'ambient_hints'} = 0;
$self->{'ambient_hinthash'} = undef;
$self->init();
while (my $arg = shift @_) {
if ($arg eq "-d") {
$self->{'use_dumper'} = 1;
require Data::Dumper;
} elsif ($arg =~ /^-f(.*)/) {
$self->{'files'}{$1} = 1;
} elsif ($arg eq "-l") {
$self->{'linenums'} = 1;
} elsif ($arg eq "-p") {
$self->{'parens'} = 1;
} elsif ($arg eq "-P") {
$self->{'noproto'} = 1;
} elsif ($arg eq "-q") {
$self->{'unquote'} = 1;
} elsif (substr($arg, 0, 2) eq "-s") {
$self->style_opts(substr $arg, 2);
} elsif ($arg =~ /^-x(\d)$/) {
$self->{'expand'} = $1;
}
}
return $self;
}
{
# Mask out the bits that L<warnings::register> uses
my $WARN_MASK;
BEGIN {
$WARN_MASK = $warnings::Bits{all} | $warnings::DeadBits{all};
}
sub WARN_MASK () {
return $WARN_MASK;
}
}
# Initialise the contextual information, either from
# defaults provided with the ambient_pragmas method,
# or from perl's own defaults otherwise.
sub init {
my $self = shift;
$self->{'arybase'} = $self->{'ambient_arybase'};
$self->{'warnings'} = defined ($self->{'ambient_warnings'})
? $self->{'ambient_warnings'} & WARN_MASK
: undef;
$self->{'hints'} = $self->{'ambient_hints'};
$self->{'hints'} &= 0xFF if $] < 5.009;
$self->{'hinthash'} = $self->{'ambient_hinthash'};
# also a convenient place to clear out subs_declared
delete $self->{'subs_declared'};
}
sub compile {
my(@args) = @_;
return sub {
my $self = B::Deparse->new(@args);
# First deparse command-line args
if (defined $^I) { # deparse -i
print q(BEGIN { $^I = ).perlstring($^I).qq(; }\n);
}
if ($^W) { # deparse -w
print qq(BEGIN { \$^W = $^W; }\n);
}
if ($/ ne "\n" or defined $O::savebackslash) { # deparse -l and -0
my $fs = perlstring($/) || 'undef';
my $bs = perlstring($O::savebackslash) || 'undef';
print qq(BEGIN { \$/ = $fs; \$\\ = $bs; }\n);
}
my @BEGINs = B::begin_av->isa("B::AV") ? B::begin_av->ARRAY : ();
my @UNITCHECKs = B::unitcheck_av->isa("B::AV")
? B::unitcheck_av->ARRAY
: ();
my @CHECKs = B::check_av->isa("B::AV") ? B::check_av->ARRAY : ();
my @INITs = B::init_av->isa("B::AV") ? B::init_av->ARRAY : ();
my @ENDs = B::end_av->isa("B::AV") ? B::end_av->ARRAY : ();
for my $block (@BEGINs, @UNITCHECKs, @CHECKs, @INITs, @ENDs) {
$self->todo($block, 0);
}
$self->stash_subs();
local($SIG{"__DIE__"}) =
sub {
if ($self->{'curcop'}) {
my $cop = $self->{'curcop'};
my($line, $file) = ($cop->line, $cop->file);
print STDERR "While deparsing $file near line $line,\n";
}
};
$self->{'curcv'} = main_cv;
$self->{'curcvlex'} = undef;
print $self->print_protos;
@{$self->{'subs_todo'}} =
sort {$a->[0] <=> $b->[0]} @{$self->{'subs_todo'}};
my $root = main_root;
local $B::overlay = {};
unless (null $root) {
$self->pessimise($root, main_start);
print $self->indent($self->deparse_root($root)), "\n";
}
my @text;
while (scalar(@{$self->{'subs_todo'}})) {
push @text, $self->next_todo;
}
print $self->indent(join("", @text)), "\n" if @text;
# Print __DATA__ section, if necessary
no strict 'refs';
my $laststash = defined $self->{'curcop'}
? $self->{'curcop'}->stash->NAME : $self->{'curstash'};
if (defined *{$laststash."::DATA"}{IO}) {
print $self->keyword("package") . " $laststash;\n"
unless $laststash eq $self->{'curstash'};
print $self->keyword("__DATA__") . "\n";
print readline(*{$laststash."::DATA"});
}
}
}
sub coderef2text {
my $self = shift;
my $sub = shift;
croak "Usage: ->coderef2text(CODEREF)" unless UNIVERSAL::isa($sub, "CODE");
$self->init();
return $self->indent($self->deparse_sub(svref_2object($sub)));
}
my %strict_bits = do {
local $^H;
map +($_ => strict::bits($_)), qw/refs subs vars/
};
sub ambient_pragmas {
my $self = shift;
my ($arybase, $hint_bits, $warning_bits, $hinthash) = (0, 0);
while (@_ > 1) {
my $name = shift();
my $val = shift();
if ($name eq 'strict') {
require strict;
if ($val eq 'none') {
$hint_bits &= $strict_bits{$_} for qw/refs subs vars/;
next();
}
my @names;
if ($val eq "all") {
@names = qw/refs subs vars/;
}
elsif (ref $val) {
@names = @$val;
}
else {
@names = split' ', $val;
}
$hint_bits |= $strict_bits{$_} for @names;
}
elsif ($name eq '$[') {
if (OPpCONST_ARYBASE) {
$arybase = $val;
} else {
croak "\$[ can't be non-zero on this perl" unless $val == 0;
}
}
elsif ($name eq 'integer'
|| $name eq 'bytes'
|| $name eq 'utf8') {
require "$name.pm";
if ($val) {
$hint_bits |= ${$::{"${name}::"}{"hint_bits"}};
}
else {
$hint_bits &= ~${$::{"${name}::"}{"hint_bits"}};
}
}
elsif ($name eq 're') {
require re;
if ($val eq 'none') {
$hint_bits &= ~re::bits(qw/taint eval/);
next();
}
my @names;
if ($val eq 'all') {
@names = qw/taint eval/;
}
elsif (ref $val) {
@names = @$val;
}
else {
@names = split' ',$val;
}
$hint_bits |= re::bits(@names);
}
elsif ($name eq 'warnings') {
if ($val eq 'none') {
$warning_bits = $warnings::NONE;
next();
}
my @names;
if (ref $val) {
@names = @$val;
}
else {
@names = split/\s+/, $val;
}
$warning_bits = $warnings::NONE if !defined ($warning_bits);
$warning_bits |= warnings::bits(@names);
}
elsif ($name eq 'warning_bits') {
$warning_bits = $val;
}
elsif ($name eq 'hint_bits') {
$hint_bits = $val;
}
elsif ($name eq '%^H') {
$hinthash = $val;
}
else {
croak "Unknown pragma type: $name";
}
}
if (@_) {
croak "The ambient_pragmas method expects an even number of args";
}
$self->{'ambient_arybase'} = $arybase;
$self->{'ambient_warnings'} = $warning_bits;
$self->{'ambient_hints'} = $hint_bits;
$self->{'ambient_hinthash'} = $hinthash;
}
# This method is the inner loop, so try to keep it simple
sub deparse {
my $self = shift;
my($op, $cx) = @_;
Carp::confess("Null op in deparse") if !defined($op)
|| class($op) eq "NULL";
my $meth = "pp_" . $op->name;
return $self->$meth($op, $cx);
}
sub indent {
my $self = shift;
my $txt = shift;
my @lines = split(/\n/, $txt);
my $leader = "";
my $level = 0;
my $line;
for $line (@lines) {
my $cmd = substr($line, 0, 1);
if ($cmd eq "\t" or $cmd eq "\b") {
$level += ($cmd eq "\t" ? 1 : -1) * $self->{'indent_size'};
if ($self->{'use_tabs'}) {
$leader = "\t" x ($level / 8) . " " x ($level % 8);
} else {
$leader = " " x $level;
}
$line = substr($line, 1);
}
if (index($line, "\f") > 0) {
$line =~ s/\f/\n/;
}
if (substr($line, 0, 1) eq "\f") {
$line = substr($line, 1); # no indent
} else {
$line = $leader . $line;