This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
[perl #41587] [PATCH] 5.8.8 make sure we get the proper ldflags on libperl.so
[perl5.git] / lib / AutoSplit.pm
1 package AutoSplit;
2
3 use 5.009005; # due to "my $_" and new regexp features
4 use Exporter ();
5 use Config qw(%Config);
6 use File::Basename ();
7 use File::Path qw(mkpath);
8 use File::Spec::Functions qw(curdir catfile catdir);
9 use strict;
10 our($VERSION, @ISA, @EXPORT, @EXPORT_OK, $Verbose, $Keep, $Maxlen,
11     $CheckForAutoloader, $CheckModTime);
12
13 $VERSION = "1.05";
14 @ISA = qw(Exporter);
15 @EXPORT = qw(&autosplit &autosplit_lib_modules);
16 @EXPORT_OK = qw($Verbose $Keep $Maxlen $CheckForAutoloader $CheckModTime);
17
18 =head1 NAME
19
20 AutoSplit - split a package for autoloading
21
22 =head1 SYNOPSIS
23
24  autosplit($file, $dir, $keep, $check, $modtime);
25
26  autosplit_lib_modules(@modules);
27
28 =head1 DESCRIPTION
29
30 This function will split up your program into files that the AutoLoader
31 module can handle. It is used by both the standard perl libraries and by
32 the MakeMaker utility, to automatically configure libraries for autoloading.
33
34 The C<autosplit> interface splits the specified file into a hierarchy 
35 rooted at the directory C<$dir>. It creates directories as needed to reflect
36 class hierarchy, and creates the file F<autosplit.ix>. This file acts as
37 both forward declaration of all package routines, and as timestamp for the
38 last update of the hierarchy.
39
40 The remaining three arguments to C<autosplit> govern other options to
41 the autosplitter.
42
43 =over 2
44
45 =item $keep
46
47 If the third argument, I<$keep>, is false, then any
48 pre-existing C<*.al> files in the autoload directory are removed if
49 they are no longer part of the module (obsoleted functions).
50 $keep defaults to 0.
51
52 =item $check
53
54 The
55 fourth argument, I<$check>, instructs C<autosplit> to check the module
56 currently being split to ensure that it includes a C<use>
57 specification for the AutoLoader module, and skips the module if
58 AutoLoader is not detected.
59 $check defaults to 1.
60
61 =item $modtime
62
63 Lastly, the I<$modtime> argument specifies
64 that C<autosplit> is to check the modification time of the module
65 against that of the C<autosplit.ix> file, and only split the module if
66 it is newer.
67 $modtime defaults to 1.
68
69 =back
70
71 Typical use of AutoSplit in the perl MakeMaker utility is via the command-line
72 with:
73
74  perl -e 'use AutoSplit; autosplit($ARGV[0], $ARGV[1], 0, 1, 1)'
75
76 Defined as a Make macro, it is invoked with file and directory arguments;
77 C<autosplit> will split the specified file into the specified directory and
78 delete obsolete C<.al> files, after checking first that the module does use
79 the AutoLoader, and ensuring that the module is not already currently split
80 in its current form (the modtime test).
81
82 The C<autosplit_lib_modules> form is used in the building of perl. It takes
83 as input a list of files (modules) that are assumed to reside in a directory
84 B<lib> relative to the current directory. Each file is sent to the 
85 autosplitter one at a time, to be split into the directory B<lib/auto>.
86
87 In both usages of the autosplitter, only subroutines defined following the
88 perl I<__END__> token are split out into separate files. Some
89 routines may be placed prior to this marker to force their immediate loading
90 and parsing.
91
92 =head2 Multiple packages
93
94 As of version 1.01 of the AutoSplit module it is possible to have
95 multiple packages within a single file. Both of the following cases
96 are supported:
97
98    package NAME;
99    __END__
100    sub AAA { ... }
101    package NAME::option1;
102    sub BBB { ... }
103    package NAME::option2;
104    sub BBB { ... }
105
106    package NAME;
107    __END__
108    sub AAA { ... }
109    sub NAME::option1::BBB { ... }
110    sub NAME::option2::BBB { ... }
111
112 =head1 DIAGNOSTICS
113
114 C<AutoSplit> will inform the user if it is necessary to create the
115 top-level directory specified in the invocation. It is preferred that
116 the script or installation process that invokes C<AutoSplit> have
117 created the full directory path ahead of time. This warning may
118 indicate that the module is being split into an incorrect path.
119
120 C<AutoSplit> will warn the user of all subroutines whose name causes
121 potential file naming conflicts on machines with drastically limited
122 (8 characters or less) file name length. Since the subroutine name is
123 used as the file name, these warnings can aid in portability to such
124 systems.
125
126 Warnings are issued and the file skipped if C<AutoSplit> cannot locate
127 either the I<__END__> marker or a "package Name;"-style specification.
128
129 C<AutoSplit> will also emit general diagnostics for inability to
130 create directories or files.
131
132 =cut
133
134 # for portability warn about names longer than $maxlen
135 $Maxlen  = 8;   # 8 for dos, 11 (14-".al") for SYSVR3
136 $Verbose = 1;   # 0=none, 1=minimal, 2=list .al files
137 $Keep    = 0;
138 $CheckForAutoloader = 1;
139 $CheckModTime = 1;
140
141 my $IndexFile = "autosplit.ix"; # file also serves as timestamp
142 my $maxflen = 255;
143 $maxflen = 14 if $Config{'d_flexfnam'} ne 'define';
144 if (defined (&Dos::UseLFN)) {
145      $maxflen = Dos::UseLFN() ? 255 : 11;
146 }
147 my $Is_VMS = ($^O eq 'VMS');
148
149 # allow checking for valid ': attrlist' attachments
150
151 my $attr_list = qr{
152     \s* : \s*
153     (?:
154         # one attribute
155         (?> # no backtrack
156             (?! \d) \w+
157             (?<nested> \( (?: [^()]++ | (?&nested)++ )*+ \) ) ?
158         )
159         (?: \s* : \s* | \s+ (?! :) )
160     )*
161 }x;
162
163 sub autosplit{
164     my($file, $autodir,  $keep, $ckal, $ckmt) = @_;
165     # $file    - the perl source file to be split (after __END__)
166     # $autodir - the ".../auto" dir below which to write split subs
167     # Handle optional flags:
168     $keep = $Keep unless defined $keep;
169     $ckal = $CheckForAutoloader unless defined $ckal;
170     $ckmt = $CheckModTime unless defined $ckmt;
171     autosplit_file($file, $autodir, $keep, $ckal, $ckmt);
172 }
173
174 sub carp{
175     require Carp;
176     goto &Carp::carp;
177 }
178
179 # This function is used during perl building/installation
180 # ./miniperl -e 'use AutoSplit; autosplit_lib_modules(@ARGV)' ...
181
182 sub autosplit_lib_modules {
183     my(@modules) = @_; # list of Module names
184
185     while (defined(my $_ = shift @modules)) {
186         while (m#([^:]+)::([^:].*)#) { # in case specified as ABC::XYZ
187             $_ = catfile($1, $2);
188         }
189         s|\\|/|g;               # bug in ksh OS/2
190         s#^lib/##s; # incase specified as lib/*.pm
191         my($lib) = catfile(curdir(), "lib");
192         if ($Is_VMS) { # may need to convert VMS-style filespecs
193             $lib =~ s#^\[\]#.\/#;
194         }
195         s#^$lib\W+##s; # incase specified as ./lib/*.pm
196         if ($Is_VMS && /[:>\]]/) { # may need to convert VMS-style filespecs
197             my ($dir,$name) = (/(.*])(.*)/s);
198             $dir =~ s/.*lib[\.\]]//s;
199             $dir =~ s#[\.\]]#/#g;
200             $_ = $dir . $name;
201         }
202         autosplit_file(catfile($lib, $_), catfile($lib, "auto"),
203                        $Keep, $CheckForAutoloader, $CheckModTime);
204     }
205     0;
206 }
207
208
209 # private functions
210
211 my $self_mod_time = (stat __FILE__)[9];
212
213 sub autosplit_file {
214     my($filename, $autodir, $keep, $check_for_autoloader, $check_mod_time)
215         = @_;
216     my(@outfiles);
217     local($_);
218     local($/) = "\n";
219
220     # where to write output files
221     $autodir ||= catfile(curdir(), "lib", "auto");
222     if ($Is_VMS) {
223         ($autodir = VMS::Filespec::unixpath($autodir)) =~ s|/\z||;
224         $filename = VMS::Filespec::unixify($filename); # may have dirs
225     }
226     unless (-d $autodir){
227         mkpath($autodir,0,0755);
228         # We should never need to create the auto dir
229         # here. installperl (or similar) should have done
230         # it. Expecting it to exist is a valuable sanity check against
231         # autosplitting into some random directory by mistake.
232         print "Warning: AutoSplit had to create top-level " .
233             "$autodir unexpectedly.\n";
234     }
235
236     # allow just a package name to be used
237     $filename .= ".pm" unless ($filename =~ m/\.pm\z/);
238
239     open(my $in, "<$filename") or die "AutoSplit: Can't open $filename: $!\n";
240     my($pm_mod_time) = (stat($filename))[9];
241     my($autoloader_seen) = 0;
242     my($in_pod) = 0;
243     my($def_package,$last_package,$this_package,$fnr);
244     while (<$in>) {
245         # Skip pod text.
246         $fnr++;
247         $in_pod = 1 if /^=\w/;
248         $in_pod = 0 if /^=cut/;
249         next if ($in_pod || /^=cut/);
250         next if /^\s*#/;
251
252         # record last package name seen
253         $def_package = $1 if (m/^\s*package\s+([\w:]+)\s*;/);
254         ++$autoloader_seen if m/^\s*(use|require)\s+AutoLoader\b/;
255         ++$autoloader_seen if m/\bISA\s*=.*\bAutoLoader\b/;
256         last if /^__END__/;
257     }
258     if ($check_for_autoloader && !$autoloader_seen){
259         print "AutoSplit skipped $filename: no AutoLoader used\n"
260             if ($Verbose>=2);
261         return 0;
262     }
263     $_ or die "Can't find __END__ in $filename\n";
264
265     $def_package or die "Can't find 'package Name;' in $filename\n";
266
267     my($modpname) = _modpname($def_package); 
268
269     # this _has_ to match so we have a reasonable timestamp file
270     die "Package $def_package ($modpname.pm) does not ".
271         "match filename $filename"
272             unless ($filename =~ m/\Q$modpname.pm\E$/ or
273                     ($^O eq 'dos') or ($^O eq 'MSWin32') or ($^O eq 'NetWare') or
274                     $Is_VMS && $filename =~ m/$modpname.pm/i);
275
276     my($al_idx_file) = catfile($autodir, $modpname, $IndexFile);
277
278     if ($check_mod_time){
279         my($al_ts_time) = (stat("$al_idx_file"))[9] || 1;
280         if ($al_ts_time >= $pm_mod_time and
281             $al_ts_time >= $self_mod_time){
282             print "AutoSplit skipped ($al_idx_file newer than $filename)\n"
283                 if ($Verbose >= 2);
284             return undef;       # one undef, not a list
285         }
286     }
287
288     my($modnamedir) = catdir($autodir, $modpname);
289     print "AutoSplitting $filename ($modnamedir)\n"
290         if $Verbose;
291
292     unless (-d $modnamedir){
293         mkpath($modnamedir,0,0777);
294     }
295
296     # We must try to deal with some SVR3 systems with a limit of 14
297     # characters for file names. Sadly we *cannot* simply truncate all
298     # file names to 14 characters on these systems because we *must*
299     # create filenames which exactly match the names used by AutoLoader.pm.
300     # This is a problem because some systems silently truncate the file
301     # names while others treat long file names as an error.
302
303     my $Is83 = $maxflen==11;  # plain, case INSENSITIVE dos filenames
304
305     my(@subnames, $subname, %proto, %package);
306     my @cache = ();
307     my $caching = 1;
308     $last_package = '';
309     my $out;
310     while (<$in>) {
311         $fnr++;
312         $in_pod = 1 if /^=\w/;
313         $in_pod = 0 if /^=cut/;
314         next if ($in_pod || /^=cut/);
315         # the following (tempting) old coding gives big troubles if a
316         # cut is forgotten at EOF:
317         # next if /^=\w/ .. /^=cut/;
318         if (/^package\s+([\w:]+)\s*;/) {
319             $this_package = $def_package = $1;
320         }
321
322         if (/^sub\s+([\w:]+)(\s*(?:\(.*?\))?(?:$attr_list)?)/) {
323             print $out "# end of $last_package\::$subname\n1;\n"
324                 if $last_package;
325             $subname = $1;
326             my $proto = $2 || '';
327             if ($subname =~ s/(.*):://){
328                 $this_package = $1;
329             } else {
330                 $this_package = $def_package;
331             }
332             my $fq_subname = "$this_package\::$subname";
333             $package{$fq_subname} = $this_package;
334             $proto{$fq_subname} = $proto;
335             push(@subnames, $fq_subname);
336             my($lname, $sname) = ($subname, substr($subname,0,$maxflen-3));
337             $modpname = _modpname($this_package);
338             my($modnamedir) = catdir($autodir, $modpname);
339             mkpath($modnamedir,0,0777);
340             my($lpath) = catfile($modnamedir, "$lname.al");
341             my($spath) = catfile($modnamedir, "$sname.al");
342             my $path;
343
344             if (!$Is83 and open($out, ">$lpath")){
345                 $path=$lpath;
346                 print "  writing $lpath\n" if ($Verbose>=2);
347             } else {
348                 open($out, ">$spath") or die "Can't create $spath: $!\n";
349                 $path=$spath;
350                 print "  writing $spath (with truncated name)\n"
351                         if ($Verbose>=1);
352             }
353             push(@outfiles, $path);
354             my $lineno = $fnr - @cache;
355             print $out <<EOT;
356 # NOTE: Derived from $filename.
357 # Changes made here will be lost when autosplit is run again.
358 # See AutoSplit.pm.
359 package $this_package;
360
361 #line $lineno "$filename (autosplit into $path)"
362 EOT
363             print $out @cache;
364             @cache = ();
365             $caching = 0;
366         }
367         if($caching) {
368             push(@cache, $_) if @cache || /\S/;
369         } else {
370             print $out $_;
371         }
372         if(/^\}/) {
373             if($caching) {
374                 print $out @cache;
375                 @cache = ();
376             }
377             print $out "\n";
378             $caching = 1;
379         }
380         $last_package = $this_package if defined $this_package;
381     }
382     if ($subname) {
383         print $out @cache,"1;\n# end of $last_package\::$subname\n";
384         close($out);
385     }
386     close($in);
387     
388     if (!$keep){  # don't keep any obsolete *.al files in the directory
389         my(%outfiles);
390         # @outfiles{@outfiles} = @outfiles;
391         # perl downcases all filenames on VMS (which upcases all filenames) so
392         # we'd better downcase the sub name list too, or subs with upper case
393         # letters in them will get their .al files deleted right after they're
394         # created. (The mixed case sub name won't match the all-lowercase
395         # filename, and so be cleaned up as a scrap file)
396         if ($Is_VMS or $Is83) {
397             %outfiles = map {lc($_) => lc($_) } @outfiles;
398         } else {
399             @outfiles{@outfiles} = @outfiles;
400         }  
401         my(%outdirs,@outdirs);
402         for (@outfiles) {
403             $outdirs{File::Basename::dirname($_)}||=1;
404         }
405         for my $dir (keys %outdirs) {
406             opendir(my $outdir,$dir);
407             foreach (sort readdir($outdir)){
408                 next unless /\.al\z/;
409                 my($file) = catfile($dir, $_);
410                 $file = lc $file if $Is83 or $Is_VMS;
411                 next if $outfiles{$file};
412                 print "  deleting $file\n" if ($Verbose>=2);
413                 my($deleted,$thistime);  # catch all versions on VMS
414                 do { $deleted += ($thistime = unlink $file) } while ($thistime);
415                 carp ("Unable to delete $file: $!") unless $deleted;
416             }
417             closedir($outdir);
418         }
419     }
420
421     open(my $ts,">$al_idx_file") or
422         carp ("AutoSplit: unable to create timestamp file ($al_idx_file): $!");
423     print $ts "# Index created by AutoSplit for $filename\n";
424     print $ts "#    (file acts as timestamp)\n";
425     $last_package = '';
426     for my $fqs (@subnames) {
427         my($subname) = $fqs;
428         $subname =~ s/.*:://;
429         print $ts "package $package{$fqs};\n"
430             unless $last_package eq $package{$fqs};
431         print $ts "sub $subname $proto{$fqs};\n";
432         $last_package = $package{$fqs};
433     }
434     print $ts "1;\n";
435     close($ts);
436
437     _check_unique($filename, $Maxlen, 1, @outfiles);
438
439     @outfiles;
440 }
441
442 sub _modpname ($) {
443     my($package) = @_;
444     my $modpname = $package;
445     if ($^O eq 'MSWin32') {
446         $modpname =~ s#::#\\#g; 
447     } else {
448         my @modpnames = ();
449         while ($modpname =~ m#(.*?[^:])::([^:].*)#) {
450                push @modpnames, $1;
451                $modpname = $2;
452          }
453         $modpname = catfile(@modpnames, $modpname);
454     }
455     if ($Is_VMS) {
456         $modpname = VMS::Filespec::unixify($modpname); # may have dirs
457     }
458     $modpname;
459 }
460
461 sub _check_unique {
462     my($filename, $maxlen, $warn, @outfiles) = @_;
463     my(%notuniq) = ();
464     my(%shorts)  = ();
465     my(@toolong) = grep(
466                         length(File::Basename::basename($_))
467                         > $maxlen,
468                         @outfiles
469                        );
470
471     foreach (@toolong){
472         my($dir) = File::Basename::dirname($_);
473         my($file) = File::Basename::basename($_);
474         my($trunc) = substr($file,0,$maxlen);
475         $notuniq{$dir}{$trunc} = 1 if $shorts{$dir}{$trunc};
476         $shorts{$dir}{$trunc} = $shorts{$dir}{$trunc} ?
477             "$shorts{$dir}{$trunc}, $file" : $file;
478     }
479     if (%notuniq && $warn){
480         print "$filename: some names are not unique when " .
481             "truncated to $maxlen characters:\n";
482         foreach my $dir (sort keys %notuniq){
483             print " directory $dir:\n";
484             foreach my $trunc (sort keys %{$notuniq{$dir}}) {
485                 print "  $shorts{$dir}{$trunc} truncate to $trunc\n";
486             }
487         }
488     }
489 }
490
491 1;
492 __END__
493
494 # test functions so AutoSplit.pm can be applied to itself:
495 sub test1 ($)   { "test 1\n"; }
496 sub test2 ($$)  { "test 2\n"; }
497 sub test3 ($$$) { "test 3\n"; }
498 sub testtesttesttest4_1  { "test 4\n"; }
499 sub testtesttesttest4_2  { "duplicate test 4\n"; }
500 sub Just::Another::test5 { "another test 5\n"; }
501 sub test6       { return join ":", __FILE__,__LINE__; }
502 package Yet::Another::AutoSplit;
503 sub testtesttesttest4_1 ($)  { "another test 4\n"; }
504 sub testtesttesttest4_2 ($$) { "another duplicate test 4\n"; }
505 package Yet::More::Attributes;
506 sub test_a1 ($) : locked :locked { 1; }
507 sub test_a2 : locked { 1; }