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