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