This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
Fixes to compile Perl with g++ and DEBUGGING.
[perl5.git] / lib / SelfLoader.pm
CommitLineData
f8881bd9 1package SelfLoader;
f8881bd9
AD
2require Exporter;
3@ISA = qw(Exporter);
4@EXPORT = qw(AUTOLOAD);
8878f897 5$VERSION = "1.0905";
52128c7b 6sub Version {$VERSION}
f8881bd9
AD
7$DEBUG = 0;
8
9my %Cache; # private cache for all SelfLoader's client packages
10
09bef843 11# allow checking for valid ': attrlist' attachments
2611e30b
JH
12# (we use 'our' rather than 'my' here, due to the rather complex and buggy
13# behaviour of lexicals with qr// and (??{$lex}) )
14our $nested;
14455d6c 15$nested = qr{ \( (?: (?> [^()]+ ) | (??{ $nested }) )* \) }x;
2611e30b
JH
16our $one_attr = qr{ (?> (?! \d) \w+ (?:$nested)? ) (?:\s*\:\s*|\s+(?!\:)) }x;
17our $attr_list = qr{ \s* : \s* (?: $one_attr )* }x;
09bef843 18
cca8f13b
AF
19# in croak and carp, protect $@ from "require Carp;" RT #40216
20
21sub croak { { local $@; require Carp; } goto &Carp::croak }
22sub carp { { local $@; require Carp; } goto &Carp::carp }
e3d0cac0 23
f8881bd9
AD
24AUTOLOAD {
25 print STDERR "SelfLoader::AUTOLOAD for $AUTOLOAD\n" if $DEBUG;
c7675058 26 my $SL_code = $Cache{$AUTOLOAD};
bfdd1499 27 my $save = $@; # evals in both AUTOLOAD and _load_stubs can corrupt $@
c7675058 28 unless ($SL_code) {
f8881bd9
AD
29 # Maybe this pack had stubs before __DATA__, and never initialized.
30 # Or, this maybe an automatic DESTROY method call when none exists.
31 $AUTOLOAD =~ m/^(.*)::/;
32 SelfLoader->_load_stubs($1) unless exists $Cache{"${1}::<DATA"};
c7675058
JG
33 $SL_code = $Cache{$AUTOLOAD};
34 $SL_code = "sub $AUTOLOAD { }"
35 if (!$SL_code and $AUTOLOAD =~ m/::DESTROY$/);
36 croak "Undefined subroutine $AUTOLOAD" unless $SL_code;
f8881bd9 37 }
c7675058 38 print STDERR "SelfLoader::AUTOLOAD eval: $SL_code\n" if $DEBUG;
bfdd1499 39
c7675058 40 eval $SL_code;
f8881bd9
AD
41 if ($@) {
42 $@ =~ s/ at .*\n//;
43 croak $@;
44 }
bfdd1499 45 $@ = $save;
f8881bd9
AD
46 defined(&$AUTOLOAD) || die "SelfLoader inconsistency error";
47 delete $Cache{$AUTOLOAD};
48 goto &$AUTOLOAD
49}
50
51sub load_stubs { shift->_load_stubs((caller)[0]) }
52
53sub _load_stubs {
33235a50
NC
54 # $endlines is used by Devel::SelfStubber to capture lines after __END__
55 my($self, $callpack, $endlines) = @_;
f8881bd9
AD
56 my $fh = \*{"${callpack}::DATA"};
57 my $currpack = $callpack;
58 my($line,$name,@lines, @stubs, $protoype);
59
60 print STDERR "SelfLoader::load_stubs($callpack)\n" if $DEBUG;
61 croak("$callpack doesn't contain an __DATA__ token")
62 unless fileno($fh);
63 $Cache{"${currpack}::<DATA"} = 1; # indicate package is cached
64
52128c7b 65 local($/) = "\n";
40da2db3 66 while(defined($line = <$fh>) and $line !~ m/^__END__/) {
09bef843 67 if ($line =~ m/^sub\s+([\w:]+)\s*((?:\([\\\$\@\%\&\*\;]*\))?(?:$attr_list)?)/) {
f8881bd9
AD
68 push(@stubs, $self->_add_to_cache($name, $currpack, \@lines, $protoype));
69 $protoype = $2;
70 @lines = ($line);
71 if (index($1,'::') == -1) { # simple sub name
72 $name = "${currpack}::$1";
73 } else { # sub name with package
74 $name = $1;
75 $name =~ m/^(.*)::/;
76 if (defined(&{"${1}::AUTOLOAD"})) {
77 \&{"${1}::AUTOLOAD"} == \&SelfLoader::AUTOLOAD ||
78 die 'SelfLoader Error: attempt to specify Selfloading',
79 " sub $name in non-selfloading module $1";
80 } else {
81 $self->export($1,'AUTOLOAD');
82 }
83 }
84 } elsif ($line =~ m/^package\s+([\w:]+)/) { # A package declared
85 push(@stubs, $self->_add_to_cache($name, $currpack, \@lines, $protoype));
86 $self->_package_defined($line);
87 $name = '';
88 @lines = ();
89 $currpack = $1;
90 $Cache{"${currpack}::<DATA"} = 1; # indicate package is cached
91 if (defined(&{"${1}::AUTOLOAD"})) {
92 \&{"${1}::AUTOLOAD"} == \&SelfLoader::AUTOLOAD ||
93 die 'SelfLoader Error: attempt to specify Selfloading',
94 " package $currpack which already has AUTOLOAD";
95 } else {
96 $self->export($currpack,'AUTOLOAD');
97 }
98 } else {
99 push(@lines,$line);
100 }
101 }
33235a50
NC
102 if (defined($line) && $line =~ /^__END__/) { # __END__
103 unless ($line =~ /^__END__\s*DATA/) {
104 if ($endlines) {
105 # Devel::SelfStubber would like us to capture the lines after
106 # __END__ so it can write out the entire file
107 @$endlines = <$fh>;
108 }
109 close($fh);
110 }
111 }
f8881bd9
AD
112 push(@stubs, $self->_add_to_cache($name, $currpack, \@lines, $protoype));
113 eval join('', @stubs) if @stubs;
114}
115
116
117sub _add_to_cache {
118 my($self,$fullname,$pack,$lines, $protoype) = @_;
119 return () unless $fullname;
8878f897 120 carp("Redefining sub $fullname")
e3d0cac0 121 if exists $Cache{$fullname};
f8881bd9
AD
122 $Cache{$fullname} = join('', "package $pack; ",@$lines);
123 print STDERR "SelfLoader cached $fullname: $Cache{$fullname}" if $DEBUG;
124 # return stub to be eval'd
125 defined($protoype) ? "sub $fullname $protoype;" : "sub $fullname;"
126}
127
128sub _package_defined {}
129
1301;
131__END__
cb1a09d0 132
f8881bd9
AD
133=head1 NAME
134
135SelfLoader - load functions only on demand
136
137=head1 SYNOPSIS
138
139 package FOOBAR;
140 use SelfLoader;
3cb6de81 141
f8881bd9 142 ... (initializing code)
3cb6de81 143
f8881bd9
AD
144 __DATA__
145 sub {....
146
147
148=head1 DESCRIPTION
149
150This module tells its users that functions in the FOOBAR package are to be
463e8aa9 151autoloaded from after the C<__DATA__> token. See also
152L<perlsub/"Autoloading">.
f8881bd9
AD
153
154=head2 The __DATA__ token
155
463e8aa9 156The C<__DATA__> token tells the perl compiler that the perl code
157for compilation is finished. Everything after the C<__DATA__> token
f8881bd9 158is available for reading via the filehandle FOOBAR::DATA,
463e8aa9 159where FOOBAR is the name of the current package when the C<__DATA__>
160token is reached. This works just the same as C<__END__> does in
161package 'main', but for other modules data after C<__END__> is not
f610777f 162automatically retrievable, whereas data after C<__DATA__> is.
463e8aa9 163The C<__DATA__> token is not recognized in versions of perl prior to
f8881bd9
AD
1645.001m.
165
463e8aa9 166Note that it is possible to have C<__DATA__> tokens in the same package
167in multiple files, and that the last C<__DATA__> token in a given
f8881bd9 168package that is encountered by the compiler is the one accessible
463e8aa9 169by the filehandle. This also applies to C<__END__> and main, i.e. if
170the 'main' program has an C<__END__>, but a module 'require'd (_not_ 'use'd)
171by that program has a 'package main;' declaration followed by an 'C<__DATA__>',
172then the C<DATA> filehandle is set to access the data after the C<__DATA__>
173in the module, _not_ the data after the C<__END__> token in the 'main'
f8881bd9
AD
174program, since the compiler encounters the 'require'd file later.
175
176=head2 SelfLoader autoloading
177
463e8aa9 178The B<SelfLoader> works by the user placing the C<__DATA__>
179token I<after> perl code which needs to be compiled and
180run at 'require' time, but I<before> subroutine declarations
f8881bd9
AD
181that can be loaded in later - usually because they may never
182be called.
183
463e8aa9 184The B<SelfLoader> will read from the FOOBAR::DATA filehandle to
185load in the data after C<__DATA__>, and load in any subroutine
f8881bd9 186when it is called. The costs are the one-time parsing of the
463e8aa9 187data after C<__DATA__>, and a load delay for the _first_
f8881bd9
AD
188call of any autoloaded function. The benefits (hopefully)
189are a speeded up compilation phase, with no need to load
190functions which are never used.
191
463e8aa9 192The B<SelfLoader> will stop reading from C<__DATA__> if
193it encounters the C<__END__> token - just as you would expect.
194If the C<__END__> token is present, and is followed by the
195token DATA, then the B<SelfLoader> leaves the FOOBAR::DATA
f8881bd9
AD
196filehandle open on the line after that token.
197
463e8aa9 198The B<SelfLoader> exports the C<AUTOLOAD> subroutine to the
199package using the B<SelfLoader>, and this loads the called
f8881bd9
AD
200subroutine when it is first called.
201
202There is no advantage to putting subroutines which will _always_
463e8aa9 203be called after the C<__DATA__> token.
f8881bd9
AD
204
205=head2 Autoloading and package lexicals
206
207A 'my $pack_lexical' statement makes the variable $pack_lexical
463e8aa9 208local _only_ to the file up to the C<__DATA__> token. Subroutines
f8881bd9
AD
209declared elsewhere _cannot_ see these types of variables,
210just as if you declared subroutines in the package but in another
211file, they cannot see these variables.
212
213So specifically, autoloaded functions cannot see package
463e8aa9 214lexicals (this applies to both the B<SelfLoader> and the Autoloader).
215The C<vars> pragma provides an alternative to defining package-level
216globals that will be visible to autoloaded routines. See the documentation
217on B<vars> in the pragma section of L<perlmod>.
f8881bd9
AD
218
219=head2 SelfLoader and AutoLoader
220
463e8aa9 221The B<SelfLoader> can replace the AutoLoader - just change 'use AutoLoader'
222to 'use SelfLoader' (though note that the B<SelfLoader> exports
f8881bd9
AD
223the AUTOLOAD function - but if you have your own AUTOLOAD and
224are using the AutoLoader too, you probably know what you're doing),
463e8aa9 225and the C<__END__> token to C<__DATA__>. You will need perl version 5.001m
f8881bd9
AD
226or later to use this (version 5.001 with all patches up to patch m).
227
463e8aa9 228There is no need to inherit from the B<SelfLoader>.
f8881bd9 229
463e8aa9 230The B<SelfLoader> works similarly to the AutoLoader, but picks up the
231subs from after the C<__DATA__> instead of in the 'lib/auto' directory.
f610777f 232There is a maintenance gain in not needing to run AutoSplit on the module
f8881bd9
AD
233at installation, and a runtime gain in not needing to keep opening and
234closing files to load subs. There is a runtime loss in needing
463e8aa9 235to parse the code after the C<__DATA__>. Details of the B<AutoLoader> and
236another view of these distinctions can be found in that module's
237documentation.
f8881bd9
AD
238
239=head2 __DATA__, __END__, and the FOOBAR::DATA filehandle.
240
241This section is only relevant if you want to use
463e8aa9 242the C<FOOBAR::DATA> together with the B<SelfLoader>.
243
244Data after the C<__DATA__> token in a module is read using the
245FOOBAR::DATA filehandle. C<__END__> can still be used to denote the end
246of the C<__DATA__> section if followed by the token DATA - this is supported
247by the B<SelfLoader>. The C<FOOBAR::DATA> filehandle is left open if an
248C<__END__> followed by a DATA is found, with the filehandle positioned at
249the start of the line after the C<__END__> token. If no C<__END__> token is
250present, or an C<__END__> token with no DATA token on the same line, then
251the filehandle is closed.
252
253The B<SelfLoader> reads from wherever the current
254position of the C<FOOBAR::DATA> filehandle is, until the
255EOF or C<__END__>. This means that if you want to use
f8881bd9
AD
256that filehandle (and ONLY if you want to), you should either
257
2581. Put all your subroutine declarations immediately after
463e8aa9 259the C<__DATA__> token and put your own data after those
260declarations, using the C<__END__> token to mark the end
261of subroutine declarations. You must also ensure that the B<SelfLoader>
1fef88e7 262reads first by calling 'SelfLoader-E<gt>load_stubs();', or by using a
f8881bd9
AD
263function which is selfloaded;
264
265or
266
463e8aa9 2672. You should read the C<FOOBAR::DATA> filehandle first, leaving
f8881bd9
AD
268the handle open and positioned at the first line of subroutine
269declarations.
270
271You could conceivably do both.
272
273=head2 Classes and inherited methods.
274
275For modules which are not classes, this section is not relevant.
276This section is only relevant if you have methods which could
277be inherited.
278
279A subroutine stub (or forward declaration) looks like
280
281 sub stub;
282
283i.e. it is a subroutine declaration without the body of the
284subroutine. For modules which are not classes, there is no real
285need for stubs as far as autoloading is concerned.
286
287For modules which ARE classes, and need to handle inherited methods,
288stubs are needed to ensure that the method inheritance mechanism works
289properly. You can load the stubs into the module at 'require' time, by
1fef88e7 290adding the statement 'SelfLoader-E<gt>load_stubs();' to the module to do
f8881bd9
AD
291this.
292
463e8aa9 293The alternative is to put the stubs in before the C<__DATA__> token BEFORE
294releasing the module, and for this purpose the C<Devel::SelfStubber>
f8881bd9
AD
295module is available. However this does require the extra step of ensuring
296that the stubs are in the module. If this is done I strongly recommend
297that this is done BEFORE releasing the module - it should NOT be done
298at install time in general.
299
300=head1 Multiple packages and fully qualified subroutine names
301
302Subroutines in multiple packages within the same file are supported - but you
463e8aa9 303should note that this requires exporting the C<SelfLoader::AUTOLOAD> to
f8881bd9 304every package which requires it. This is done automatically by the
463e8aa9 305B<SelfLoader> when it first loads the subs into the cache, but you should
306really specify it in the initialization before the C<__DATA__> by putting
f8881bd9
AD
307a 'use SelfLoader' statement in each package.
308
309Fully qualified subroutine names are also supported. For example,
310
311 __DATA__
312 sub foo::bar {23}
313 package baz;
314 sub dob {32}
315
463e8aa9 316will all be loaded correctly by the B<SelfLoader>, and the B<SelfLoader>
f8881bd9 317will ensure that the packages 'foo' and 'baz' correctly have the
463e8aa9 318B<SelfLoader> C<AUTOLOAD> method when the data after C<__DATA__> is first
319parsed.
f8881bd9
AD
320
321=cut