fix for Exporter's $SIG{__WARN__} handler
[p5sagit/p5-mst-13.2.git] / lib / Exporter.pm
1 package Exporter;
2
3 require 5.001;
4
5 $ExportLevel = 0;
6 $Verbose = 0 unless $Verbose;
7
8 require Carp;
9
10 sub export {
11
12     # First make import warnings look like they're coming from the "use".
13     local $SIG{__WARN__} = sub {
14         my $text = shift;
15         if ($text =~ s/ at \S*Exporter.pm line \d+.*\n//) {
16             local $Carp::CarpLevel = 1; # ignore package calling us too.
17             Carp::carp($text);
18         }
19         else {
20             warn $text;
21         }
22     };
23     local $SIG{__DIE__} = sub {
24         Carp::croak("$_[0]Illegal null symbol in \@${1}::EXPORT")
25             if $_[0] =~ /^Unable to create sub named "(.*?)::"/;
26     };
27
28     my($pkg, $callpkg, @imports) = @_;
29     my($type, $sym, $oops);
30     *exports = *{"${pkg}::EXPORT"};
31
32     if (@imports) {
33         if (!%exports) {
34             grep(s/^&//, @exports);
35             @exports{@exports} = (1) x @exports;
36             my $ok = \@{"${pkg}::EXPORT_OK"};
37             if (@$ok) {
38                 grep(s/^&//, @$ok);
39                 @exports{@$ok} = (1) x @$ok;
40             }
41         }
42
43         if ($imports[0] =~ m#^[/!:]#){
44             my $tagsref = \%{"${pkg}::EXPORT_TAGS"};
45             my $tagdata;
46             my %imports;
47             my($remove, $spec, @names, @allexports);
48             # negated first item implies starting with default set:
49             unshift @imports, ':DEFAULT' if $imports[0] =~ m/^!/;
50             foreach $spec (@imports){
51                 $remove = $spec =~ s/^!//;
52
53                 if ($spec =~ s/^://){
54                     if ($spec eq 'DEFAULT'){
55                         @names = @exports;
56                     }
57                     elsif ($tagdata = $tagsref->{$spec}) {
58                         @names = @$tagdata;
59                     }
60                     else {
61                         warn qq["$spec" is not defined in %${pkg}::EXPORT_TAGS];
62                         ++$oops;
63                         next;
64                     }
65                 }
66                 elsif ($spec =~ m:^/(.*)/$:){
67                     my $patn = $1;
68                     @allexports = keys %exports unless @allexports; # only do keys once
69                     @names = grep(/$patn/, @allexports); # not anchored by default
70                 }
71                 else {
72                     @names = ($spec); # is a normal symbol name
73                 }
74
75                 warn "Import ".($remove ? "del":"add").": @names "
76                     if $Verbose;
77
78                 if ($remove) {
79                    foreach $sym (@names) { delete $imports{$sym} } 
80                 }
81                 else {
82                     @imports{@names} = (1) x @names;
83                 }
84             }
85             @imports = keys %imports;
86         }
87
88         foreach $sym (@imports) {
89             if (!$exports{$sym}) {
90                 if ($sym =~ m/^\d/) {
91                     $pkg->require_version($sym);
92                     # If the version number was the only thing specified
93                     # then we should act as if nothing was specified:
94                     if (@imports == 1) {
95                         @imports = @exports;
96                         last;
97                     }
98                     # We need a way to emulate 'use Foo ()' but still
99                     # allow an easy version check: "use Foo 1.23, ''";
100                     if (@imports == 2 and !$imports[1]) {
101                         @imports = ();
102                         last;
103                     }
104                 } elsif ($sym !~ s/^&// || !$exports{$sym}) {
105                     warn qq["$sym" is not exported by the $pkg module];
106                     $oops++;
107                 }
108             }
109         }
110         Carp::croak("Can't continue after import errors") if $oops;
111     }
112     else {
113         @imports = @exports;
114     }
115
116     *fail = *{"${pkg}::EXPORT_FAIL"};
117     if (@fail) {
118         if (!%fail) {
119             # Build cache of symbols. Optimise the lookup by adding
120             # barewords twice... both with and without a leading &.
121             # (Technique could be applied to %exports cache at cost of memory)
122             my @expanded = map { /^\w/ ? ($_, '&'.$_) : $_ } @fail;
123             warn "${pkg}::EXPORT_FAIL cached: @expanded" if $Verbose;
124             @fail{@expanded} = (1) x @expanded;
125         }
126         my @failed;
127         foreach $sym (@imports) { push(@failed, $sym) if $fail{$sym} }
128         if (@failed) {
129             @failed = $pkg->export_fail(@failed);
130             foreach $sym (@failed) {
131                 warn qq["$sym" is not implemented by the $pkg module ],
132                         "on this architecture";
133             }
134             Carp::croak("Can't continue after import errors") if @failed;
135         }
136     }
137
138     warn "Importing into $callpkg from $pkg: ",
139                 join(", ",sort @imports) if $Verbose;
140
141     foreach $sym (@imports) {
142         # shortcut for the common case of no type character
143         (*{"${callpkg}::$sym"} = \&{"${pkg}::$sym"}, next)
144             unless $sym =~ s/^(\W)//;
145         $type = $1;
146         *{"${callpkg}::$sym"} =
147             $type eq '&' ? \&{"${pkg}::$sym"} :
148             $type eq '$' ? \${"${pkg}::$sym"} :
149             $type eq '@' ? \@{"${pkg}::$sym"} :
150             $type eq '%' ? \%{"${pkg}::$sym"} :
151             $type eq '*' ?  *{"${pkg}::$sym"} :
152                 Carp::croak("Can't export symbol: $type$sym");
153     }
154 }
155
156 sub import {
157     my $pkg = shift;
158     my $callpkg = caller($ExportLevel);
159     export $pkg, $callpkg, @_;
160 }
161
162
163 # Utility functions
164
165 sub _push_tags {
166     my($pkg, $var, $syms) = @_;
167     my $nontag;
168     *export_tags = \%{"${pkg}::EXPORT_TAGS"};
169     push(@{"${pkg}::$var"},
170         map { $export_tags{$_} ? @{$export_tags{$_}} : scalar(++$nontag,$_) }
171                 (@$syms) ? @$syms : keys %export_tags);
172     # This may change to a die one day
173     Carp::carp("Some names are not tags") if $nontag and $^W;
174 }
175
176 sub export_tags    { _push_tags((caller)[0], "EXPORT",    \@_) }
177 sub export_ok_tags { _push_tags((caller)[0], "EXPORT_OK", \@_) }
178
179
180 # Default methods
181
182 sub export_fail {
183     my $self = shift;
184     @_;
185 }
186
187 sub require_version {
188     my($self, $wanted) = @_;
189     my $pkg = ref $self || $self;
190     my $version = ${"${pkg}::VERSION"};
191     if (!$version or $version < $wanted) {
192         $version ||= "(undef)";
193         my $file = $INC{"$pkg.pm"};
194         $file &&= " ($file)";
195         Carp::croak("$pkg $wanted required--this is only version $version$file")
196     }
197     $version;
198 }
199
200 1;
201
202 # A simple self test harness. Change 'require Carp' to 'use Carp ()' for testing.
203 # package main; eval(join('',<DATA>)) or die $@ unless caller;
204 __END__
205 package Test;
206 $INC{'Exporter.pm'} = 1;
207 @ISA = qw(Exporter);
208 @EXPORT      = qw(A1 A2 A3 A4 A5);
209 @EXPORT_OK   = qw(B1 B2 B3 B4 B5);
210 %EXPORT_TAGS = (T1=>[qw(A1 A2 B1 B2)], T2=>[qw(A1 A2 B3 B4)], T3=>[qw(X3)]);
211 @EXPORT_FAIL = qw(B4);
212 Exporter::export_ok_tags('T3', 'unknown_tag');
213 sub export_fail {
214     map { "Test::$_" } @_       # edit symbols just as an example
215 }
216
217 package main;
218 $Exporter::Verbose = 1;
219 #import Test;
220 #import Test qw(X3);            # export ok via export_ok_tags()
221 #import Test qw(:T1 !A2 /5/ !/3/ B5);
222 import Test qw(:T2 !B4);
223 import Test qw(:T2);            # should fail
224 1;
225
226 =head1 NAME
227
228 Exporter - Implements default import method for modules
229
230 =head1 SYNOPSIS
231
232 In module ModuleName.pm:
233
234   package ModuleName;
235   require Exporter;
236   @ISA = qw(Exporter);
237
238   @EXPORT = qw(...);            # symbols to export by default
239   @EXPORT_OK = qw(...);         # symbols to export on request
240   %EXPORT_TAGS = tag => [...];  # define names for sets of symbols
241
242 In other files which wish to use ModuleName:
243
244   use ModuleName;               # import default symbols into my package
245
246   use ModuleName qw(...);       # import listed symbols into my package
247
248   use ModuleName ();            # do not import any symbols
249
250 =head1 DESCRIPTION
251
252 The Exporter module implements a default C<import> method which
253 many modules choose to inherit rather than implement their own.
254
255 Perl automatically calls the C<import> method when processing a
256 C<use> statement for a module. Modules and C<use> are documented
257 in L<perlfunc> and L<perlmod>. Understanding the concept of
258 modules and how the C<use> statement operates is important to
259 understanding the Exporter.
260
261 =head2 Selecting What To Export
262
263 Do B<not> export method names!
264
265 Do B<not> export anything else by default without a good reason!
266
267 Exports pollute the namespace of the module user.  If you must export
268 try to use @EXPORT_OK in preference to @EXPORT and avoid short or
269 common symbol names to reduce the risk of name clashes.
270
271 Generally anything not exported is still accessible from outside the
272 module using the ModuleName::item_name (or $blessed_ref-E<gt>method)
273 syntax.  By convention you can use a leading underscore on names to
274 informally indicate that they are 'internal' and not for public use.
275
276 (It is actually possible to get private functions by saying:
277
278   my $subref = sub { ... };
279   &$subref;
280
281 But there's no way to call that directly as a method, since a method
282 must have a name in the symbol table.)
283
284 As a general rule, if the module is trying to be object oriented
285 then export nothing. If it's just a collection of functions then
286 @EXPORT_OK anything but use @EXPORT with caution.
287
288 Other module design guidelines can be found in L<perlmod>.
289
290 =head2 Specialised Import Lists
291
292 If the first entry in an import list begins with !, : or / then the
293 list is treated as a series of specifications which either add to or
294 delete from the list of names to import. They are processed left to
295 right. Specifications are in the form:
296
297     [!]name         This name only
298     [!]:DEFAULT     All names in @EXPORT
299     [!]:tag         All names in $EXPORT_TAGS{tag} anonymous list
300     [!]/pattern/    All names in @EXPORT and @EXPORT_OK which match
301
302 A leading ! indicates that matching names should be deleted from the
303 list of names to import.  If the first specification is a deletion it
304 is treated as though preceded by :DEFAULT. If you just want to import
305 extra names in addition to the default set you will still need to
306 include :DEFAULT explicitly.
307
308 e.g., Module.pm defines:
309
310     @EXPORT      = qw(A1 A2 A3 A4 A5);
311     @EXPORT_OK   = qw(B1 B2 B3 B4 B5);
312     %EXPORT_TAGS = (T1 => [qw(A1 A2 B1 B2)], T2 => [qw(A1 A2 B3 B4)]);
313
314     Note that you cannot use tags in @EXPORT or @EXPORT_OK.
315     Names in EXPORT_TAGS must also appear in @EXPORT or @EXPORT_OK.
316
317 An application using Module can say something like:
318
319     use Module qw(:DEFAULT :T2 !B3 A3);
320
321 Other examples include:
322
323     use Socket qw(!/^[AP]F_/ !SOMAXCONN !SOL_SOCKET);
324     use POSIX  qw(:errno_h :termios_h !TCSADRAIN !/^EXIT/);
325
326 Remember that most patterns (using //) will need to be anchored
327 with a leading ^, e.g., C</^EXIT/> rather than C</EXIT/>.
328
329 You can say C<BEGIN { $Exporter::Verbose=1 }> to see how the
330 specifications are being processed and what is actually being imported
331 into modules.
332
333 =head2 Module Version Checking
334
335 The Exporter module will convert an attempt to import a number from a
336 module into a call to $module_name-E<gt>require_version($value). This can
337 be used to validate that the version of the module being used is
338 greater than or equal to the required version.
339
340 The Exporter module supplies a default require_version method which
341 checks the value of $VERSION in the exporting module.
342
343 Since the default require_version method treats the $VERSION number as
344 a simple numeric value it will regard version 1.10 as lower than
345 1.9. For this reason it is strongly recommended that you use numbers
346 with at least two decimal places, e.g., 1.09.
347
348 =head2 Managing Unknown Symbols
349
350 In some situations you may want to prevent certain symbols from being
351 exported. Typically this applies to extensions which have functions
352 or constants that may not exist on some systems.
353
354 The names of any symbols that cannot be exported should be listed
355 in the C<@EXPORT_FAIL> array.
356
357 If a module attempts to import any of these symbols the Exporter will
358 will give the module an opportunity to handle the situation before
359 generating an error. The Exporter will call an export_fail method
360 with a list of the failed symbols:
361
362   @failed_symbols = $module_name->export_fail(@failed_symbols);
363
364 If the export_fail method returns an empty list then no error is
365 recorded and all the requested symbols are exported. If the returned
366 list is not empty then an error is generated for each symbol and the
367 export fails. The Exporter provides a default export_fail method which
368 simply returns the list unchanged.
369
370 Uses for the export_fail method include giving better error messages
371 for some symbols and performing lazy architectural checks (put more
372 symbols into @EXPORT_FAIL by default and then take them out if someone
373 actually tries to use them and an expensive check shows that they are
374 usable on that platform).
375
376 =head2 Tag Handling Utility Functions
377
378 Since the symbols listed within %EXPORT_TAGS must also appear in either
379 @EXPORT or @EXPORT_OK, two utility functions are provided which allow
380 you to easily add tagged sets of symbols to @EXPORT or @EXPORT_OK:
381
382   %EXPORT_TAGS = (foo => [qw(aa bb cc)], bar => [qw(aa cc dd)]);
383
384   Exporter::export_tags('foo');     # add aa, bb and cc to @EXPORT
385   Exporter::export_ok_tags('bar');  # add aa, cc and dd to @EXPORT_OK
386
387 Any names which are not tags are added to @EXPORT or @EXPORT_OK
388 unchanged but will trigger a warning (with C<-w>) to avoid misspelt tags
389 names being silently added to @EXPORT or @EXPORT_OK. Future versions
390 may make this a fatal error.
391
392 =cut