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