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