This is patch.2b1c to perl5.002beta1. This patch includes
[p5sagit/p5-mst-13.2.git] / lib / SelfLoader.pm
1 package SelfLoader;
2 use Carp;
3 require Exporter;
4 @ISA = qw(Exporter);
5 @EXPORT = qw(AUTOLOAD);
6 $VERSION = 1.06; sub Version {$VERSION}
7 $DEBUG = 0;
8
9 my %Cache;      # private cache for all SelfLoader's client packages
10
11 AUTOLOAD {
12     print STDERR "SelfLoader::AUTOLOAD for $AUTOLOAD\n" if $DEBUG;
13     my $code = $Cache{$AUTOLOAD};
14     unless ($code) {
15         # Maybe this pack had stubs before __DATA__, and never initialized.
16         # Or, this maybe an automatic DESTROY method call when none exists.
17         $AUTOLOAD =~ m/^(.*)::/;
18         SelfLoader->_load_stubs($1) unless exists $Cache{"${1}::<DATA"};
19         $code = $Cache{$AUTOLOAD};
20         $code = "sub $AUTOLOAD { }" if (!$code and $AUTOLOAD =~ m/::DESTROY$/);
21         croak "Undefined subroutine $AUTOLOAD" unless $code;
22     }
23     print STDERR "SelfLoader::AUTOLOAD eval: $code\n" if $DEBUG;
24     eval $code;
25     if ($@) {
26         $@ =~ s/ at .*\n//;
27         croak $@;
28     }
29     defined(&$AUTOLOAD) || die "SelfLoader inconsistency error";
30     delete $Cache{$AUTOLOAD};
31     goto &$AUTOLOAD
32 }
33
34 sub load_stubs { shift->_load_stubs((caller)[0]) }
35
36 sub _load_stubs {
37     my($self, $callpack) = @_;
38     my $fh = \*{"${callpack}::DATA"};
39     my $currpack = $callpack;
40     my($line,$name,@lines, @stubs, $protoype);
41
42     print STDERR "SelfLoader::load_stubs($callpack)\n" if $DEBUG;
43     croak("$callpack doesn't contain an __DATA__ token")
44         unless fileno($fh);
45     $Cache{"${currpack}::<DATA"} = 1;   # indicate package is cached
46
47     while($line = <$fh> and $line !~ m/^__END__/) {
48         if ($line =~ m/^sub\s+([\w:]+)\s*(\([\$\@\;\%\\]*\))?/) {       # A sub declared
49             push(@stubs, $self->_add_to_cache($name, $currpack, \@lines, $protoype));
50             $protoype = $2;
51             @lines = ($line);
52             if (index($1,'::') == -1) {         # simple sub name
53                 $name = "${currpack}::$1";
54             } else {                            # sub name with package
55                 $name = $1;
56                 $name =~ m/^(.*)::/;
57                 if (defined(&{"${1}::AUTOLOAD"})) {
58                     \&{"${1}::AUTOLOAD"} == \&SelfLoader::AUTOLOAD ||
59                         die 'SelfLoader Error: attempt to specify Selfloading',
60                             " sub $name in non-selfloading module $1";
61                 } else {
62                     $self->export($1,'AUTOLOAD');
63                 }
64             }
65         } elsif ($line =~ m/^package\s+([\w:]+)/) { # A package declared
66             push(@stubs, $self->_add_to_cache($name, $currpack, \@lines, $protoype));
67             $self->_package_defined($line);
68             $name = '';
69             @lines = ();
70             $currpack = $1;
71             $Cache{"${currpack}::<DATA"} = 1;   # indicate package is cached
72             if (defined(&{"${1}::AUTOLOAD"})) {
73                 \&{"${1}::AUTOLOAD"} == \&SelfLoader::AUTOLOAD ||
74                     die 'SelfLoader Error: attempt to specify Selfloading',
75                         " package $currpack which already has AUTOLOAD";
76             } else {
77                 $self->export($currpack,'AUTOLOAD');
78             }
79         } else {
80             push(@lines,$line);
81         }
82     }
83     close($fh) unless defined($line) && $line =~ /^__END__\s*DATA/;     # __END__
84     push(@stubs, $self->_add_to_cache($name, $currpack, \@lines, $protoype));
85     eval join('', @stubs) if @stubs;
86 }
87
88
89 sub _add_to_cache {
90     my($self,$fullname,$pack,$lines, $protoype) = @_;
91     return () unless $fullname;
92     carp("Redefining sub $fullname") if exists $Cache{$fullname};
93     $Cache{$fullname} = join('', "package $pack; ",@$lines);
94     print STDERR "SelfLoader cached $fullname: $Cache{$fullname}" if $DEBUG;
95     # return stub to be eval'd
96     defined($protoype) ? "sub $fullname $protoype;" : "sub $fullname;"
97 }
98
99 sub _package_defined {}
100
101 1;
102 __END__
103 =head1 NAME
104
105 SelfLoader - load functions only on demand
106
107 =head1 SYNOPSIS
108
109     package FOOBAR;
110     use SelfLoader;
111     
112     ... (initializing code)
113     
114     __DATA__
115     sub {....
116
117
118 =head1 DESCRIPTION
119
120 This module tells its users that functions in the FOOBAR package are to be
121 autoloaded from after the __DATA__ token.  See also L<perlsub/"Autoloading">.
122
123 =head2 The __DATA__ token
124
125 The __DATA__ token tells the perl compiler that the perl code
126 for compilation is finished. Everything after the __DATA__ token
127 is available for reading via the filehandle FOOBAR::DATA,
128 where FOOBAR is the name of the current package when the __DATA__
129 token is reached. This works just the same as __END__ does in
130 package 'main', but for other modules data after __END__ is not
131 automatically retreivable , whereas data after __DATA__ is.
132 The __DATA__ token is not recognized in versions of perl prior to
133 5.001m.
134
135 Note that it is possible to have __DATA__ tokens in the same package
136 in multiple files, and that the last __DATA__ token in a given
137 package that is encountered by the compiler is the one accessible
138 by the filehandle. This also applies to __END__ and main, i.e. if
139 the 'main' program has an __END__, but a module 'require'd (_not_ 'use'd)
140 by that program has a 'package main;' declaration followed by an '__DATA__',
141 then the DATA filehandle is set to access the data after the __DATA__
142 in the module, _not_ the data after the __END__ token in the 'main'
143 program, since the compiler encounters the 'require'd file later.
144
145 =head2 SelfLoader autoloading
146
147 The SelfLoader works by the user placing the __DATA__
148 token _after_ perl code which needs to be compiled and
149 run at 'require' time, but _before_ subroutine declarations
150 that can be loaded in later - usually because they may never
151 be called.
152
153 The SelfLoader will read from the FOOBAR::DATA filehandle to
154 load in the data after __DATA__, and load in any subroutine
155 when it is called. The costs are the one-time parsing of the
156 data after __DATA__, and a load delay for the _first_
157 call of any autoloaded function. The benefits (hopefully)
158 are a speeded up compilation phase, with no need to load
159 functions which are never used.
160
161 The SelfLoader will stop reading from __DATA__ if
162 it encounters the __END__ token - just as you would expect.
163 If the __END__ token is present, and is followed by the
164 token DATA, then the SelfLoader leaves the FOOBAR::DATA
165 filehandle open on the line after that token.
166
167 The SelfLoader exports the AUTOLOAD subroutine to the
168 package using the SelfLoader, and this loads the called
169 subroutine when it is first called.
170
171 There is no advantage to putting subroutines which will _always_
172 be called after the __DATA__ token.
173
174 =head2 Autoloading and package lexicals
175
176 A 'my $pack_lexical' statement makes the variable $pack_lexical
177 local _only_ to the file up to the __DATA__ token. Subroutines
178 declared elsewhere _cannot_ see these types of variables,
179 just as if you declared subroutines in the package but in another
180 file, they cannot see these variables.
181
182 So specifically, autoloaded functions cannot see package
183 lexicals (this applies to both the SelfLoader and the Autoloader).
184
185 =head2 SelfLoader and AutoLoader
186
187 The SelfLoader can replace the AutoLoader - just change 'use AutoLoader'
188 to 'use SelfLoader' (though note that the SelfLoader exports
189 the AUTOLOAD function - but if you have your own AUTOLOAD and
190 are using the AutoLoader too, you probably know what you're doing),
191 and the __END__ token to __DATA__. You will need perl version 5.001m
192 or later to use this (version 5.001 with all patches up to patch m).
193
194 There is no need to inherit from the SelfLoader.
195
196 The SelfLoader works similarly to the AutoLoader, but picks up the
197 subs from after the __DATA__ instead of in the 'lib/auto' directory.
198 There is a maintainance gain in not needing to run AutoSplit on the module
199 at installation, and a runtime gain in not needing to keep opening and
200 closing files to load subs. There is a runtime loss in needing
201 to parse the code after the __DATA__.
202
203 =head2 __DATA__, __END__, and the FOOBAR::DATA filehandle.
204
205 This section is only relevant if you want to use
206 the FOOBAR::DATA together with the SelfLoader.
207
208 Data after the __DATA__ token in a module is read using the
209 FOOBAR::DATA filehandle. __END__ can still be used to denote the end
210 of the __DATA__ section if followed by the token DATA - this is supported
211 by the SelfLoader. The FOOBAR::DATA filehandle is left open if an __END__
212 followed by a DATA is found, with the filehandle positioned at the start
213 of the line after the __END__ token. If no __END__ token is present,
214 or an __END__ token with no DATA token on the same line, then the filehandle
215 is closed.
216
217 The SelfLoader reads from wherever the current
218 position of the FOOBAR::DATA filehandle is, until the
219 EOF or __END__. This means that if you want to use
220 that filehandle (and ONLY if you want to), you should either
221
222 1. Put all your subroutine declarations immediately after
223 the __DATA__ token and put your own data after those
224 declarations, using the __END__ token to mark the end
225 of subroutine declarations. You must also ensure that the SelfLoader
226 reads first by  calling 'SelfLoader->load_stubs();', or by using a
227 function which is selfloaded;
228
229 or
230
231 2. You should read the FOOBAR::DATA filehandle first, leaving
232 the handle open and positioned at the first line of subroutine
233 declarations.
234
235 You could conceivably do both.
236
237 =head2 Classes and inherited methods.
238
239 For modules which are not classes, this section is not relevant.
240 This section is only relevant if you have methods which could
241 be inherited.
242
243 A subroutine stub (or forward declaration) looks like
244
245   sub stub;
246
247 i.e. it is a subroutine declaration without the body of the
248 subroutine. For modules which are not classes, there is no real
249 need for stubs as far as autoloading is concerned.
250
251 For modules which ARE classes, and need to handle inherited methods,
252 stubs are needed to ensure that the method inheritance mechanism works
253 properly. You can load the stubs into the module at 'require' time, by
254 adding the statement 'SelfLoader->load_stubs();' to the module to do
255 this.
256
257 The alternative is to put the stubs in before the __DATA__ token BEFORE
258 releasing the module, and for this purpose the Devel::SelfStubber
259 module is available.  However this does require the extra step of ensuring
260 that the stubs are in the module. If this is done I strongly recommend
261 that this is done BEFORE releasing the module - it should NOT be done
262 at install time in general.
263
264 =head1 Multiple packages and fully qualified subroutine names
265
266 Subroutines in multiple packages within the same file are supported - but you
267 should note that this requires exporting the SelfLoader::AUTOLOAD to
268 every package which requires it. This is done automatically by the
269 SelfLoader when it first loads the subs into the cache, but you should
270 really specify it in the initialization before the __DATA__ by putting
271 a 'use SelfLoader' statement in each package.
272
273 Fully qualified subroutine names are also supported. For example,
274
275    __DATA__
276    sub foo::bar {23}
277    package baz;
278    sub dob {32}
279
280 will all be loaded correctly by the SelfLoader, and the SelfLoader
281 will ensure that the packages 'foo' and 'baz' correctly have the
282 SelfLoader AUTOLOAD method when the data after __DATA__ is first parsed.
283
284 =cut