This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
Refactoring the /Can't return (?:array|hash) to scalar context/ croak
[perl5.git] / lib / SelfLoader.pm
1 package SelfLoader;
2 use 5.008;
3 use strict;
4 our $VERSION = "1.15";
5
6 # The following bit of eval-magic is necessary to make this work on
7 # perls < 5.009005.
8 use vars qw/$AttrList/;
9 BEGIN {
10   if ($] > 5.009004) {
11     eval <<'NEWERPERL';
12 use 5.009005; # due to new regexp features
13 # allow checking for valid ': attrlist' attachments
14 # see also AutoSplit
15 $AttrList = qr{
16     \s* : \s*
17     (?:
18         # one attribute
19         (?> # no backtrack
20             (?! \d) \w+
21             (?<nested> \( (?: [^()]++ | (?&nested)++ )*+ \) ) ?
22         )
23         (?: \s* : \s* | \s+ (?! :) )
24     )*
25 }x;
26
27 NEWERPERL
28   }
29   else {
30     eval <<'OLDERPERL';
31 # allow checking for valid ': attrlist' attachments
32 # (we use 'our' rather than 'my' here, due to the rather complex and buggy
33 # behaviour of lexicals with qr// and (??{$lex}) )
34 our $nested;
35 $nested = qr{ \( (?: (?> [^()]+ ) | (??{ $nested }) )* \) }x;
36 our $one_attr = qr{ (?> (?! \d) \w+ (?:$nested)? ) (?:\s*\:\s*|\s+(?!\:)) }x;
37 $AttrList = qr{ \s* : \s* (?: $one_attr )* }x;
38 OLDERPERL
39   }
40 }
41 use Exporter;
42 our @ISA = qw(Exporter);
43 our @EXPORT = qw(AUTOLOAD);
44 sub Version {$VERSION}
45 sub DEBUG () { 0 }
46
47 my %Cache;      # private cache for all SelfLoader's client packages
48
49 # in croak and carp, protect $@ from "require Carp;" RT #40216
50
51 sub croak { { local $@; require Carp; } goto &Carp::croak }
52 sub carp { { local $@; require Carp; } goto &Carp::carp }
53
54 AUTOLOAD {
55     our $AUTOLOAD;
56     print STDERR "SelfLoader::AUTOLOAD for $AUTOLOAD\n" if DEBUG;
57     my $SL_code = $Cache{$AUTOLOAD};
58     my $save = $@; # evals in both AUTOLOAD and _load_stubs can corrupt $@
59     unless ($SL_code) {
60         # Maybe this pack had stubs before __DATA__, and never initialized.
61         # Or, this maybe an automatic DESTROY method call when none exists.
62         $AUTOLOAD =~ m/^(.*)::/;
63         SelfLoader->_load_stubs($1) unless exists $Cache{"${1}::<DATA"};
64         $SL_code = $Cache{$AUTOLOAD};
65         $SL_code = "sub $AUTOLOAD { }"
66             if (!$SL_code and $AUTOLOAD =~ m/::DESTROY$/);
67         croak "Undefined subroutine $AUTOLOAD" unless $SL_code;
68     }
69     print STDERR "SelfLoader::AUTOLOAD eval: $SL_code\n" if DEBUG;
70
71     {
72         no strict;
73         eval $SL_code;
74     }
75     if ($@) {
76         $@ =~ s/ at .*\n//;
77         croak $@;
78     }
79     $@ = $save;
80     defined(&$AUTOLOAD) || die "SelfLoader inconsistency error";
81     delete $Cache{$AUTOLOAD};
82     goto &$AUTOLOAD
83 }
84
85 sub load_stubs { shift->_load_stubs((caller)[0]) }
86
87 sub _load_stubs {
88     # $endlines is used by Devel::SelfStubber to capture lines after __END__
89     my($self, $callpack, $endlines) = @_;
90     no strict "refs";
91     my $fh = \*{"${callpack}::DATA"};
92     use strict;
93     my $currpack = $callpack;
94     my($line,$name,@lines, @stubs, $protoype);
95
96     print STDERR "SelfLoader::load_stubs($callpack)\n" if DEBUG;
97     croak("$callpack doesn't contain an __DATA__ token")
98         unless defined fileno($fh);
99     # Protect: fork() shares the file pointer between the parent and the kid
100     if(sysseek($fh, tell($fh), 0)) {
101       open my $nfh, '<&', $fh or croak "reopen: $!";# dup() the fd
102       close $fh or die "close: $1";                 # autocloses, but be paranoid
103       open $fh, '<&', $nfh or croak "reopen2: $!";  # dup() the fd "back"
104       close $nfh or die "close after reopen: $1";   # autocloses, but be paranoid
105     }
106     $Cache{"${currpack}::<DATA"} = 1;   # indicate package is cached
107
108     local($/) = "\n";
109     while(defined($line = <$fh>) and $line !~ m/^__END__/) {
110         if ($line =~ m/^\s*sub\s+([\w:]+)\s*((?:\([\\\$\@\%\&\*\;]*\))?(?:$AttrList)?)/) {
111             push(@stubs, $self->_add_to_cache($name, $currpack, \@lines, $protoype));
112             $protoype = $2;
113             @lines = ($line);
114             if (index($1,'::') == -1) {         # simple sub name
115                 $name = "${currpack}::$1";
116             } else {                            # sub name with package
117                 $name = $1;
118                 $name =~ m/^(.*)::/;
119                 if (defined(&{"${1}::AUTOLOAD"})) {
120                     \&{"${1}::AUTOLOAD"} == \&SelfLoader::AUTOLOAD ||
121                         die 'SelfLoader Error: attempt to specify Selfloading',
122                             " sub $name in non-selfloading module $1";
123                 } else {
124                     $self->export($1,'AUTOLOAD');
125                 }
126             }
127         } elsif ($line =~ m/^package\s+([\w:]+)/) { # A package declared
128             push(@stubs, $self->_add_to_cache($name, $currpack, \@lines, $protoype));
129             $self->_package_defined($line);
130             $name = '';
131             @lines = ();
132             $currpack = $1;
133             $Cache{"${currpack}::<DATA"} = 1;   # indicate package is cached
134             if (defined(&{"${1}::AUTOLOAD"})) {
135                 \&{"${1}::AUTOLOAD"} == \&SelfLoader::AUTOLOAD ||
136                     die 'SelfLoader Error: attempt to specify Selfloading',
137                         " package $currpack which already has AUTOLOAD";
138             } else {
139                 $self->export($currpack,'AUTOLOAD');
140             }
141         } else {
142             push(@lines,$line);
143         }
144     }
145     if (defined($line) && $line =~ /^__END__/) { # __END__
146         unless ($line =~ /^__END__\s*DATA/) {
147             if ($endlines) {
148                 # Devel::SelfStubber would like us to capture the lines after
149                 # __END__ so it can write out the entire file
150                 @$endlines = <$fh>;
151             }
152             close($fh);
153         }
154     }
155     push(@stubs, $self->_add_to_cache($name, $currpack, \@lines, $protoype));
156     no strict;
157     eval join('', @stubs) if @stubs;
158 }
159
160
161 sub _add_to_cache {
162     my($self,$fullname,$pack,$lines, $protoype) = @_;
163     return () unless $fullname;
164     carp("Redefining sub $fullname")
165       if exists $Cache{$fullname};
166     $Cache{$fullname} = join('', "package $pack; ",@$lines);
167     print STDERR "SelfLoader cached $fullname: $Cache{$fullname}" if DEBUG;
168     # return stub to be eval'd
169     defined($protoype) ? "sub $fullname $protoype;" : "sub $fullname;"
170 }
171
172 sub _package_defined {}
173
174 1;
175 __END__
176
177 =head1 NAME
178
179 SelfLoader - load functions only on demand
180
181 =head1 SYNOPSIS
182
183     package FOOBAR;
184     use SelfLoader;
185
186     ... (initializing code)
187
188     __DATA__
189     sub {....
190
191
192 =head1 DESCRIPTION
193
194 This module tells its users that functions in the FOOBAR package are to be
195 autoloaded from after the C<__DATA__> token.  See also
196 L<perlsub/"Autoloading">.
197
198 =head2 The __DATA__ token
199
200 The C<__DATA__> token tells the perl compiler that the perl code
201 for compilation is finished. Everything after the C<__DATA__> token
202 is available for reading via the filehandle FOOBAR::DATA,
203 where FOOBAR is the name of the current package when the C<__DATA__>
204 token is reached. This works just the same as C<__END__> does in
205 package 'main', but for other modules data after C<__END__> is not
206 automatically retrievable, whereas data after C<__DATA__> is.
207 The C<__DATA__> token is not recognized in versions of perl prior to
208 5.001m.
209
210 Note that it is possible to have C<__DATA__> tokens in the same package
211 in multiple files, and that the last C<__DATA__> token in a given
212 package that is encountered by the compiler is the one accessible
213 by the filehandle. This also applies to C<__END__> and main, i.e. if
214 the 'main' program has an C<__END__>, but a module 'require'd (_not_ 'use'd)
215 by that program has a 'package main;' declaration followed by an 'C<__DATA__>',
216 then the C<DATA> filehandle is set to access the data after the C<__DATA__>
217 in the module, _not_ the data after the C<__END__> token in the 'main'
218 program, since the compiler encounters the 'require'd file later.
219
220 =head2 SelfLoader autoloading
221
222 The B<SelfLoader> works by the user placing the C<__DATA__>
223 token I<after> perl code which needs to be compiled and
224 run at 'require' time, but I<before> subroutine declarations
225 that can be loaded in later - usually because they may never
226 be called.
227
228 The B<SelfLoader> will read from the FOOBAR::DATA filehandle to
229 load in the data after C<__DATA__>, and load in any subroutine
230 when it is called. The costs are the one-time parsing of the
231 data after C<__DATA__>, and a load delay for the _first_
232 call of any autoloaded function. The benefits (hopefully)
233 are a speeded up compilation phase, with no need to load
234 functions which are never used.
235
236 The B<SelfLoader> will stop reading from C<__DATA__> if
237 it encounters the C<__END__> token - just as you would expect.
238 If the C<__END__> token is present, and is followed by the
239 token DATA, then the B<SelfLoader> leaves the FOOBAR::DATA
240 filehandle open on the line after that token.
241
242 The B<SelfLoader> exports the C<AUTOLOAD> subroutine to the
243 package using the B<SelfLoader>, and this loads the called
244 subroutine when it is first called.
245
246 There is no advantage to putting subroutines which will _always_
247 be called after the C<__DATA__> token.
248
249 =head2 Autoloading and package lexicals
250
251 A 'my $pack_lexical' statement makes the variable $pack_lexical
252 local _only_ to the file up to the C<__DATA__> token. Subroutines
253 declared elsewhere _cannot_ see these types of variables,
254 just as if you declared subroutines in the package but in another
255 file, they cannot see these variables.
256
257 So specifically, autoloaded functions cannot see package
258 lexicals (this applies to both the B<SelfLoader> and the Autoloader).
259 The C<vars> pragma provides an alternative to defining package-level
260 globals that will be visible to autoloaded routines. See the documentation
261 on B<vars> in the pragma section of L<perlmod>.
262
263 =head2 SelfLoader and AutoLoader
264
265 The B<SelfLoader> can replace the AutoLoader - just change 'use AutoLoader'
266 to 'use SelfLoader' (though note that the B<SelfLoader> exports
267 the AUTOLOAD function - but if you have your own AUTOLOAD and
268 are using the AutoLoader too, you probably know what you're doing),
269 and the C<__END__> token to C<__DATA__>. You will need perl version 5.001m
270 or later to use this (version 5.001 with all patches up to patch m).
271
272 There is no need to inherit from the B<SelfLoader>.
273
274 The B<SelfLoader> works similarly to the AutoLoader, but picks up the
275 subs from after the C<__DATA__> instead of in the 'lib/auto' directory.
276 There is a maintenance gain in not needing to run AutoSplit on the module
277 at installation, and a runtime gain in not needing to keep opening and
278 closing files to load subs. There is a runtime loss in needing
279 to parse the code after the C<__DATA__>. Details of the B<AutoLoader> and
280 another view of these distinctions can be found in that module's
281 documentation.
282
283 =head2 __DATA__, __END__, and the FOOBAR::DATA filehandle.
284
285 This section is only relevant if you want to use
286 the C<FOOBAR::DATA> together with the B<SelfLoader>.
287
288 Data after the C<__DATA__> token in a module is read using the
289 FOOBAR::DATA filehandle. C<__END__> can still be used to denote the end
290 of the C<__DATA__> section if followed by the token DATA - this is supported
291 by the B<SelfLoader>. The C<FOOBAR::DATA> filehandle is left open if an
292 C<__END__> followed by a DATA is found, with the filehandle positioned at
293 the start of the line after the C<__END__> token. If no C<__END__> token is
294 present, or an C<__END__> token with no DATA token on the same line, then
295 the filehandle is closed.
296
297 The B<SelfLoader> reads from wherever the current
298 position of the C<FOOBAR::DATA> filehandle is, until the
299 EOF or C<__END__>. This means that if you want to use
300 that filehandle (and ONLY if you want to), you should either
301
302 1. Put all your subroutine declarations immediately after
303 the C<__DATA__> token and put your own data after those
304 declarations, using the C<__END__> token to mark the end
305 of subroutine declarations. You must also ensure that the B<SelfLoader>
306 reads first by  calling 'SelfLoader-E<gt>load_stubs();', or by using a
307 function which is selfloaded;
308
309 or
310
311 2. You should read the C<FOOBAR::DATA> filehandle first, leaving
312 the handle open and positioned at the first line of subroutine
313 declarations.
314
315 You could conceivably do both.
316
317 =head2 Classes and inherited methods.
318
319 For modules which are not classes, this section is not relevant.
320 This section is only relevant if you have methods which could
321 be inherited.
322
323 A subroutine stub (or forward declaration) looks like
324
325   sub stub;
326
327 i.e. it is a subroutine declaration without the body of the
328 subroutine. For modules which are not classes, there is no real
329 need for stubs as far as autoloading is concerned.
330
331 For modules which ARE classes, and need to handle inherited methods,
332 stubs are needed to ensure that the method inheritance mechanism works
333 properly. You can load the stubs into the module at 'require' time, by
334 adding the statement 'SelfLoader-E<gt>load_stubs();' to the module to do
335 this.
336
337 The alternative is to put the stubs in before the C<__DATA__> token BEFORE
338 releasing the module, and for this purpose the C<Devel::SelfStubber>
339 module is available.  However this does require the extra step of ensuring
340 that the stubs are in the module. If this is done I strongly recommend
341 that this is done BEFORE releasing the module - it should NOT be done
342 at install time in general.
343
344 =head1 Multiple packages and fully qualified subroutine names
345
346 Subroutines in multiple packages within the same file are supported - but you
347 should note that this requires exporting the C<SelfLoader::AUTOLOAD> to
348 every package which requires it. This is done automatically by the
349 B<SelfLoader> when it first loads the subs into the cache, but you should
350 really specify it in the initialization before the C<__DATA__> by putting
351 a 'use SelfLoader' statement in each package.
352
353 Fully qualified subroutine names are also supported. For example,
354
355    __DATA__
356    sub foo::bar {23}
357    package baz;
358    sub dob {32}
359
360 will all be loaded correctly by the B<SelfLoader>, and the B<SelfLoader>
361 will ensure that the packages 'foo' and 'baz' correctly have the
362 B<SelfLoader> C<AUTOLOAD> method when the data after C<__DATA__> is first
363 parsed.
364
365 =head1 AUTHOR
366
367 C<SelfLoader> is maintained by the perl5-porters. Please direct
368 any questions to the canonical mailing list. Anything that
369 is applicable to the CPAN release can be sent to its maintainer,
370 though.
371
372 Author and Maintainer: The Perl5-Porters <perl5-porters@perl.org>
373
374 Maintainer of the CPAN release: Steffen Mueller <smueller@cpan.org>
375
376 =head1 COPYRIGHT AND LICENSE
377
378 This package has been part of the perl core since the first release
379 of perl5. It has been released separately to CPAN so older installations
380 can benefit from bug fixes.
381
382 This package has the same copyright and license as the perl core:
383
384              Copyright (C) 1993, 1994, 1995, 1996, 1997, 1998, 1999,
385         2000, 2001, 2002, 2003, 2004, 2005, 2006 by Larry Wall and others
386     
387                             All rights reserved.
388     
389     This program is free software; you can redistribute it and/or modify
390     it under the terms of either:
391     
392         a) the GNU General Public License as published by the Free
393         Software Foundation; either version 1, or (at your option) any
394         later version, or
395     
396         b) the "Artistic License" which comes with this Kit.
397     
398     This program is distributed in the hope that it will be useful,
399     but WITHOUT ANY WARRANTY; without even the implied warranty of
400     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See either
401     the GNU General Public License or the Artistic License for more details.
402     
403     You should have received a copy of the Artistic License with this
404     Kit, in the file named "Artistic".  If not, I'll be glad to provide one.
405     
406     You should also have received a copy of the GNU General Public License
407     along with this program in the file named "Copying". If not, write to the 
408     Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 
409     02111-1307, USA or visit their web page on the internet at
410     http://www.gnu.org/copyleft/gpl.html.
411     
412     For those of you that choose to use the GNU General Public License,
413     my interpretation of the GNU General Public License is that no Perl
414     script falls under the terms of the GPL unless you explicitly put
415     said script under the terms of the GPL yourself.  Furthermore, any
416     object code linked with perl does not automatically fall under the
417     terms of the GPL, provided such object code only adds definitions
418     of subroutines and variables, and does not otherwise impair the
419     resulting interpreter from executing any standard Perl script.  I
420     consider linking in C subroutines in this manner to be the moral
421     equivalent of defining subroutines in the Perl language itself.  You
422     may sell such an object file as proprietary provided that you provide
423     or offer to provide the Perl source, as specified by the GNU General
424     Public License.  (This is merely an alternate way of specifying input
425     to the program.)  You may also sell a binary produced by the dumping of
426     a running Perl script that belongs to you, provided that you provide or
427     offer to provide the Perl source as specified by the GPL.  (The
428     fact that a Perl interpreter and your code are in the same binary file
429     is, in this case, a form of mere aggregation.)  This is my interpretation
430     of the GPL.  If you still have concerns or difficulties understanding
431     my intent, feel free to contact me.  Of course, the Artistic License
432     spells all this out for your protection, so you may prefer to use that.
433
434 =cut