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