tests: protect test libs against multiple inclusion
[automake.git] / aclocal.in
blobe8855d554b8504e270bdedb679d5237834c4c2f0
1 #!@PERL@ -w
2 # -*- perl -*-
3 # @configure_input@
5 eval 'case $# in 0) exec @PERL@ -S "$0";; *) exec @PERL@ -S "$0" "$@";; esac'
6     if 0;
8 # aclocal - create aclocal.m4 by scanning configure.ac
10 # Copyright (C) 1996-2012 Free Software Foundation, Inc.
12 # This program is free software; you can redistribute it and/or modify
13 # it under the terms of the GNU General Public License as published by
14 # the Free Software Foundation; either version 2, or (at your option)
15 # any later version.
17 # This program is distributed in the hope that it will be useful,
18 # but WITHOUT ANY WARRANTY; without even the implied warranty of
19 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20 # GNU General Public License for more details.
22 # You should have received a copy of the GNU General Public License
23 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
25 # Written by Tom Tromey <tromey@redhat.com>, and
26 # Alexandre Duret-Lutz <adl@gnu.org>.
28 BEGIN
30   my $perllibdir = $ENV{'perllibdir'} || '@datadir@/@PACKAGE@-@APIVERSION@';
31   unshift @INC, (split '@PATH_SEPARATOR@', $perllibdir);
34 use strict;
36 use Automake::Config;
37 use Automake::General;
38 use Automake::Configure_ac;
39 use Automake::Channels;
40 use Automake::ChannelDefs;
41 use Automake::XFile;
42 use Automake::FileUtils;
43 use File::Basename;
44 use File::Path ();
46 # Some globals.
48 # We do not operate in threaded mode.
49 $perl_threads = 0;
51 # Include paths for searching macros.  We search macros in this order:
52 # user-supplied directories first, then the directory containing the
53 # automake macros, and finally the system-wide directories for
54 # third-party macros.
55 # @user_includes can be augmented with -I.
56 # @automake_includes can be reset with the '--automake-acdir' option.
57 # @system_includes can be augmented with the 'dirlist' file or the
58 # ACLOCAL_PATH environment variable, and reset with the '--system-acdir'
59 # option.
60 my @user_includes = ();
61 my @automake_includes = ("@datadir@/aclocal-$APIVERSION");
62 my @system_includes = ('@datadir@/aclocal');
64 # Whether we should copy M4 file in $user_includes[0].
65 my $install = 0;
67 # --diff
68 my @diff_command;
70 # --dry-run
71 my $dry_run = 0;
73 # configure.ac or configure.in.
74 my $configure_ac;
76 # Output file name.
77 my $output_file = 'aclocal.m4';
79 # Option --force.
80 my $force_output = 0;
82 # Modification time of the youngest dependency.
83 my $greatest_mtime = 0;
85 # Which macros have been seen.
86 my %macro_seen = ();
88 # Remember the order into which we scanned the files.
89 # It's important to output the contents of aclocal.m4 in the opposite order.
90 # (Definitions in first files we have scanned should override those from
91 # later files.  So they must appear last in the output.)
92 my @file_order = ();
94 # Map macro names to file names.
95 my %map = ();
97 # Ditto, but records the last definition of each macro as returned by --trace.
98 my %map_traced_defs = ();
100 # Map basenames to macro names.
101 my %invmap = ();
103 # Map file names to file contents.
104 my %file_contents = ();
106 # Map file names to file types.
107 my %file_type = ();
108 use constant FT_USER => 1;
109 use constant FT_AUTOMAKE => 2;
110 use constant FT_SYSTEM => 3;
112 # Map file names to included files (transitively closed).
113 my %file_includes = ();
115 # Files which have already been added.
116 my %file_added = ();
118 # Files that have already been scanned.
119 my %scanned_configure_dep = ();
121 # Serial numbers, for files that have one.
122 # The key is the basename of the file,
123 # the value is the serial number represented as a list.
124 my %serial = ();
126 # Matches a macro definition.
127 #   AC_DEFUN([macroname], ...)
128 # or
129 #   AC_DEFUN(macroname, ...)
130 # When macroname is '['-quoted , we accept any character in the name,
131 # except ']'.  Otherwise macroname stops on the first ']', ',', ')',
132 # or '\n' encountered.
133 my $ac_defun_rx =
134   "(?:AU_ALIAS|A[CU]_DEFUN|AC_DEFUN_ONCE)\\((?:\\[([^]]+)\\]|([^],)\n]+))";
136 # Matches an AC_REQUIRE line.
137 my $ac_require_rx = "AC_REQUIRE\\((?:\\[([^]]+)\\]|([^],)\n]+))\\)";
139 # Matches an m4_include line.
140 my $m4_include_rx = "(m4_|m4_s|s)include\\((?:\\[([^]]+)\\]|([^],)\n]+))\\)";
142 # Match a serial number.
143 my $serial_line_rx = '^#\s*serial\s+(\S*)';
144 my $serial_number_rx = '^\d+(?:\.\d+)*$';
146 # Autoconf version
147 # Set by trace_used_macros.
148 my $ac_version;
150 # If set, names a temporary file that must be erased on abnormal exit.
151 my $erase_me;
153 ################################################################
155 # Prototypes for all subroutines.
157 sub unlink_tmp (;$);
158 sub xmkdir_p ($);
159 sub check_acinclude ();
160 sub reset_maps ();
161 sub install_file ($$);
162 sub list_compare (\@\@);
163 sub scan_m4_dirs ($@);
164 sub scan_m4_files ();
165 sub add_macro ($);
166 sub scan_configure_dep ($);
167 sub add_file ($);
168 sub scan_file ($$$);
169 sub strip_redundant_includes (%);
170 sub trace_used_macros ();
171 sub scan_configure ();
172 sub write_aclocal ($@);
173 sub usage ($);
174 sub version ();
175 sub handle_acdir_option ($$);
176 sub parse_arguments ();
177 sub parse_ACLOCAL_PATH ();
179 ################################################################
181 # Erase temporary file ERASE_ME.  Handle signals.
182 sub unlink_tmp (;$)
184   my ($sig) = @_;
186   if ($sig)
187     {
188       verb "caught SIG$sig, bailing out";
189     }
190   if (defined $erase_me && -e $erase_me && !unlink ($erase_me))
191     {
192       fatal "could not remove '$erase_me': $!";
193     }
194   undef $erase_me;
196   # reraise default handler.
197   if ($sig)
198     {
199       $SIG{$sig} = 'DEFAULT';
200       kill $sig => $$;
201     }
204 $SIG{'INT'} = $SIG{'TERM'} = $SIG{'QUIT'} = $SIG{'HUP'} = 'unlink_tmp';
205 END { unlink_tmp }
207 sub xmkdir_p ($)
209   my $dir = shift;
210   local $@ = undef;
211   return
212     if -d $dir or eval { File::Path::mkpath $dir };
213   chomp $@;
214   $@ =~ s/\s+at\s.*\bline\s\d+.*$//;
215   fatal "could not create directory '$dir': $@";
218 # Check macros in acinclude.m4.  If one is not used, warn.
219 sub check_acinclude ()
221   foreach my $key (keys %map)
222     {
223       # FIXME: should print line number of acinclude.m4.
224       msg ('syntax', "macro '$key' defined in acinclude.m4 but never used")
225         if $map{$key} eq 'acinclude.m4' && ! exists $macro_seen{$key};
226     }
229 sub reset_maps ()
231   $greatest_mtime = 0;
232   %macro_seen = ();
233   @file_order = ();
234   %map = ();
235   %map_traced_defs = ();
236   %file_contents = ();
237   %file_type = ();
238   %file_includes = ();
239   %file_added = ();
240   %scanned_configure_dep = ();
241   %invmap = ();
242   %serial = ();
243   undef &search;
246 # install_file ($SRC, $DESTDIR)
247 sub install_file ($$)
249   my ($src, $destdir) = @_;
250   my $dest = $destdir . "/" . basename ($src);
251   my $diff_dest;
253   verb "installing $src to $dest";
255   if ($force_output
256       || !exists $file_contents{$dest}
257       || $file_contents{$src} ne $file_contents{$dest})
258     {
259       if (-e $dest)
260         {
261           msg 'note', "overwriting '$dest' with '$src'";
262           $diff_dest = $dest;
263         }
264       else
265         {
266           msg 'note', "installing '$dest' from '$src'";
267         }
269       if (@diff_command)
270         {
271           if (! defined $diff_dest)
272             {
273               # $dest does not exist.  We create an empty one just to
274               # run diff, and we erase it afterward.  Using the real
275               # the destination file (rather than a temporary file) is
276               # good when diff is run with options that display the
277               # file name.
278               #
279               # If creating $dest fails, fall back to /dev/null.  At
280               # least one diff implementation (Tru64's) cannot deal
281               # with /dev/null.  However working around this is not
282               # worth the trouble since nobody run aclocal on a
283               # read-only tree anyway.
284               $erase_me = $dest;
285               my $f = new IO::File "> $dest";
286               if (! defined $f)
287                 {
288                   undef $erase_me;
289                   $diff_dest = '/dev/null';
290                 }
291               else
292                 {
293                   $diff_dest = $dest;
294                   $f->close;
295                 }
296             }
297           my @cmd = (@diff_command, $diff_dest, $src);
298           $! = 0;
299           verb "running: @cmd";
300           my $res = system (@cmd);
301           Automake::FileUtils::handle_exec_errors "@cmd", 1
302             if $res;
303           unlink_tmp;
304         }
305       elsif (!$dry_run)
306         {
307           xmkdir_p ($destdir);
308           xsystem ('cp', $src, $dest);
309         }
310     }
313 # Compare two lists of numbers.
314 sub list_compare (\@\@)
316   my @l = @{$_[0]};
317   my @r = @{$_[1]};
318   while (1)
319     {
320       if (0 == @l)
321         {
322           return (0 == @r) ? 0 : -1;
323         }
324       elsif (0 == @r)
325         {
326           return 1;
327         }
328       elsif ($l[0] < $r[0])
329         {
330           return -1;
331         }
332       elsif ($l[0] > $r[0])
333         {
334           return 1;
335         }
336       shift @l;
337       shift @r;
338     }
341 ################################################################
343 # scan_m4_dirs($TYPE, @DIRS)
344 # --------------------------
345 # Scan all M4 files installed in @DIRS for new macro definitions.
346 # Register each file as of type $TYPE (one of the FT_* constants).
347 my $first_user_m4dir = 1;
348 sub scan_m4_dirs ($@)
350   my ($type, @dirlist) = @_;
352   foreach my $m4dir (@dirlist)
353     {
354       if (! opendir (DIR, $m4dir))
355         {
356           if ($install && $type == FT_USER && $first_user_m4dir)
357             {
358               # We will try to create this directory later, so don't
359               # complain if it doesn't exist.
360               # TODO: maybe we should avoid complaining only if errno
361               # is ENONENT?
362               $first_user_m4dir = 0;
363               next;
364             }
365           fatal "couldn't open directory '$m4dir': $!";
366         }
368       # We reverse the directory contents so that foo2.m4 gets
369       # used in preference to foo1.m4.
370       foreach my $file (reverse sort grep (! /^\./, readdir (DIR)))
371         {
372           # Only examine .m4 files.
373           next unless $file =~ /\.m4$/;
375           # Skip some files when running out of srcdir.
376           next if $file eq 'aclocal.m4';
378           my $fullfile = File::Spec->canonpath ("$m4dir/$file");
379           scan_file ($type, $fullfile, 'aclocal');
380         }
381       closedir (DIR);
382     }
385 # Scan all the installed m4 files and construct a map.
386 sub scan_m4_files ()
388   # First, scan configure.ac.  It may contain macro definitions,
389   # or may include other files that define macros.
390   scan_file (FT_USER, $configure_ac, 'aclocal');
392   # Then, scan acinclude.m4 if it exists.
393   if (-f 'acinclude.m4')
394     {
395       scan_file (FT_USER, 'acinclude.m4', 'aclocal');
396     }
398   # Finally, scan all files in our search paths.
399   scan_m4_dirs (FT_USER, @user_includes);
400   scan_m4_dirs (FT_AUTOMAKE, @automake_includes);
401   scan_m4_dirs (FT_SYSTEM, @system_includes);
403   # Construct a new function that does the searching.  We use a
404   # function (instead of just evaluating $search in the loop) so that
405   # "die" is correctly and easily propagated if run.
406   my $search = "sub search {\nmy \$found = 0;\n";
407   foreach my $key (reverse sort keys %map)
408     {
409       $search .= ('if (/\b\Q' . $key . '\E(?!\w)/) { add_macro ("' . $key
410                   . '"); $found = 1; }' . "\n");
411     }
412   $search .= "return \$found;\n};\n";
413   eval $search;
414   prog_error "$@\n search is $search" if $@;
417 ################################################################
419 # Add a macro to the output.
420 sub add_macro ($)
422   my ($macro) = @_;
424   # Ignore unknown required macros.  Either they are not really
425   # needed (e.g., a conditional AC_REQUIRE), in which case aclocal
426   # should be quiet, or they are needed and Autoconf itself will
427   # complain when we trace for macro usage later.
428   return unless defined $map{$macro};
430   verb "saw macro $macro";
431   $macro_seen{$macro} = 1;
432   add_file ($map{$macro});
435 # scan_configure_dep ($file)
436 # --------------------------
437 # Scan a configure dependency (configure.ac, or separate m4 files)
438 # for uses of known macros and AC_REQUIREs of possibly unknown macros.
439 # Recursively scan m4_included files.
440 sub scan_configure_dep ($)
442   my ($file) = @_;
443   # Do not scan a file twice.
444   return ()
445     if exists $scanned_configure_dep{$file};
446   $scanned_configure_dep{$file} = 1;
448   my $mtime = mtime $file;
449   $greatest_mtime = $mtime if $greatest_mtime < $mtime;
451   my $contents = exists $file_contents{$file} ?
452     $file_contents{$file} : contents $file;
454   my $line = 0;
455   my @rlist = ();
456   my @ilist = ();
457   foreach (split ("\n", $contents))
458     {
459       ++$line;
460       # Remove comments from current line.
461       s/\bdnl\b.*$//;
462       s/\#.*$//;
463       # Avoid running all the following regexes on white lines.
464       next if /^\s*$/;
466       while (/$m4_include_rx/go)
467         {
468           my $ifile = $2 || $3;
469           # Skip missing 'sinclude'd files.
470           next if $1 ne 'm4_' && ! -f $ifile;
471           push @ilist, $ifile;
472         }
474       while (/$ac_require_rx/go)
475         {
476           push (@rlist, $1 || $2);
477         }
479       # The search function is constructed dynamically by
480       # scan_m4_files.  The last parenthetical match makes sure we
481       # don't match things that look like macro assignments or
482       # AC_SUBSTs.
483       if (! &search && /(^|\s+)(AM_[A-Z0-9_]+)($|[^\]\)=A-Z0-9_])/)
484         {
485           # Macro not found, but AM_ prefix found.
486           # Make this just a warning, because we do not know whether
487           # the macro is actually used (it could be called conditionally).
488           msg ('unsupported', "$file:$line",
489                "macro '$2' not found in library");
490         }
491     }
493   add_macro ($_) foreach (@rlist);
494   scan_configure_dep ($_) foreach @ilist;
497 # add_file ($FILE)
498 # ----------------
499 # Add $FILE to output.
500 sub add_file ($)
502   my ($file) = @_;
504   # Only add a file once.
505   return if ($file_added{$file});
506   $file_added{$file} = 1;
508   scan_configure_dep $file;
511 # Point to the documentation for underquoted AC_DEFUN only once.
512 my $underquoted_manual_once = 0;
514 # scan_file ($TYPE, $FILE, $WHERE)
515 # --------------------------------
516 # Scan a single M4 file ($FILE), and all files it includes.
517 # Return the list of included files.
518 # $TYPE is one of FT_USER, FT_AUTOMAKE, or FT_SYSTEM, depending
519 # on where the file comes from.
520 # $WHERE is the location to use in the diagnostic if the file
521 # does not exist.
522 sub scan_file ($$$)
524   my ($type, $file, $where) = @_;
525   my $basename = basename $file;
527   # Do not scan the same file twice.
528   return @{$file_includes{$file}} if exists $file_includes{$file};
529   # Prevent potential infinite recursion (if two files include each other).
530   return () if exists $file_contents{$file};
532   unshift @file_order, $file;
534   $file_type{$file} = $type;
536   fatal "$where: file '$file' does not exist" if ! -e $file;
538   my $fh = new Automake::XFile $file;
539   my $contents = '';
540   my @inc_files = ();
541   my %inc_lines = ();
543   my $defun_seen = 0;
544   my $serial_seen = 0;
545   my $serial_older = 0;
547   while ($_ = $fh->getline)
548     {
549       # Ignore '##' lines.
550       next if /^##/;
552       $contents .= $_;
553       my $line = $_;
555       if ($line =~ /$serial_line_rx/go)
556         {
557           my $number = $1;
558           if ($number !~ /$serial_number_rx/go)
559             {
560               msg ('syntax', "$file:$.",
561                    "ill-formed serial number '$number', "
562                    . "expecting a version string with only digits and dots");
563             }
564           elsif ($defun_seen)
565             {
566               # aclocal removes all definitions from M4 file with the
567               # same basename if a greater serial number is found.
568               # Encountering a serial after some macros will undefine
569               # these macros...
570               msg ('syntax', "$file:$.",
571                    'the serial number must appear before any macro definition');
572             }
573           # We really care about serials only for non-automake macros
574           # and when --install is used.  But the above diagnostics are
575           # made regardless of this, because not using --install is
576           # not a reason not the fix macro files.
577           elsif ($install && $type != FT_AUTOMAKE)
578             {
579               $serial_seen = 1;
580               my @new = split (/\./, $number);
582               verb "$file:$.: serial $number";
584               if (!exists $serial{$basename}
585                   || list_compare (@new, @{$serial{$basename}}) > 0)
586                 {
587                   # Delete any definition we knew from the old macro.
588                   foreach my $def (@{$invmap{$basename}})
589                     {
590                       verb "$file:$.: ignoring previous definition of $def";
591                       delete $map{$def};
592                     }
593                   $invmap{$basename} = [];
594                   $serial{$basename} = \@new;
595                 }
596               else
597                 {
598                   $serial_older = 1;
599                 }
600             }
601         }
603       # Remove comments from current line.
604       # Do not do it earlier, because the serial line is a comment.
605       $line =~ s/\bdnl\b.*$//;
606       $line =~ s/\#.*$//;
608       while ($line =~ /$ac_defun_rx/go)
609         {
610           $defun_seen = 1;
611           if (! defined $1)
612             {
613               msg ('syntax', "$file:$.", "underquoted definition of $2"
614                    . "\n  run info Automake 'Extending aclocal'\n"
615                    . "  or see http://www.gnu.org/software/automake/manual/"
616                    . "automake.html#Extending-aclocal")
617                 unless $underquoted_manual_once;
618               $underquoted_manual_once = 1;
619             }
621           # If this macro does not have a serial and we have already
622           # seen a macro with the same basename earlier, we should
623           # ignore the macro (don't exit immediately so we can still
624           # diagnose later #serial numbers and underquoted macros).
625           $serial_older ||= ($type != FT_AUTOMAKE
626                              && !$serial_seen && exists $serial{$basename});
628           my $macro = $1 || $2;
629           if (!$serial_older && !defined $map{$macro})
630             {
631               verb "found macro $macro in $file: $.";
632               $map{$macro} = $file;
633               push @{$invmap{$basename}}, $macro;
634             }
635           else
636             {
637               # Note: we used to give an error here if we saw a
638               # duplicated macro.  However, this turns out to be
639               # extremely unpopular.  It causes actual problems which
640               # are hard to work around, especially when you must
641               # mix-and-match tool versions.
642               verb "ignoring macro $macro in $file: $.";
643             }
644         }
646       while ($line =~ /$m4_include_rx/go)
647         {
648           my $ifile = $2 || $3;
649           # Skip missing 'sinclude'd files.
650           next if $1 ne 'm4_' && ! -f $ifile;
651           push (@inc_files, $ifile);
652           $inc_lines{$ifile} = $.;
653         }
654     }
656   # Ignore any file that has an old serial (or no serial if we know
657   # another one with a serial).
658   return ()
659     if ($serial_older ||
660         ($type != FT_AUTOMAKE && !$serial_seen && exists $serial{$basename}));
662   $file_contents{$file} = $contents;
664   # For some reason I don't understand, it does not work
665   # to do "map { scan_file ($_, ...) } @inc_files" below.
666   # With Perl 5.8.2 it undefines @inc_files.
667   my @copy = @inc_files;
668   my @all_inc_files = (@inc_files,
669                        map { scan_file ($type, $_,
670                                         "$file:$inc_lines{$_}") } @copy);
671   $file_includes{$file} = \@all_inc_files;
672   return @all_inc_files;
675 # strip_redundant_includes (%FILES)
676 # ---------------------------------
677 # Each key in %FILES is a file that must be present in the output.
678 # However some of these files might already include other files in %FILES,
679 # so there is no point in including them another time.
680 # This removes items of %FILES which are already included by another file.
681 sub strip_redundant_includes (%)
683   my %files = @_;
685   # Always include acinclude.m4, even if it does not appear to be used.
686   $files{'acinclude.m4'} = 1 if -f 'acinclude.m4';
687   # File included by $configure_ac are redundant.
688   $files{$configure_ac} = 1;
690   # Files at the end of @file_order should override those at the beginning,
691   # so it is important to preserve these trailing files.  We can remove
692   # a file A if it is going to be output before a file B that includes
693   # file A, not the converse.
694   foreach my $file (reverse @file_order)
695     {
696       next unless exists $files{$file};
697       foreach my $ifile (@{$file_includes{$file}})
698         {
699           next unless exists $files{$ifile};
700           delete $files{$ifile};
701           verb "$ifile is already included by $file";
702         }
703     }
705   # configure.ac is implicitly included.
706   delete $files{$configure_ac};
708   return %files;
711 sub trace_used_macros ()
713   my %files = map { $map{$_} => 1 } keys %macro_seen;
714   %files = strip_redundant_includes %files;
716   my $traces = ($ENV{AUTOM4TE} || '@am_AUTOM4TE@');
717   $traces .= " --language Autoconf-without-aclocal-m4 ";
718   # All candidate files.
719   $traces .= join (' ',
720                    (map { "'$_'" }
721                     (grep { exists $files{$_} } @file_order))) . " ";
722   # All candidate macros.
723   $traces .= join (' ',
724                    (map { "--trace='$_:\$f::\$n::\$1'" }
725                     ('AC_DEFUN',
726                      'AC_DEFUN_ONCE',
727                      'AU_DEFUN',
728                      '_AM_AUTOCONF_VERSION')),
729                    # Do not trace $1 for all other macros as we do
730                    # not need it and it might contains harmful
731                    # characters (like newlines).
732                    (map { "--trace='$_:\$f::\$n'" } (keys %macro_seen)));
734   verb "running $traces $configure_ac";
736   my $tracefh = new Automake::XFile ("$traces $configure_ac |");
738   my %traced = ();
740   while ($_ = $tracefh->getline)
741     {
742       chomp;
743       my ($file, $macro, $arg1) = split (/::/);
745       $traced{$macro} = 1 if exists $macro_seen{$macro};
747       $map_traced_defs{$arg1} = $file
748         if ($macro eq 'AC_DEFUN'
749             || $macro eq 'AC_DEFUN_ONCE'
750             || $macro eq 'AU_DEFUN');
752       $ac_version = $arg1 if $macro eq '_AM_AUTOCONF_VERSION';
753     }
755   $tracefh->close;
757   return %traced;
760 sub scan_configure ()
762   # Make sure we include acinclude.m4 if it exists.
763   if (-f 'acinclude.m4')
764     {
765       add_file ('acinclude.m4');
766     }
767   scan_configure_dep ($configure_ac);
770 ################################################################
772 # Write output.
773 # Return 0 iff some files were installed locally.
774 sub write_aclocal ($@)
776   my ($output_file, @macros) = @_;
777   my $output = '';
779   my %files = ();
780   # Get the list of files containing definitions for the macros used.
781   # (Filter out unused macro definitions with $map_traced_defs.  This
782   # can happen when an Autoconf macro is conditionally defined:
783   # aclocal sees the potential definition, but this definition is
784   # actually never processed and the Autoconf implementation is used
785   # instead.)
786   for my $m (@macros)
787     {
788       $files{$map{$m}} = 1
789         if (exists $map_traced_defs{$m}
790             && $map{$m} eq $map_traced_defs{$m});
791     }
792   # Do not explicitly include a file that is already indirectly included.
793   %files = strip_redundant_includes %files;
795   my $installed = 0;
797   for my $file (grep { exists $files{$_} } @file_order)
798     {
799       # Check the time stamp of this file, and of all files it includes.
800       for my $ifile ($file, @{$file_includes{$file}})
801         {
802           my $mtime = mtime $ifile;
803           $greatest_mtime = $mtime if $greatest_mtime < $mtime;
804         }
806       # If the file to add looks like outside the project, copy it
807       # to the output.  The regex catches filenames starting with
808       # things like '/', '\', or 'c:\'.
809       if ($file_type{$file} != FT_USER
810           || $file =~ m,^(?:\w:)?[\\/],)
811         {
812           if (!$install || $file_type{$file} != FT_SYSTEM)
813             {
814               # Copy the file into aclocal.m4.
815               $output .= $file_contents{$file} . "\n";
816             }
817           else
818             {
819               # Install the file (and any file it includes).
820               my $dest;
821               for my $ifile (@{$file_includes{$file}}, $file)
822                 {
823                   install_file ($ifile, $user_includes[0]);
824                 }
825               $installed = 1;
826             }
827         }
828       else
829         {
830           # Otherwise, simply include the file.
831           $output .= "m4_include([$file])\n";
832         }
833     }
835   if ($installed)
836     {
837       verb "running aclocal anew, because some files were installed locally";
838       return 0;
839     }
841   # Nothing to output?!
842   # FIXME: Shouldn't we diagnose this?
843   return 1 if ! length ($output);
845   if ($ac_version)
846     {
847       # Do not use "$output_file" here for the same reason we do not
848       # use it in the header below.  autom4te will output the name of
849       # the file in the diagnostic anyway.
850       $output = "m4_ifndef([AC_AUTOCONF_VERSION],
851   [m4_copy([m4_PACKAGE_VERSION], [AC_AUTOCONF_VERSION])])dnl
852 m4_if(m4_defn([AC_AUTOCONF_VERSION]), [$ac_version],,
853 [m4_warning([this file was generated for autoconf $ac_version.
854 You have another version of autoconf.  It may work, but is not guaranteed to.
855 If you have problems, you may need to regenerate the build system entirely.
856 To do so, use the procedure documented by the package, typically 'autoreconf'.])])
858 $output";
859     }
861   # We used to print "# $output_file generated automatically etc."  But
862   # this creates spurious differences when using autoreconf.  Autoreconf
863   # creates aclocal.m4t and then rename it to aclocal.m4, but the
864   # rebuild rules generated by Automake create aclocal.m4 directly --
865   # this would gives two ways to get the same file, with a different
866   # name in the header.
867   $output = "# generated automatically by aclocal $VERSION -*- Autoconf -*-
869 # Copyright (C) 1996-$RELEASE_YEAR Free Software Foundation, Inc.
871 # This file is free software; the Free Software Foundation
872 # gives unlimited permission to copy and/or distribute it,
873 # with or without modifications, as long as this notice is preserved.
875 # This program is distributed in the hope that it will be useful,
876 # but WITHOUT ANY WARRANTY, to the extent permitted by law; without
877 # even the implied warranty of MERCHANTABILITY or FITNESS FOR A
878 # PARTICULAR PURPOSE.
880 $output";
882   # We try not to update $output_file unless necessary, because
883   # doing so invalidate Autom4te's cache and therefore slows down
884   # tools called after aclocal.
885   #
886   # We need to overwrite $output_file in the following situations.
887   #   * The --force option is in use.
888   #   * One of the dependencies is younger.
889   #     (Not updating $output_file in this situation would cause
890   #     make to call aclocal in loop.)
891   #   * The contents of the current file are different from what
892   #     we have computed.
893   if (!$force_output
894       && $greatest_mtime < mtime ($output_file)
895       && $output eq contents ($output_file))
896     {
897       verb "$output_file unchanged";
898       return 1;
899     }
901   verb "writing $output_file";
903   if (!$dry_run)
904     {
905       if (-e $output_file && !unlink $output_file)
906         {
907           fatal "could not remove '$output_file': $!";
908         }
909       my $out = new Automake::XFile "> $output_file";
910       print $out $output;
911     }
912   return 1;
915 ################################################################
917 # Print usage and exit.
918 sub usage ($)
920   my ($status) = @_;
922   print <<'EOF';
923 Usage: aclocal [OPTION]...
925 Generate 'aclocal.m4' by scanning 'configure.ac' or 'configure.in'
927 Options:
928       --automake-acdir=DIR  directory holding automake-provided m4 files
929       --system-acdir=DIR    directory holding third-party system-wide files
930       --diff[=COMMAND]      run COMMAND [diff -u] on M4 files that would be
931                             changed (implies --install and --dry-run)
932       --dry-run             pretend to, but do not actually update any file
933       --force               always update output file
934       --help                print this help, then exit
935   -I DIR                    add directory to search list for .m4 files
936       --install             copy third-party files to the first -I directory
937       --output=FILE         put output in FILE (default aclocal.m4)
938       --print-ac-dir        print name of directory holding system-wide
939                               third-party m4 files, then exit
940       --verbose             don't be silent
941       --version             print version number, then exit
942   -W, --warnings=CATEGORY   report the warnings falling in CATEGORY
944 Warning categories include:
945   syntax        dubious syntactic constructs (default)
946   unsupported   unknown macros (default)
947   all           all the warnings (default)
948   no-CATEGORY   turn off warnings in CATEGORY
949   none          turn off all the warnings
950   error         treat warnings as errors
952 Report bugs to <@PACKAGE_BUGREPORT@>.
953 GNU Automake home page: <@PACKAGE_URL@>.
954 General help using GNU software: <http://www.gnu.org/gethelp/>.
956   exit $status;
959 # Print version and exit.
960 sub version ()
962   print <<EOF;
963 aclocal (GNU $PACKAGE) $VERSION
964 Copyright (C) $RELEASE_YEAR Free Software Foundation, Inc.
965 License GPLv2+: GNU GPL version 2 or later <http://gnu.org/licenses/gpl-2.0.html>
966 This is free software: you are free to change and redistribute it.
967 There is NO WARRANTY, to the extent permitted by law.
969 Written by Tom Tromey <tromey\@redhat.com>
970        and Alexandre Duret-Lutz <adl\@gnu.org>.
972   exit 0;
975 # Using --acdir overrides both the automake (versioned) directory and
976 # the public (unversioned) system directory.  This usage is obsolete.
977 sub handle_acdir_option ($$)
979   msg 'obsolete', '', "'--acdir' is deprecated\n";
980   @system_includes = ($_[1]);
981   @automake_includes = ();
984 # Parse command line.
985 sub parse_arguments ()
987   my $print_and_exit = 0;
988   my $diff_command;
990   my %cli_options =
991     (
992      'help'             => sub { usage(0); },
993      'version'          => \&version,
994      'acdir=s'          => \&handle_acdir_option,
995      'system-acdir=s'   => sub { shift; @system_includes = @_; },
996      'automake-acdir=s' => sub { shift; @automake_includes = @_; },
997      'diff:s'           => \$diff_command,
998      'dry-run'          => \$dry_run,
999      'force'            => \$force_output,
1000      'I=s'              => \@user_includes,
1001      'install'          => \$install,
1002      'output=s'         => \$output_file,
1003      'print-ac-dir'     => \$print_and_exit,
1004      'verbose'          => sub { setup_channel 'verb', silent => 0; },
1005      'W|warnings=s'     => \&parse_warnings,
1006      );
1008   use Automake::Getopt ();
1009   Automake::Getopt::parse_options %cli_options;
1011   if (@ARGV > 0)
1012     {
1013       fatal ("non-option arguments are not accepted: '$ARGV[0]'.\n"
1014              . "Try '$0 --help' for more information.");
1015     }
1017   if ($print_and_exit)
1018     {
1019       print "@system_includes\n";
1020       exit 0;
1021     }
1023   if (defined $diff_command)
1024     {
1025       $diff_command = 'diff -u' if $diff_command eq '';
1026       @diff_command = split (' ', $diff_command);
1027       $install = 1;
1028       $dry_run = 1;
1029     }
1031   if ($install && !@user_includes)
1032     {
1033       fatal ("--install should copy macros in the directory indicated by the"
1034              . "\nfirst -I option, but no -I was supplied");
1035     }
1037   # Finally, adds any directory listed in the 'dirlist' file.
1038   if (open (DIRLIST, "$system_includes[0]/dirlist"))
1039     {
1040       while (<DIRLIST>)
1041         {
1042           # Ignore '#' lines.
1043           next if /^#/;
1044           # strip off newlines and end-of-line comments
1045           s/\s*\#.*$//;
1046           chomp;
1047           foreach my $dir (glob)
1048             {
1049               push (@system_includes, $dir) if -d $dir;
1050             }
1051         }
1052       close (DIRLIST);
1053     }
1056 # Add any directory listed in the 'ACLOCAL_PATH' environment variable
1057 # to the list of system include directories.
1058 sub parse_ACLOCAL_PATH ()
1060   return if not defined $ENV{"ACLOCAL_PATH"};
1061   # Directories in ACLOCAL_PATH should take precedence over system
1062   # directories, so we use unshift.  However, directories that
1063   # come first in ACLOCAL_PATH take precedence over directories
1064   # coming later, which is why the result of split is reversed.
1065   foreach my $dir (reverse split /:/, $ENV{"ACLOCAL_PATH"})
1066     {
1067       unshift (@system_includes, $dir) if $dir ne '' && -d $dir;
1068     }
1071 ################################################################
1073 parse_WARNINGS;             # Parse the WARNINGS environment variable.
1074 parse_arguments;
1075 parse_ACLOCAL_PATH;
1076 $configure_ac = require_configure_ac;
1078 # We may have to rerun aclocal if some file have been installed, but
1079 # it should not happen more than once.  The reason we must run again
1080 # is that once the file has been moved from /usr/share/aclocal/ to the
1081 # local m4/ directory it appears at a new place in the search path,
1082 # hence it should be output at a different position in aclocal.m4.  If
1083 # we did not rerun aclocal, the next run of aclocal would produce a
1084 # different aclocal.m4.
1085 my $loop = 0;
1086 while (1)
1087   {
1088     ++$loop;
1089     prog_error "too many loops" if $loop > 2;
1091     reset_maps;
1092     scan_m4_files;
1093     scan_configure;
1094     last if $exit_code;
1095     my %macro_traced = trace_used_macros;
1096     last if write_aclocal ($output_file, keys %macro_traced);
1097     last if $dry_run;
1098   }
1099 check_acinclude;
1101 exit $exit_code;
1103 ### Setup "GNU" style for perl-mode and cperl-mode.
1104 ## Local Variables:
1105 ## perl-indent-level: 2
1106 ## perl-continued-statement-offset: 2
1107 ## perl-continued-brace-offset: 0
1108 ## perl-brace-offset: 0
1109 ## perl-brace-imaginary-offset: 0
1110 ## perl-label-offset: -2
1111 ## cperl-indent-level: 2
1112 ## cperl-brace-offset: 0
1113 ## cperl-continued-brace-offset: 0
1114 ## cperl-label-offset: -2
1115 ## cperl-extra-newline-before-brace: t
1116 ## cperl-merge-trailing-else: nil
1117 ## cperl-continued-statement-offset: 2
1118 ## End: