1ca3b14520da9a52bdb815d7b04740d8df7abdd2
[p5sagit/p5-mst-13.2.git] / lib / AutoLoader.pm
1 package AutoLoader;
2
3 use vars qw(@EXPORT @EXPORT_OK $VERSION);
4
5 my $is_dosish;
6 my $is_vms;
7
8 BEGIN {
9     require Exporter;
10     @EXPORT = ();
11     @EXPORT_OK = qw(AUTOLOAD);
12     $is_dosish = $^O eq 'dos' || $^O eq 'os2' || $^O eq 'MSWin32';
13     $is_vms = $^O eq 'VMS';
14     $VERSION = '5.56';
15 }
16
17 AUTOLOAD {
18     my $sub = $AUTOLOAD;
19     my $filename;
20     # Braces used to preserve $1 et al.
21     {
22         # Try to find the autoloaded file from the package-qualified
23         # name of the sub. e.g., if the sub needed is
24         # Getopt::Long::GetOptions(), then $INC{Getopt/Long.pm} is
25         # something like '/usr/lib/perl5/Getopt/Long.pm', and the
26         # autoload file is '/usr/lib/perl5/auto/Getopt/Long/GetOptions.al'.
27         #
28         # However, if @INC is a relative path, this might not work.  If,
29         # for example, @INC = ('lib'), then $INC{Getopt/Long.pm} is
30         # 'lib/Getopt/Long.pm', and we want to require
31         # 'auto/Getopt/Long/GetOptions.al' (without the leading 'lib').
32         # In this case, we simple prepend the 'auto/' and let the
33         # C<require> take care of the searching for us.
34
35         my ($pkg,$func) = ($sub =~ /(.*)::([^:]+)$/);
36         $pkg =~ s#::#/#g;
37         if (defined($filename = $INC{"$pkg.pm"})) {
38             $filename =~ s#^(.*)$pkg\.pm$#$1auto/$pkg/$func.al#;
39
40             # if the file exists, then make sure that it is a
41             # a fully anchored path (i.e either '/usr/lib/auto/foo/bar.al',
42             # or './lib/auto/foo/bar.al'.  This avoids C<require> searching
43             # (and failing) to find the 'lib/auto/foo/bar.al' because it
44             # looked for 'lib/lib/auto/foo/bar.al', given @INC = ('lib').
45
46             if (-r $filename) {
47                 unless ($filename =~ m|^/|) {
48                     if ($is_dosish) {
49                         unless ($filename =~ m{^([a-z]:)?[\\/]}i) {
50                              $filename = "./$filename";
51                         }
52                     }
53                     elsif ($is_vms) {
54                         # XXX todo by VMSmiths
55                         $filename = "./$filename";
56                     }
57                     else {
58                         $filename = "./$filename";
59                     }
60                 }
61             }
62             else {
63                 $filename = undef;
64             }
65         }
66         unless (defined $filename) {
67             # let C<require> do the searching
68             $filename = "auto/$sub.al";
69             $filename =~ s#::#/#g;
70         }
71     }
72     my $save = $@;
73     eval { local $SIG{__DIE__}; require $filename };
74     if ($@) {
75         if (substr($sub,-9) eq '::DESTROY') {
76             *$sub = sub {};
77         } else {
78             # The load might just have failed because the filename was too
79             # long for some old SVR3 systems which treat long names as errors.
80             # If we can succesfully truncate a long name then it's worth a go.
81             # There is a slight risk that we could pick up the wrong file here
82             # but autosplit should have warned about that when splitting.
83             if ($filename =~ s/(\w{12,})\.al$/substr($1,0,11).".al"/e){
84                 eval { local $SIG{__DIE__}; require $filename };
85             }
86             if ($@){
87                 $@ =~ s/ at .*\n//;
88                 my $error = $@;
89                 require Carp;
90                 Carp::croak($error);
91             }
92         }
93     }
94     $@ = $save;
95     goto &$sub;
96 }
97
98 sub import {
99     my $pkg = shift;
100     my $callpkg = caller;
101
102     #
103     # Export symbols, but not by accident of inheritance.
104     #
105
106     Exporter::export $pkg, $callpkg, @_ if $pkg eq 'AutoLoader';
107
108     #
109     # Try to find the autosplit index file.  Eg., if the call package
110     # is POSIX, then $INC{POSIX.pm} is something like
111     # '/usr/local/lib/perl5/POSIX.pm', and the autosplit index file is in
112     # '/usr/local/lib/perl5/auto/POSIX/autosplit.ix', so we require that.
113     #
114     # However, if @INC is a relative path, this might not work.  If,
115     # for example, @INC = ('lib'), then
116     # $INC{POSIX.pm} is 'lib/POSIX.pm', and we want to require
117     # 'auto/POSIX/autosplit.ix' (without the leading 'lib').
118     #
119
120     (my $calldir = $callpkg) =~ s#::#/#g;
121     my $path = $INC{$calldir . '.pm'};
122     if (defined($path)) {
123         # Try absolute path name.
124         $path =~ s#^(.*)$calldir\.pm$#$1auto/$calldir/autosplit.ix#;
125         eval { require $path; };
126         # If that failed, try relative path with normal @INC searching.
127         if ($@) {
128             $path ="auto/$calldir/autosplit.ix";
129             eval { require $path; };
130         }
131         if ($@) {
132             my $error = $@;
133             require Carp;
134             Carp::carp($error);
135         }
136     } 
137 }
138
139 1;
140
141 __END__
142
143 =head1 NAME
144
145 AutoLoader - load subroutines only on demand
146
147 =head1 SYNOPSIS
148
149     package Foo;
150     use AutoLoader 'AUTOLOAD';   # import the default AUTOLOAD subroutine
151
152     package Bar;
153     use AutoLoader;              # don't import AUTOLOAD, define our own
154     sub AUTOLOAD {
155         ...
156         $AutoLoader::AUTOLOAD = "...";
157         goto &AutoLoader::AUTOLOAD;
158     }
159
160 =head1 DESCRIPTION
161
162 The B<AutoLoader> module works with the B<AutoSplit> module and the
163 C<__END__> token to defer the loading of some subroutines until they are
164 used rather than loading them all at once.
165
166 To use B<AutoLoader>, the author of a module has to place the
167 definitions of subroutines to be autoloaded after an C<__END__> token.
168 (See L<perldata>.)  The B<AutoSplit> module can then be run manually to
169 extract the definitions into individual files F<auto/funcname.al>.
170
171 B<AutoLoader> implements an AUTOLOAD subroutine.  When an undefined
172 subroutine in is called in a client module of B<AutoLoader>,
173 B<AutoLoader>'s AUTOLOAD subroutine attempts to locate the subroutine in a
174 file with a name related to the location of the file from which the
175 client module was read.  As an example, if F<POSIX.pm> is located in
176 F</usr/local/lib/perl5/POSIX.pm>, B<AutoLoader> will look for perl
177 subroutines B<POSIX> in F</usr/local/lib/perl5/auto/POSIX/*.al>, where
178 the C<.al> file has the same name as the subroutine, sans package.  If
179 such a file exists, AUTOLOAD will read and evaluate it,
180 thus (presumably) defining the needed subroutine.  AUTOLOAD will then
181 C<goto> the newly defined subroutine.
182
183 Once this process completes for a given function, it is defined, so
184 future calls to the subroutine will bypass the AUTOLOAD mechanism.
185
186 =head2 Subroutine Stubs
187
188 In order for object method lookup and/or prototype checking to operate
189 correctly even when methods have not yet been defined it is necessary to
190 "forward declare" each subroutine (as in C<sub NAME;>).  See
191 L<perlsub/"SYNOPSIS">.  Such forward declaration creates "subroutine
192 stubs", which are place holders with no code.
193
194 The AutoSplit and B<AutoLoader> modules automate the creation of forward
195 declarations.  The AutoSplit module creates an 'index' file containing
196 forward declarations of all the AutoSplit subroutines.  When the
197 AutoLoader module is 'use'd it loads these declarations into its callers
198 package.
199
200 Because of this mechanism it is important that B<AutoLoader> is always
201 C<use>d and not C<require>d.
202
203 =head2 Using B<AutoLoader>'s AUTOLOAD Subroutine
204
205 In order to use B<AutoLoader>'s AUTOLOAD subroutine you I<must>
206 explicitly import it:
207
208     use AutoLoader 'AUTOLOAD';
209
210 =head2 Overriding B<AutoLoader>'s AUTOLOAD Subroutine
211
212 Some modules, mainly extensions, provide their own AUTOLOAD subroutines.
213 They typically need to check for some special cases (such as constants)
214 and then fallback to B<AutoLoader>'s AUTOLOAD for the rest.
215
216 Such modules should I<not> import B<AutoLoader>'s AUTOLOAD subroutine.
217 Instead, they should define their own AUTOLOAD subroutines along these
218 lines:
219
220     use AutoLoader;
221     use Carp;
222     use Errno;
223
224     sub AUTOLOAD {
225         my $sub = $AUTOLOAD;
226         (my $constname = $sub) =~ s/.*:://;
227         my $val = constant($constname, @_ ? $_[0] : 0);
228         if ($! != 0) {
229             if ($!{EINVAL} || $! =~ /Invalid/) {
230                 $AutoLoader::AUTOLOAD = $sub;
231                 goto &AutoLoader::AUTOLOAD;
232             }
233             else {
234                 croak "Your vendor has not defined constant $constname";
235             }
236         }
237         *$sub = sub { $val }; # same as: eval "sub $sub { $val }";
238         goto &$sub;
239     }
240
241 If any module's own AUTOLOAD subroutine has no need to fallback to the
242 AutoLoader's AUTOLOAD subroutine (because it doesn't have any AutoSplit
243 subroutines), then that module should not use B<AutoLoader> at all.
244
245 =head2 Package Lexicals
246
247 Package lexicals declared with C<my> in the main block of a package
248 using B<AutoLoader> will not be visible to auto-loaded subroutines, due to
249 the fact that the given scope ends at the C<__END__> marker.  A module
250 using such variables as package globals will not work properly under the
251 B<AutoLoader>.
252
253 The C<vars> pragma (see L<perlmod/"vars">) may be used in such
254 situations as an alternative to explicitly qualifying all globals with
255 the package namespace.  Variables pre-declared with this pragma will be
256 visible to any autoloaded routines (but will not be invisible outside
257 the package, unfortunately).
258
259 =head2 B<AutoLoader> vs. B<SelfLoader>
260
261 The B<AutoLoader> is similar in purpose to B<SelfLoader>: both delay the
262 loading of subroutines.
263
264 B<SelfLoader> uses the C<__DATA__> marker rather than C<__END__>.
265 While this avoids the use of a hierarchy of disk files and the
266 associated open/close for each routine loaded, B<SelfLoader> suffers a
267 startup speed disadvantage in the one-time parsing of the lines after
268 C<__DATA__>, after which routines are cached.  B<SelfLoader> can also
269 handle multiple packages in a file.
270
271 B<AutoLoader> only reads code as it is requested, and in many cases
272 should be faster, but requires a mechanism like B<AutoSplit> be used to
273 create the individual files.  L<ExtUtils::MakeMaker> will invoke
274 B<AutoSplit> automatically if B<AutoLoader> is used in a module source
275 file.
276
277 =head1 CAVEATS
278
279 AutoLoaders prior to Perl 5.002 had a slightly different interface.  Any
280 old modules which use B<AutoLoader> should be changed to the new calling
281 style.  Typically this just means changing a require to a use, adding
282 the explicit C<'AUTOLOAD'> import if needed, and removing B<AutoLoader>
283 from C<@ISA>.
284
285 On systems with restrictions on file name length, the file corresponding
286 to a subroutine may have a shorter name that the routine itself.  This
287 can lead to conflicting file names.  The I<AutoSplit> package warns of
288 these potential conflicts when used to split a module.
289
290 AutoLoader may fail to find the autosplit files (or even find the wrong
291 ones) in cases where C<@INC> contains relative paths, B<and> the program
292 does C<chdir>.
293
294 =head1 SEE ALSO
295
296 L<SelfLoader> - an autoloader that doesn't use external files.
297
298 =cut