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