Extra paranoia from Nicholas Clark.
[p5sagit/p5-mst-13.2.git] / ext / B / B.pm
1 #      B.pm
2 #
3 #      Copyright (c) 1996, 1997, 1998 Malcolm Beattie
4 #
5 #      You may distribute under the terms of either the GNU General Public
6 #      License or the Artistic License, as specified in the README file.
7 #
8 package B;
9
10 our $VERSION = '1.00';
11
12 use XSLoader ();
13 require Exporter;
14 @ISA = qw(Exporter);
15
16 # walkoptree_slow comes from B.pm (you are there),
17 # walkoptree comes from B.xs
18 @EXPORT_OK = qw(minus_c ppname save_BEGINs
19                 class peekop cast_I32 cstring cchar hash threadsv_names
20                 main_root main_start main_cv svref_2object opnumber
21                 amagic_generation
22                 walkoptree_slow walkoptree walkoptree_exec walksymtable
23                 parents comppadlist sv_undef compile_stats timing_info
24                 begin_av init_av end_av regex_padav);
25
26 sub OPf_KIDS ();
27 use strict;
28 @B::SV::ISA = 'B::OBJECT';
29 @B::NULL::ISA = 'B::SV';
30 @B::PV::ISA = 'B::SV';
31 @B::IV::ISA = 'B::SV';
32 @B::NV::ISA = 'B::IV';
33 @B::RV::ISA = 'B::SV';
34 @B::PVIV::ISA = qw(B::PV B::IV);
35 @B::PVNV::ISA = qw(B::PV B::NV);
36 @B::PVMG::ISA = 'B::PVNV';
37 @B::PVLV::ISA = 'B::PVMG';
38 @B::BM::ISA = 'B::PVMG';
39 @B::AV::ISA = 'B::PVMG';
40 @B::GV::ISA = 'B::PVMG';
41 @B::HV::ISA = 'B::PVMG';
42 @B::CV::ISA = 'B::PVMG';
43 @B::IO::ISA = 'B::PVMG';
44 @B::FM::ISA = 'B::CV';
45
46 @B::OP::ISA = 'B::OBJECT';
47 @B::UNOP::ISA = 'B::OP';
48 @B::BINOP::ISA = 'B::UNOP';
49 @B::LOGOP::ISA = 'B::UNOP';
50 @B::LISTOP::ISA = 'B::BINOP';
51 @B::SVOP::ISA = 'B::OP';
52 @B::PADOP::ISA = 'B::OP';
53 @B::PVOP::ISA = 'B::OP';
54 @B::CVOP::ISA = 'B::OP';
55 @B::LOOP::ISA = 'B::LISTOP';
56 @B::PMOP::ISA = 'B::LISTOP';
57 @B::COP::ISA = 'B::OP';
58
59 @B::SPECIAL::ISA = 'B::OBJECT';
60
61 {
62     # Stop "-w" from complaining about the lack of a real B::OBJECT class
63     package B::OBJECT;
64 }
65
66 sub B::GV::SAFENAME {
67   my $name = (shift())->NAME;
68
69   # The regex below corresponds to the isCONTROLVAR macro
70   # from toke.c
71
72   $name =~ s/^([\cA-\cZ\c\\c[\c]\c?\c_\c^])/"^".
73         chr( utf8::unicode_to_native( 64 ^ ord($1) ))/e;
74
75   # When we say unicode_to_native we really mean ascii_to_native,
76   # which matters iff this is a non-ASCII platform (EBCDIC).
77
78   return $name;
79 }
80
81 sub B::IV::int_value {
82   my ($self) = @_;
83   return (($self->FLAGS() & SVf_IVisUV()) ? $self->UVX : $self->IV);
84 }
85
86 sub B::NULL::as_string() {""}
87 sub B::IV::as_string()   {goto &B::IV::int_value}
88 sub B::PV::as_string()   {goto &B::PV::PV}
89
90 my $debug;
91 my $op_count = 0;
92 my @parents = ();
93
94 sub debug {
95     my ($class, $value) = @_;
96     $debug = $value;
97     walkoptree_debug($value);
98 }
99
100 sub class {
101     my $obj = shift;
102     my $name = ref $obj;
103     $name =~ s/^.*:://;
104     return $name;
105 }
106
107 sub parents { \@parents }
108
109 # For debugging
110 sub peekop {
111     my $op = shift;
112     return sprintf("%s (0x%x) %s", class($op), $$op, $op->name);
113 }
114
115 sub walkoptree_slow {
116     my($op, $method, $level) = @_;
117     $op_count++; # just for statistics
118     $level ||= 0;
119     warn(sprintf("walkoptree: %d. %s\n", $level, peekop($op))) if $debug;
120     $op->$method($level);
121     if ($$op && ($op->flags & OPf_KIDS)) {
122         my $kid;
123         unshift(@parents, $op);
124         for ($kid = $op->first; $$kid; $kid = $kid->sibling) {
125             walkoptree_slow($kid, $method, $level + 1);
126         }
127         shift @parents;
128     }
129 }
130
131 sub compile_stats {
132     return "Total number of OPs processed: $op_count\n";
133 }
134
135 sub timing_info {
136     my ($sec, $min, $hr) = localtime;
137     my ($user, $sys) = times;
138     sprintf("%02d:%02d:%02d user=$user sys=$sys",
139             $hr, $min, $sec, $user, $sys);
140 }
141
142 my %symtable;
143
144 sub clearsym {
145     %symtable = ();
146 }
147
148 sub savesym {
149     my ($obj, $value) = @_;
150 #    warn(sprintf("savesym: sym_%x => %s\n", $$obj, $value)); # debug
151     $symtable{sprintf("sym_%x", $$obj)} = $value;
152 }
153
154 sub objsym {
155     my $obj = shift;
156     return $symtable{sprintf("sym_%x", $$obj)};
157 }
158
159 sub walkoptree_exec {
160     my ($op, $method, $level) = @_;
161     $level ||= 0;
162     my ($sym, $ppname);
163     my $prefix = "    " x $level;
164     for (; $$op; $op = $op->next) {
165         $sym = objsym($op);
166         if (defined($sym)) {
167             print $prefix, "goto $sym\n";
168             return;
169         }
170         savesym($op, sprintf("%s (0x%lx)", class($op), $$op));
171         $op->$method($level);
172         $ppname = $op->name;
173         if ($ppname =~
174             /^(or|and|mapwhile|grepwhile|entertry|range|cond_expr)$/)
175         {
176             print $prefix, uc($1), " => {\n";
177             walkoptree_exec($op->other, $method, $level + 1);
178             print $prefix, "}\n";
179         } elsif ($ppname eq "match" || $ppname eq "subst") {
180             my $pmreplstart = $op->pmreplstart;
181             if ($$pmreplstart) {
182                 print $prefix, "PMREPLSTART => {\n";
183                 walkoptree_exec($pmreplstart, $method, $level + 1);
184                 print $prefix, "}\n";
185             }
186         } elsif ($ppname eq "substcont") {
187             print $prefix, "SUBSTCONT => {\n";
188             walkoptree_exec($op->other->pmreplstart, $method, $level + 1);
189             print $prefix, "}\n";
190             $op = $op->other;
191         } elsif ($ppname eq "enterloop") {
192             print $prefix, "REDO => {\n";
193             walkoptree_exec($op->redoop, $method, $level + 1);
194             print $prefix, "}\n", $prefix, "NEXT => {\n";
195             walkoptree_exec($op->nextop, $method, $level + 1);
196             print $prefix, "}\n", $prefix, "LAST => {\n";
197             walkoptree_exec($op->lastop,  $method, $level + 1);
198             print $prefix, "}\n";
199         } elsif ($ppname eq "subst") {
200             my $replstart = $op->pmreplstart;
201             if ($$replstart) {
202                 print $prefix, "SUBST => {\n";
203                 walkoptree_exec($replstart, $method, $level + 1);
204                 print $prefix, "}\n";
205             }
206         }
207     }
208 }
209
210 sub walksymtable {
211     my ($symref, $method, $recurse, $prefix) = @_;
212     my $sym;
213     my $ref;
214     my $fullname;
215     no strict 'refs';
216     $prefix = '' unless defined $prefix;
217     while (($sym, $ref) = each %$symref) {
218         $fullname = "*main::".$prefix.$sym;
219         if ($sym =~ /::$/) {
220             $sym = $prefix . $sym;
221             if ($sym ne "main::" && $sym ne "<none>::" && &$recurse($sym)) {
222                walksymtable(\%$fullname, $method, $recurse, $sym);
223             }
224         } else {
225            svref_2object(\*$fullname)->$method();
226         }
227     }
228 }
229
230 {
231     package B::Section;
232     my $output_fh;
233     my %sections;
234     
235     sub new {
236         my ($class, $section, $symtable, $default) = @_;
237         $output_fh ||= FileHandle->new_tmpfile;
238         my $obj = bless [-1, $section, $symtable, $default], $class;
239         $sections{$section} = $obj;
240         return $obj;
241     }
242     
243     sub get {
244         my ($class, $section) = @_;
245         return $sections{$section};
246     }
247
248     sub add {
249         my $section = shift;
250         while (defined($_ = shift)) {
251             print $output_fh "$section->[1]\t$_\n";
252             $section->[0]++;
253         }
254     }
255
256     sub index {
257         my $section = shift;
258         return $section->[0];
259     }
260
261     sub name {
262         my $section = shift;
263         return $section->[1];
264     }
265
266     sub symtable {
267         my $section = shift;
268         return $section->[2];
269     }
270         
271     sub default {
272         my $section = shift;
273         return $section->[3];
274     }
275         
276     sub output {
277         my ($section, $fh, $format) = @_;
278         my $name = $section->name;
279         my $sym = $section->symtable || {};
280         my $default = $section->default;
281
282         seek($output_fh, 0, 0);
283         while (<$output_fh>) {
284             chomp;
285             s/^(.*?)\t//;
286             if ($1 eq $name) {
287                 s{(s\\_[0-9a-f]+)} {
288                     exists($sym->{$1}) ? $sym->{$1} : $default;
289                 }ge;
290                 printf $fh $format, $_;
291             }
292         }
293     }
294 }
295
296 XSLoader::load 'B';
297
298 1;
299
300 __END__
301
302 =head1 NAME
303
304 B - The Perl Compiler
305
306 =head1 SYNOPSIS
307
308         use B;
309
310 =head1 DESCRIPTION
311
312 The C<B> module supplies classes which allow a Perl program to delve
313 into its own innards. It is the module used to implement the
314 "backends" of the Perl compiler. Usage of the compiler does not
315 require knowledge of this module: see the F<O> module for the
316 user-visible part. The C<B> module is of use to those who want to
317 write new compiler backends. This documentation assumes that the
318 reader knows a fair amount about perl's internals including such
319 things as SVs, OPs and the internal symbol table and syntax tree
320 of a program.
321
322 =head1 OVERVIEW OF CLASSES
323
324 The C structures used by Perl's internals to hold SV and OP
325 information (PVIV, AV, HV, ..., OP, SVOP, UNOP, ...) are modelled on a
326 class hierarchy and the C<B> module gives access to them via a true
327 object hierarchy. Structure fields which point to other objects
328 (whether types of SV or types of OP) are represented by the C<B>
329 module as Perl objects of the appropriate class. The bulk of the C<B>
330 module is the methods for accessing fields of these structures. Note
331 that all access is read-only: you cannot modify the internals by
332 using this module.
333
334 =head2 SV-RELATED CLASSES
335
336 B::IV, B::NV, B::RV, B::PV, B::PVIV, B::PVNV, B::PVMG, B::BM, B::PVLV,
337 B::AV, B::HV, B::CV, B::GV, B::FM, B::IO. These classes correspond in
338 the obvious way to the underlying C structures of similar names. The
339 inheritance hierarchy mimics the underlying C "inheritance". Access
340 methods correspond to the underlying C macros for field access,
341 usually with the leading "class indication" prefix removed (Sv, Av,
342 Hv, ...). The leading prefix is only left in cases where its removal
343 would cause a clash in method name. For example, C<GvREFCNT> stays
344 as-is since its abbreviation would clash with the "superclass" method
345 C<REFCNT> (corresponding to the C function C<SvREFCNT>).
346
347 =head2 B::SV METHODS
348
349 =over 4
350
351 =item REFCNT
352
353 =item FLAGS
354
355 =back
356
357 =head2 B::IV METHODS
358
359 =over 4
360
361 =item IV
362
363 Returns the value of the IV, I<interpreted as
364 a signed integer>. This will be misleading
365 if C<FLAGS & SVf_IVisUV>. Perhaps you want the
366 C<int_value> method instead?
367
368 =item IVX
369
370 =item UVX
371
372 =item int_value
373
374 This method returns the value of the IV as an integer.
375 It differs from C<IV> in that it returns the correct
376 value regardless of whether it's stored signed or
377 unsigned.
378
379 =item needs64bits
380
381 =item packiv
382
383 =back
384
385 =head2 B::NV METHODS
386
387 =over 4
388
389 =item NV
390
391 =item NVX
392
393 =back
394
395 =head2 B::RV METHODS
396
397 =over 4
398
399 =item RV
400
401 =back
402
403 =head2 B::PV METHODS
404
405 =over 4
406
407 =item PV
408
409 This method is the one you usually want. It constructs a
410 string using the length and offset information in the struct:
411 for ordinary scalars it will return the string that you'd see
412 from Perl, even if it contains null characters.
413
414 =item RV
415
416 Same as B::RV::RV, except that it will die() if the PV isn't
417 a reference.
418
419 =item PVX
420
421 This method is less often useful. It assumes that the string
422 stored in the struct is null-terminated, and disregards the
423 length information.
424
425 It is the appropriate method to use if you need to get the name
426 of a lexical variable from a padname array. Lexical variable names
427 are always stored with a null terminator, and the length field
428 (SvCUR) is overloaded for other purposes and can't be relied on here.
429
430 =back
431
432 =head2 B::PVMG METHODS
433
434 =over 4
435
436 =item MAGIC
437
438 =item SvSTASH
439
440 =back
441
442 =head2 B::MAGIC METHODS
443
444 =over 4
445
446 =item MOREMAGIC
447
448 =item precomp
449
450 Only valid on r-magic, returns the string that generated the regexp.
451
452 =item PRIVATE
453
454 =item TYPE
455
456 =item FLAGS
457
458 =item OBJ
459
460 Will die() if called on r-magic.
461
462 =item PTR
463
464 =item REGEX
465
466 Only valid on r-magic, returns the integer value of the REGEX stored
467 in the MAGIC.
468
469 =back
470
471 =head2 B::PVLV METHODS
472
473 =over 4
474
475 =item TARGOFF
476
477 =item TARGLEN
478
479 =item TYPE
480
481 =item TARG
482
483 =back
484
485 =head2 B::BM METHODS
486
487 =over 4
488
489 =item USEFUL
490
491 =item PREVIOUS
492
493 =item RARE
494
495 =item TABLE
496
497 =back
498
499 =head2 B::GV METHODS
500
501 =over 4
502
503 =item is_empty
504
505 This method returns TRUE if the GP field of the GV is NULL.
506
507 =item NAME
508
509 =item SAFENAME
510
511 This method returns the name of the glob, but if the first
512 character of the name is a control character, then it converts
513 it to ^X first, so that *^G would return "^G" rather than "\cG".
514
515 It's useful if you want to print out the name of a variable.
516 If you restrict yourself to globs which exist at compile-time
517 then the result ought to be unambiguous, because code like
518 C<${"^G"} = 1> is compiled as two ops - a constant string and
519 a dereference (rv2gv) - so that the glob is created at runtime.
520
521 If you're working with globs at runtime, and need to disambiguate
522 *^G from *{"^G"}, then you should use the raw NAME method.
523
524 =item STASH
525
526 =item SV
527
528 =item IO
529
530 =item FORM
531
532 =item AV
533
534 =item HV
535
536 =item EGV
537
538 =item CV
539
540 =item CVGEN
541
542 =item LINE
543
544 =item FILE
545
546 =item FILEGV
547
548 =item GvREFCNT
549
550 =item FLAGS
551
552 =back
553
554 =head2 B::IO METHODS
555
556 =over 4
557
558 =item LINES
559
560 =item PAGE
561
562 =item PAGE_LEN
563
564 =item LINES_LEFT
565
566 =item TOP_NAME
567
568 =item TOP_GV
569
570 =item FMT_NAME
571
572 =item FMT_GV
573
574 =item BOTTOM_NAME
575
576 =item BOTTOM_GV
577
578 =item SUBPROCESS
579
580 =item IoTYPE
581
582 =item IoFLAGS
583
584 =item IsSTD
585
586 Takes one arguments ( 'stdin' | 'stdout' | 'stderr' ) and returns true
587 if the IoIFP of the object is equal to the handle whose name was
588 passed as argument ( i.e. $io->IsSTD('stderr') is true if
589 IoIFP($io) == PerlIO_stdin() ).
590
591 =back
592
593 =head2 B::AV METHODS
594
595 =over 4
596
597 =item FILL
598
599 =item MAX
600
601 =item OFF
602
603 =item ARRAY
604
605 =item AvFLAGS
606
607 =back
608
609 =head2 B::CV METHODS
610
611 =over 4
612
613 =item STASH
614
615 =item START
616
617 =item ROOT
618
619 =item GV
620
621 =item FILE
622
623 =item DEPTH
624
625 =item PADLIST
626
627 =item OUTSIDE
628
629 =item XSUB
630
631 =item XSUBANY
632
633 For constant subroutines, returns the constant SV returned by the subroutine.
634
635 =item CvFLAGS
636
637 =item const_sv
638
639 =back
640
641 =head2 B::HV METHODS
642
643 =over 4
644
645 =item FILL
646
647 =item MAX
648
649 =item KEYS
650
651 =item RITER
652
653 =item NAME
654
655 =item PMROOT
656
657 =item ARRAY
658
659 =back
660
661 =head2 OP-RELATED CLASSES
662
663 B::OP, B::UNOP, B::BINOP, B::LOGOP, B::LISTOP, B::PMOP,
664 B::SVOP, B::PADOP, B::PVOP, B::CVOP, B::LOOP, B::COP.
665 These classes correspond in
666 the obvious way to the underlying C structures of similar names. The
667 inheritance hierarchy mimics the underlying C "inheritance". Access
668 methods correspond to the underlying C structre field names, with the
669 leading "class indication" prefix removed (op_).
670
671 =head2 B::OP METHODS
672
673 =over 4
674
675 =item next
676
677 =item sibling
678
679 =item name
680
681 This returns the op name as a string (e.g. "add", "rv2av").
682
683 =item ppaddr
684
685 This returns the function name as a string (e.g. "PL_ppaddr[OP_ADD]",
686 "PL_ppaddr[OP_RV2AV]").
687
688 =item desc
689
690 This returns the op description from the global C PL_op_desc array
691 (e.g. "addition" "array deref").
692
693 =item targ
694
695 =item type
696
697 =item seq
698
699 =item flags
700
701 =item private
702
703 =back
704
705 =head2 B::UNOP METHOD
706
707 =over 4
708
709 =item first
710
711 =back
712
713 =head2 B::BINOP METHOD
714
715 =over 4
716
717 =item last
718
719 =back
720
721 =head2 B::LOGOP METHOD
722
723 =over 4
724
725 =item other
726
727 =back
728
729 =head2 B::LISTOP METHOD
730
731 =over 4
732
733 =item children
734
735 =back
736
737 =head2 B::PMOP METHODS
738
739 =over 4
740
741 =item pmreplroot
742
743 =item pmreplstart
744
745 =item pmnext
746
747 =item pmregexp
748
749 =item pmflags
750
751 =item pmdynflags
752
753 =item pmpermflags
754
755 =item precomp
756
757 =item pmoffet
758
759 Only when perl was compiled with ithreads.
760
761 =back
762
763 =head2 B::SVOP METHOD
764
765 =over 4
766
767 =item sv
768
769 =item gv
770
771 =back
772
773 =head2 B::PADOP METHOD
774
775 =over 4
776
777 =item padix
778
779 =back
780
781 =head2 B::PVOP METHOD
782
783 =over 4
784
785 =item pv
786
787 =back
788
789 =head2 B::LOOP METHODS
790
791 =over 4
792
793 =item redoop
794
795 =item nextop
796
797 =item lastop
798
799 =back
800
801 =head2 B::COP METHODS
802
803 =over 4
804
805 =item label
806
807 =item stash
808
809 =item file
810
811 =item cop_seq
812
813 =item arybase
814
815 =item line
816
817 =back
818
819 =head1 FUNCTIONS EXPORTED BY C<B>
820
821 The C<B> module exports a variety of functions: some are simple
822 utility functions, others provide a Perl program with a way to
823 get an initial "handle" on an internal object.
824
825 =over 4
826
827 =item main_cv
828
829 Return the (faked) CV corresponding to the main part of the Perl
830 program.
831
832 =item init_av
833
834 Returns the AV object (i.e. in class B::AV) representing INIT blocks.
835
836 =item begin_av
837
838 Returns the AV object (i.e. in class B::AV) representing BEGIN blocks.
839
840 =item end_av
841
842 Returns the AV object (i.e. in class B::AV) representing END blocks.
843
844 =item main_root
845
846 Returns the root op (i.e. an object in the appropriate B::OP-derived
847 class) of the main part of the Perl program.
848
849 =item main_start
850
851 Returns the starting op of the main part of the Perl program.
852
853 =item comppadlist
854
855 Returns the AV object (i.e. in class B::AV) of the global comppadlist.
856
857 =item regex_padav
858
859 Only when perl was compiled with ithreads.
860
861 =item sv_undef
862
863 Returns the SV object corresponding to the C variable C<sv_undef>.
864
865 =item sv_yes
866
867 Returns the SV object corresponding to the C variable C<sv_yes>.
868
869 =item sv_no
870
871 Returns the SV object corresponding to the C variable C<sv_no>.
872
873 =item amagic_generation
874
875 Returns the SV object corresponding to the C variable C<amagic_generation>.
876
877 =item walkoptree(OP, METHOD)
878
879 Does a tree-walk of the syntax tree based at OP and calls METHOD on
880 each op it visits. Each node is visited before its children. If
881 C<walkoptree_debug> (q.v.) has been called to turn debugging on then
882 the method C<walkoptree_debug> is called on each op before METHOD is
883 called.
884
885 =item walkoptree_debug(DEBUG)
886
887 Returns the current debugging flag for C<walkoptree>. If the optional
888 DEBUG argument is non-zero, it sets the debugging flag to that. See
889 the description of C<walkoptree> above for what the debugging flag
890 does.
891
892 =item walksymtable(SYMREF, METHOD, RECURSE, PREFIX)
893
894 Walk the symbol table starting at SYMREF and call METHOD on each
895 symbol (a B::GV object) visited.  When the walk reaches package
896 symbols (such as "Foo::") it invokes RECURSE, passing in the symbol
897 name, and only recurses into the package if that sub returns true.
898
899 PREFIX is the name of the SYMREF you're walking.
900
901 For example...
902
903   # Walk CGI's symbol table calling print_subs on each symbol.
904   # Only recurse into CGI::Util::
905   walksymtable(\%CGI::, 'print_subs', sub { $_[0] eq 'CGI::Util::' },
906                'CGI::');
907
908 print_subs() is a B::GV method you have declared.
909
910
911 =item svref_2object(SV)
912
913 Takes any Perl variable and turns it into an object in the
914 appropriate B::OP-derived or B::SV-derived class. Apart from functions
915 such as C<main_root>, this is the primary way to get an initial
916 "handle" on an internal perl data structure which can then be followed
917 with the other access methods.
918
919 =item ppname(OPNUM)
920
921 Return the PP function name (e.g. "pp_add") of op number OPNUM.
922
923 =item hash(STR)
924
925 Returns a string in the form "0x..." representing the value of the
926 internal hash function used by perl on string STR.
927
928 =item cast_I32(I)
929
930 Casts I to the internal I32 type used by that perl.
931
932
933 =item minus_c
934
935 Does the equivalent of the C<-c> command-line option. Obviously, this
936 is only useful in a BEGIN block or else the flag is set too late.
937
938
939 =item cstring(STR)
940
941 Returns a double-quote-surrounded escaped version of STR which can
942 be used as a string in C source code.
943
944 =item class(OBJ)
945
946 Returns the class of an object without the part of the classname
947 preceding the first "::". This is used to turn "B::UNOP" into
948 "UNOP" for example.
949
950 =item threadsv_names
951
952 In a perl compiled for threads, this returns a list of the special
953 per-thread threadsv variables.
954
955 =back
956
957 =head1 AUTHOR
958
959 Malcolm Beattie, C<mbeattie@sable.ox.ac.uk>
960
961 =cut