This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
[inseparable changes from match from perl-5.003_97c to perl-5.003_97d]
[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.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(defined($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
104 =head1 NAME
105
106 SelfLoader - load functions only on demand
107
108 =head1 SYNOPSIS
109
110     package FOOBAR;
111     use SelfLoader;
112     
113     ... (initializing code)
114     
115     __DATA__
116     sub {....
117
118
119 =head1 DESCRIPTION
120
121 This module tells its users that functions in the FOOBAR package are to be
122 autoloaded from after the C<__DATA__> token.  See also
123 L<perlsub/"Autoloading">.
124
125 =head2 The __DATA__ token
126
127 The C<__DATA__> token tells the perl compiler that the perl code
128 for compilation is finished. Everything after the C<__DATA__> token
129 is available for reading via the filehandle FOOBAR::DATA,
130 where FOOBAR is the name of the current package when the C<__DATA__>
131 token is reached. This works just the same as C<__END__> does in
132 package 'main', but for other modules data after C<__END__> is not
133 automatically retreivable , whereas data after C<__DATA__> is.
134 The C<__DATA__> token is not recognized in versions of perl prior to
135 5.001m.
136
137 Note that it is possible to have C<__DATA__> tokens in the same package
138 in multiple files, and that the last C<__DATA__> token in a given
139 package that is encountered by the compiler is the one accessible
140 by the filehandle. This also applies to C<__END__> and main, i.e. if
141 the 'main' program has an C<__END__>, but a module 'require'd (_not_ 'use'd)
142 by that program has a 'package main;' declaration followed by an 'C<__DATA__>',
143 then the C<DATA> filehandle is set to access the data after the C<__DATA__>
144 in the module, _not_ the data after the C<__END__> token in the 'main'
145 program, since the compiler encounters the 'require'd file later.
146
147 =head2 SelfLoader autoloading
148
149 The B<SelfLoader> works by the user placing the C<__DATA__>
150 token I<after> perl code which needs to be compiled and
151 run at 'require' time, but I<before> subroutine declarations
152 that can be loaded in later - usually because they may never
153 be called.
154
155 The B<SelfLoader> will read from the FOOBAR::DATA filehandle to
156 load in the data after C<__DATA__>, and load in any subroutine
157 when it is called. The costs are the one-time parsing of the
158 data after C<__DATA__>, and a load delay for the _first_
159 call of any autoloaded function. The benefits (hopefully)
160 are a speeded up compilation phase, with no need to load
161 functions which are never used.
162
163 The B<SelfLoader> will stop reading from C<__DATA__> if
164 it encounters the C<__END__> token - just as you would expect.
165 If the C<__END__> token is present, and is followed by the
166 token DATA, then the B<SelfLoader> leaves the FOOBAR::DATA
167 filehandle open on the line after that token.
168
169 The B<SelfLoader> exports the C<AUTOLOAD> subroutine to the
170 package using the B<SelfLoader>, and this loads the called
171 subroutine when it is first called.
172
173 There is no advantage to putting subroutines which will _always_
174 be called after the C<__DATA__> token.
175
176 =head2 Autoloading and package lexicals
177
178 A 'my $pack_lexical' statement makes the variable $pack_lexical
179 local _only_ to the file up to the C<__DATA__> token. Subroutines
180 declared elsewhere _cannot_ see these types of variables,
181 just as if you declared subroutines in the package but in another
182 file, they cannot see these variables.
183
184 So specifically, autoloaded functions cannot see package
185 lexicals (this applies to both the B<SelfLoader> and the Autoloader).
186 The C<vars> pragma provides an alternative to defining package-level
187 globals that will be visible to autoloaded routines. See the documentation
188 on B<vars> in the pragma section of L<perlmod>.
189
190 =head2 SelfLoader and AutoLoader
191
192 The B<SelfLoader> can replace the AutoLoader - just change 'use AutoLoader'
193 to 'use SelfLoader' (though note that the B<SelfLoader> exports
194 the AUTOLOAD function - but if you have your own AUTOLOAD and
195 are using the AutoLoader too, you probably know what you're doing),
196 and the C<__END__> token to C<__DATA__>. You will need perl version 5.001m
197 or later to use this (version 5.001 with all patches up to patch m).
198
199 There is no need to inherit from the B<SelfLoader>.
200
201 The B<SelfLoader> works similarly to the AutoLoader, but picks up the
202 subs from after the C<__DATA__> instead of in the 'lib/auto' directory.
203 There is a maintainance gain in not needing to run AutoSplit on the module
204 at installation, and a runtime gain in not needing to keep opening and
205 closing files to load subs. There is a runtime loss in needing
206 to parse the code after the C<__DATA__>. Details of the B<AutoLoader> and
207 another view of these distinctions can be found in that module's
208 documentation.
209
210 =head2 __DATA__, __END__, and the FOOBAR::DATA filehandle.
211
212 This section is only relevant if you want to use
213 the C<FOOBAR::DATA> together with the B<SelfLoader>.
214
215 Data after the C<__DATA__> token in a module is read using the
216 FOOBAR::DATA filehandle. C<__END__> can still be used to denote the end
217 of the C<__DATA__> section if followed by the token DATA - this is supported
218 by the B<SelfLoader>. The C<FOOBAR::DATA> filehandle is left open if an
219 C<__END__> followed by a DATA is found, with the filehandle positioned at
220 the start of the line after the C<__END__> token. If no C<__END__> token is
221 present, or an C<__END__> token with no DATA token on the same line, then
222 the filehandle is closed.
223
224 The B<SelfLoader> reads from wherever the current
225 position of the C<FOOBAR::DATA> filehandle is, until the
226 EOF or C<__END__>. This means that if you want to use
227 that filehandle (and ONLY if you want to), you should either
228
229 1. Put all your subroutine declarations immediately after
230 the C<__DATA__> token and put your own data after those
231 declarations, using the C<__END__> token to mark the end
232 of subroutine declarations. You must also ensure that the B<SelfLoader>
233 reads first by  calling 'SelfLoader-E<gt>load_stubs();', or by using a
234 function which is selfloaded;
235
236 or
237
238 2. You should read the C<FOOBAR::DATA> filehandle first, leaving
239 the handle open and positioned at the first line of subroutine
240 declarations.
241
242 You could conceivably do both.
243
244 =head2 Classes and inherited methods.
245
246 For modules which are not classes, this section is not relevant.
247 This section is only relevant if you have methods which could
248 be inherited.
249
250 A subroutine stub (or forward declaration) looks like
251
252   sub stub;
253
254 i.e. it is a subroutine declaration without the body of the
255 subroutine. For modules which are not classes, there is no real
256 need for stubs as far as autoloading is concerned.
257
258 For modules which ARE classes, and need to handle inherited methods,
259 stubs are needed to ensure that the method inheritance mechanism works
260 properly. You can load the stubs into the module at 'require' time, by
261 adding the statement 'SelfLoader-E<gt>load_stubs();' to the module to do
262 this.
263
264 The alternative is to put the stubs in before the C<__DATA__> token BEFORE
265 releasing the module, and for this purpose the C<Devel::SelfStubber>
266 module is available.  However this does require the extra step of ensuring
267 that the stubs are in the module. If this is done I strongly recommend
268 that this is done BEFORE releasing the module - it should NOT be done
269 at install time in general.
270
271 =head1 Multiple packages and fully qualified subroutine names
272
273 Subroutines in multiple packages within the same file are supported - but you
274 should note that this requires exporting the C<SelfLoader::AUTOLOAD> to
275 every package which requires it. This is done automatically by the
276 B<SelfLoader> when it first loads the subs into the cache, but you should
277 really specify it in the initialization before the C<__DATA__> by putting
278 a 'use SelfLoader' statement in each package.
279
280 Fully qualified subroutine names are also supported. For example,
281
282    __DATA__
283    sub foo::bar {23}
284    package baz;
285    sub dob {32}
286
287 will all be loaded correctly by the B<SelfLoader>, and the B<SelfLoader>
288 will ensure that the packages 'foo' and 'baz' correctly have the
289 B<SelfLoader> C<AUTOLOAD> method when the data after C<__DATA__> is first
290 parsed.
291
292 =cut