Merge branch '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, $ERR_ON_NONEXISTING, @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 sub scan_m4_dirs ($$@)
352 {
353   my ($type, $err_on_nonexisting, @dirlist) = @_;
354
355   foreach my $m4dir (@dirlist)
356     {
357       if (! opendir (DIR, $m4dir))
358         {
359           # TODO: maybe avoid complaining only if errno == ENONENT?
360           next unless $err_on_nonexisting;
361           fatal "couldn't open directory '$m4dir': $!";
362         }
363
364       # We reverse the directory contents so that foo2.m4 gets
365       # used in preference to foo1.m4.
366       foreach my $file (reverse sort grep (! /^\./, readdir (DIR)))
367         {
368           # Only examine .m4 files.
369           next unless $file =~ /\.m4$/;
370
371           # Skip some files when running out of srcdir.
372           next if $file eq 'aclocal.m4';
373
374           my $fullfile = File::Spec->canonpath ("$m4dir/$file");
375           scan_file ($type, $fullfile, 'aclocal');
376         }
377       closedir (DIR);
378     }
379 }
380
381 # Scan all the installed m4 files and construct a map.
382 sub scan_m4_files ()
383 {
384   # First, scan configure.ac.  It may contain macro definitions,
385   # or may include other files that define macros.
386   scan_file (FT_USER, $configure_ac, 'aclocal');
387
388   # Then, scan acinclude.m4 if it exists.
389   if (-f 'acinclude.m4')
390     {
391       scan_file (FT_USER, 'acinclude.m4', 'aclocal');
392     }
393
394   # Finally, scan all files in our search paths.
395
396   if (@user_includes)
397     {
398       # Don't complain if the first user directory doesn't exist, in case
399       # we need to create it later (can happen if '--install' was given).
400       scan_m4_dirs (FT_USER, !$install, $user_includes[0]);
401       scan_m4_dirs (FT_USER, 1, @user_includes[1..$#user_includes]);
402     }
403   scan_m4_dirs (FT_AUTOMAKE, 1, @automake_includes);
404   scan_m4_dirs (FT_SYSTEM,   1, @system_includes);
405
406   # Construct a new function that does the searching.  We use a
407   # function (instead of just evaluating $search in the loop) so that
408   # "die" is correctly and easily propagated if run.
409   my $search = "sub search {\nmy \$found = 0;\n";
410   foreach my $key (reverse sort keys %map)
411     {
412       $search .= ('if (/\b\Q' . $key . '\E(?!\w)/) { add_macro ("' . $key
413                   . '"); $found = 1; }' . "\n");
414     }
415   $search .= "return \$found;\n};\n";
416   eval $search;
417   prog_error "$@\n search is $search" if $@;
418 }
419
420 ################################################################
421
422 # Add a macro to the output.
423 sub add_macro ($)
424 {
425   my ($macro) = @_;
426
427   # Ignore unknown required macros.  Either they are not really
428   # needed (e.g., a conditional AC_REQUIRE), in which case aclocal
429   # should be quiet, or they are needed and Autoconf itself will
430   # complain when we trace for macro usage later.
431   return unless defined $map{$macro};
432
433   verb "saw macro $macro";
434   $macro_seen{$macro} = 1;
435   add_file ($map{$macro});
436 }
437
438 # scan_configure_dep ($file)
439 # --------------------------
440 # Scan a configure dependency (configure.ac, or separate m4 files)
441 # for uses of known macros and AC_REQUIREs of possibly unknown macros.
442 # Recursively scan m4_included files.
443 sub scan_configure_dep ($)
444 {
445   my ($file) = @_;
446   # Do not scan a file twice.
447   return ()
448     if exists $scanned_configure_dep{$file};
449   $scanned_configure_dep{$file} = 1;
450
451   my $mtime = mtime $file;
452   $greatest_mtime = $mtime if $greatest_mtime < $mtime;
453
454   my $contents = exists $file_contents{$file} ?
455     $file_contents{$file} : contents $file;
456
457   my $line = 0;
458   my @rlist = ();
459   my @ilist = ();
460   foreach (split ("\n", $contents))
461     {
462       ++$line;
463       # Remove comments from current line.
464       s/\bdnl\b.*$//;
465       s/\#.*$//;
466       # Avoid running all the following regexes on white lines.
467       next if /^\s*$/;
468
469       while (/$m4_include_rx/go)
470         {
471           my $ifile = $2 || $3;
472           # Skip missing 'sinclude'd files.
473           next if $1 ne 'm4_' && ! -f $ifile;
474           push @ilist, $ifile;
475         }
476
477       while (/$ac_require_rx/go)
478         {
479           push (@rlist, $1 || $2);
480         }
481
482       # The search function is constructed dynamically by
483       # scan_m4_files.  The last parenthetical match makes sure we
484       # don't match things that look like macro assignments or
485       # AC_SUBSTs.
486       if (! &search && /(^|\s+)(AM_[A-Z0-9_]+)($|[^\]\)=A-Z0-9_])/)
487         {
488           # Macro not found, but AM_ prefix found.
489           # Make this just a warning, because we do not know whether
490           # the macro is actually used (it could be called conditionally).
491           msg ('unsupported', "$file:$line",
492                "macro '$2' not found in library");
493         }
494     }
495
496   add_macro ($_) foreach (@rlist);
497   scan_configure_dep ($_) foreach @ilist;
498 }
499
500 # add_file ($FILE)
501 # ----------------
502 # Add $FILE to output.
503 sub add_file ($)
504 {
505   my ($file) = @_;
506
507   # Only add a file once.
508   return if ($file_added{$file});
509   $file_added{$file} = 1;
510
511   scan_configure_dep $file;
512 }
513
514 # Point to the documentation for underquoted AC_DEFUN only once.
515 my $underquoted_manual_once = 0;
516
517 # scan_file ($TYPE, $FILE, $WHERE)
518 # --------------------------------
519 # Scan a single M4 file ($FILE), and all files it includes.
520 # Return the list of included files.
521 # $TYPE is one of FT_USER, FT_AUTOMAKE, or FT_SYSTEM, depending
522 # on where the file comes from.
523 # $WHERE is the location to use in the diagnostic if the file
524 # does not exist.
525 sub scan_file ($$$)
526 {
527   my ($type, $file, $where) = @_;
528   my $basename = basename $file;
529
530   # Do not scan the same file twice.
531   return @{$file_includes{$file}} if exists $file_includes{$file};
532   # Prevent potential infinite recursion (if two files include each other).
533   return () if exists $file_contents{$file};
534
535   unshift @file_order, $file;
536
537   $file_type{$file} = $type;
538
539   fatal "$where: file '$file' does not exist" if ! -e $file;
540
541   my $fh = new Automake::XFile $file;
542   my $contents = '';
543   my @inc_files = ();
544   my %inc_lines = ();
545
546   my $defun_seen = 0;
547   my $serial_seen = 0;
548   my $serial_older = 0;
549
550   while ($_ = $fh->getline)
551     {
552       # Ignore '##' lines.
553       next if /^##/;
554
555       $contents .= $_;
556       my $line = $_;
557
558       if ($line =~ /$serial_line_rx/go)
559         {
560           my $number = $1;
561           if ($number !~ /$serial_number_rx/go)
562             {
563               msg ('syntax', "$file:$.",
564                    "ill-formed serial number '$number', "
565                    . "expecting a version string with only digits and dots");
566             }
567           elsif ($defun_seen)
568             {
569               # aclocal removes all definitions from M4 file with the
570               # same basename if a greater serial number is found.
571               # Encountering a serial after some macros will undefine
572               # these macros...
573               msg ('syntax', "$file:$.",
574                    'the serial number must appear before any macro definition');
575             }
576           # We really care about serials only for non-automake macros
577           # and when --install is used.  But the above diagnostics are
578           # made regardless of this, because not using --install is
579           # not a reason not the fix macro files.
580           elsif ($install && $type != FT_AUTOMAKE)
581             {
582               $serial_seen = 1;
583               my @new = split (/\./, $number);
584
585               verb "$file:$.: serial $number";
586
587               if (!exists $serial{$basename}
588                   || list_compare (@new, @{$serial{$basename}}) > 0)
589                 {
590                   # Delete any definition we knew from the old macro.
591                   foreach my $def (@{$invmap{$basename}})
592                     {
593                       verb "$file:$.: ignoring previous definition of $def";
594                       delete $map{$def};
595                     }
596                   $invmap{$basename} = [];
597                   $serial{$basename} = \@new;
598                 }
599               else
600                 {
601                   $serial_older = 1;
602                 }
603             }
604         }
605
606       # Remove comments from current line.
607       # Do not do it earlier, because the serial line is a comment.
608       $line =~ s/\bdnl\b.*$//;
609       $line =~ s/\#.*$//;
610
611       while ($line =~ /$ac_defun_rx/go)
612         {
613           $defun_seen = 1;
614           if (! defined $1)
615             {
616               msg ('syntax', "$file:$.", "underquoted definition of $2"
617                    . "\n  run info Automake 'Extending aclocal'\n"
618                    . "  or see http://www.gnu.org/software/automake/manual/"
619                    . "automake.html#Extending-aclocal")
620                 unless $underquoted_manual_once;
621               $underquoted_manual_once = 1;
622             }
623
624           # If this macro does not have a serial and we have already
625           # seen a macro with the same basename earlier, we should
626           # ignore the macro (don't exit immediately so we can still
627           # diagnose later #serial numbers and underquoted macros).
628           $serial_older ||= ($type != FT_AUTOMAKE
629                              && !$serial_seen && exists $serial{$basename});
630
631           my $macro = $1 || $2;
632           if (!$serial_older && !defined $map{$macro})
633             {
634               verb "found macro $macro in $file: $.";
635               $map{$macro} = $file;
636               push @{$invmap{$basename}}, $macro;
637             }
638           else
639             {
640               # Note: we used to give an error here if we saw a
641               # duplicated macro.  However, this turns out to be
642               # extremely unpopular.  It causes actual problems which
643               # are hard to work around, especially when you must
644               # mix-and-match tool versions.
645               verb "ignoring macro $macro in $file: $.";
646             }
647         }
648
649       while ($line =~ /$m4_include_rx/go)
650         {
651           my $ifile = $2 || $3;
652           # Skip missing 'sinclude'd files.
653           next if $1 ne 'm4_' && ! -f $ifile;
654           push (@inc_files, $ifile);
655           $inc_lines{$ifile} = $.;
656         }
657     }
658
659   # Ignore any file that has an old serial (or no serial if we know
660   # another one with a serial).
661   return ()
662     if ($serial_older ||
663         ($type != FT_AUTOMAKE && !$serial_seen && exists $serial{$basename}));
664
665   $file_contents{$file} = $contents;
666
667   # For some reason I don't understand, it does not work
668   # to do "map { scan_file ($_, ...) } @inc_files" below.
669   # With Perl 5.8.2 it undefines @inc_files.
670   my @copy = @inc_files;
671   my @all_inc_files = (@inc_files,
672                        map { scan_file ($type, $_,
673                                         "$file:$inc_lines{$_}") } @copy);
674   $file_includes{$file} = \@all_inc_files;
675   return @all_inc_files;
676 }
677
678 # strip_redundant_includes (%FILES)
679 # ---------------------------------
680 # Each key in %FILES is a file that must be present in the output.
681 # However some of these files might already include other files in %FILES,
682 # so there is no point in including them another time.
683 # This removes items of %FILES which are already included by another file.
684 sub strip_redundant_includes (%)
685 {
686   my %files = @_;
687
688   # Always include acinclude.m4, even if it does not appear to be used.
689   $files{'acinclude.m4'} = 1 if -f 'acinclude.m4';
690   # File included by $configure_ac are redundant.
691   $files{$configure_ac} = 1;
692
693   # Files at the end of @file_order should override those at the beginning,
694   # so it is important to preserve these trailing files.  We can remove
695   # a file A if it is going to be output before a file B that includes
696   # file A, not the converse.
697   foreach my $file (reverse @file_order)
698     {
699       next unless exists $files{$file};
700       foreach my $ifile (@{$file_includes{$file}})
701         {
702           next unless exists $files{$ifile};
703           delete $files{$ifile};
704           verb "$ifile is already included by $file";
705         }
706     }
707
708   # configure.ac is implicitly included.
709   delete $files{$configure_ac};
710
711   return %files;
712 }
713
714 sub trace_used_macros ()
715 {
716   my %files = map { $map{$_} => 1 } keys %macro_seen;
717   %files = strip_redundant_includes %files;
718
719   my $traces = ($ENV{AUTOM4TE} || '@am_AUTOM4TE@');
720   $traces .= " --language Autoconf-without-aclocal-m4 ";
721   # When AC_CONFIG_MACRO_DIRS is used, avoid possible spurious warnings
722   # from autom4te about macros being "m4_require'd but not m4_defun'd";
723   # for more background, see:
724   # http://lists.gnu.org/archive/html/autoconf-patches/2012-11/msg00004.html
725   # as well as autoconf commit 'v2.69-44-g1ed0548', "warn: allow aclocal
726   # to silence m4_require warnings".
727   $traces = "echo 'm4_define([m4_require_silent_probe], [-])' | " .
728             "$traces - ";
729   # All candidate files.
730   $traces .= join (' ',
731                    (map { "'$_'" }
732                     (grep { exists $files{$_} } @file_order))) . " ";
733
734   # All candidate macros.
735   $traces .= join (' ',
736                    (map { "--trace='$_:\$f::\$n::\${::}%'" }
737                     ('AC_DEFUN',
738                      'AC_DEFUN_ONCE',
739                      'AU_DEFUN',
740                      '_AM_AUTOCONF_VERSION',
741                      # FIXME: We still need to trace AC_CONFIG_MACRO_DIR
742                      # for compatibility with older autoconf.  Remove this
743                      # when we can assume Autoconf 2.70 or later.
744                      'AC_CONFIG_MACRO_DIR',
745                      'AC_CONFIG_MACRO_DIR_TRACE')),
746                    # Do not trace $1 for all other macros as we do
747                    # not need it and it might contains harmful
748                    # characters (like newlines).
749                    (map { "--trace='$_:\$f::\$n'" } (keys %macro_seen)));
750
751   verb "running $traces $configure_ac";
752
753   my $tracefh = new Automake::XFile ("$traces $configure_ac |");
754
755   @ac_config_macro_dirs = ();
756
757   my %traced = ();
758
759   while ($_ = $tracefh->getline)
760     {
761       chomp;
762       my ($file, $macro, $arg1) = split (/::/);
763
764       $traced{$macro} = 1 if exists $macro_seen{$macro};
765
766       if ($macro eq 'AC_DEFUN' || $macro eq 'AC_DEFUN_ONCE'
767             || $macro eq 'AU_DEFUN')
768         {
769           $map_traced_defs{$arg1} = $file;
770         }
771       elsif ($macro eq '_AM_AUTOCONF_VERSION')
772         {
773           $ac_version = $arg1;
774         }
775       elsif ($macro eq 'AC_CONFIG_MACRO_DIR_TRACE')
776         {
777           push @ac_config_macro_dirs, $arg1;
778         }
779     # FIXME: We still need to trace AC_CONFIG_MACRO_DIR
780     # for compatibility with older autoconf.  Remove this
781     # when we can assume Autoconf 2.70 or later.
782     elsif ($macro eq 'AC_CONFIG_MACRO_DIR')
783         {
784           @ac_config_macro_dirs = ($arg1);
785         }
786     }
787
788   # FIXME: in Autoconf >= 2.70, AC_CONFIG_MACRO_DIR calls
789   # AC_CONFIG_MACRO_DIR_TRACE behind the scenes, which could
790   # leave unwanted duplicates in @ac_config_macro_dirs.
791   @ac_config_macro_dirs = uniq @ac_config_macro_dirs;
792
793   $tracefh->close;
794
795   return %traced;
796 }
797
798 sub scan_configure ()
799 {
800   # Make sure we include acinclude.m4 if it exists.
801   if (-f 'acinclude.m4')
802     {
803       add_file ('acinclude.m4');
804     }
805   scan_configure_dep ($configure_ac);
806 }
807
808 ################################################################
809
810 # Write output.
811 # Return 0 iff some files were installed locally.
812 sub write_aclocal ($@)
813 {
814   my ($output_file, @macros) = @_;
815   my $output = '';
816
817   my %files = ();
818   # Get the list of files containing definitions for the macros used.
819   # (Filter out unused macro definitions with $map_traced_defs.  This
820   # can happen when an Autoconf macro is conditionally defined:
821   # aclocal sees the potential definition, but this definition is
822   # actually never processed and the Autoconf implementation is used
823   # instead.)
824   for my $m (@macros)
825     {
826       $files{$map{$m}} = 1
827         if (exists $map_traced_defs{$m}
828             && $map{$m} eq $map_traced_defs{$m});
829     }
830   # Do not explicitly include a file that is already indirectly included.
831   %files = strip_redundant_includes %files;
832
833   my $installed = 0;
834
835   for my $file (grep { exists $files{$_} } @file_order)
836     {
837       # Check the time stamp of this file, and of all files it includes.
838       for my $ifile ($file, @{$file_includes{$file}})
839         {
840           my $mtime = mtime $ifile;
841           $greatest_mtime = $mtime if $greatest_mtime < $mtime;
842         }
843
844       # If the file to add looks like outside the project, copy it
845       # to the output.  The regex catches filenames starting with
846       # things like '/', '\', or 'c:\'.
847       if ($file_type{$file} != FT_USER
848           || $file =~ m,^(?:\w:)?[\\/],)
849         {
850           if (!$install || $file_type{$file} != FT_SYSTEM)
851             {
852               # Copy the file into aclocal.m4.
853               $output .= $file_contents{$file} . "\n";
854             }
855           else
856             {
857               # Install the file (and any file it includes).
858               my $dest;
859               for my $ifile (@{$file_includes{$file}}, $file)
860                 {
861                   install_file ($ifile, $user_includes[0]);
862                 }
863               $installed = 1;
864             }
865         }
866       else
867         {
868           # Otherwise, simply include the file.
869           $output .= "m4_include([$file])\n";
870         }
871     }
872
873   if ($installed)
874     {
875       verb "running aclocal anew, because some files were installed locally";
876       return 0;
877     }
878
879   # Nothing to output?!
880   # FIXME: Shouldn't we diagnose this?
881   return 1 if ! length ($output);
882
883   if ($ac_version)
884     {
885       # Do not use "$output_file" here for the same reason we do not
886       # use it in the header below.  autom4te will output the name of
887       # the file in the diagnostic anyway.
888       $output = "m4_ifndef([AC_AUTOCONF_VERSION],
889   [m4_copy([m4_PACKAGE_VERSION], [AC_AUTOCONF_VERSION])])dnl
890 m4_if(m4_defn([AC_AUTOCONF_VERSION]), [$ac_version],,
891 [m4_warning([this file was generated for autoconf $ac_version.
892 You have another version of autoconf.  It may work, but is not guaranteed to.
893 If you have problems, you may need to regenerate the build system entirely.
894 To do so, use the procedure documented by the package, typically 'autoreconf'.])])
895
896 $output";
897     }
898
899   # We used to print "# $output_file generated automatically etc."  But
900   # this creates spurious differences when using autoreconf.  Autoreconf
901   # creates aclocal.m4t and then rename it to aclocal.m4, but the
902   # rebuild rules generated by Automake create aclocal.m4 directly --
903   # this would gives two ways to get the same file, with a different
904   # name in the header.
905   $output = "# generated automatically by aclocal $VERSION -*- Autoconf -*-
906
907 # Copyright (C) 1996-$RELEASE_YEAR Free Software Foundation, Inc.
908
909 # This file is free software; the Free Software Foundation
910 # gives unlimited permission to copy and/or distribute it,
911 # with or without modifications, as long as this notice is preserved.
912
913 # This program is distributed in the hope that it will be useful,
914 # but WITHOUT ANY WARRANTY, to the extent permitted by law; without
915 # even the implied warranty of MERCHANTABILITY or FITNESS FOR A
916 # PARTICULAR PURPOSE.
917
918 $output";
919
920   # We try not to update $output_file unless necessary, because
921   # doing so invalidate Autom4te's cache and therefore slows down
922   # tools called after aclocal.
923   #
924   # We need to overwrite $output_file in the following situations.
925   #   * The --force option is in use.
926   #   * One of the dependencies is younger.
927   #     (Not updating $output_file in this situation would cause
928   #     make to call aclocal in loop.)
929   #   * The contents of the current file are different from what
930   #     we have computed.
931   if (!$force_output
932       && $greatest_mtime < mtime ($output_file)
933       && $output eq contents ($output_file))
934     {
935       verb "$output_file unchanged";
936       return 1;
937     }
938
939   verb "writing $output_file";
940
941   if (!$dry_run)
942     {
943       if (-e $output_file && !unlink $output_file)
944         {
945           fatal "could not remove '$output_file': $!";
946         }
947       my $out = new Automake::XFile "> $output_file";
948       print $out $output;
949     }
950   return 1;
951 }
952
953 ################################################################
954
955 # Print usage and exit.
956 sub usage ($)
957 {
958   my ($status) = @_;
959
960   print <<'EOF';
961 Usage: aclocal [OPTION]...
962
963 Generate 'aclocal.m4' by scanning 'configure.ac' or 'configure.in'
964
965 Options:
966       --automake-acdir=DIR  directory holding automake-provided m4 files
967       --system-acdir=DIR    directory holding third-party system-wide files
968       --diff[=COMMAND]      run COMMAND [diff -u] on M4 files that would be
969                             changed (implies --install and --dry-run)
970       --dry-run             pretend to, but do not actually update any file
971       --force               always update output file
972       --help                print this help, then exit
973   -I DIR                    add directory to search list for .m4 files
974       --install             copy third-party files to the first -I directory
975       --output=FILE         put output in FILE (default aclocal.m4)
976       --print-ac-dir        print name of directory holding system-wide
977                               third-party m4 files, then exit
978       --verbose             don't be silent
979       --version             print version number, then exit
980   -W, --warnings=CATEGORY   report the warnings falling in CATEGORY
981
982 Warning categories include:
983   syntax        dubious syntactic constructs (default)
984   unsupported   unknown macros (default)
985   all           all the warnings (default)
986   no-CATEGORY   turn off warnings in CATEGORY
987   none          turn off all the warnings
988   error         treat warnings as errors
989
990 Report bugs to <@PACKAGE_BUGREPORT@>.
991 GNU Automake home page: <@PACKAGE_URL@>.
992 General help using GNU software: <http://www.gnu.org/gethelp/>.
993 EOF
994   exit $status;
995 }
996
997 # Print version and exit.
998 sub version ()
999 {
1000   print <<EOF;
1001 aclocal (GNU $PACKAGE) $VERSION
1002 Copyright (C) $RELEASE_YEAR Free Software Foundation, Inc.
1003 License GPLv2+: GNU GPL version 2 or later <http://gnu.org/licenses/gpl-2.0.html>
1004 This is free software: you are free to change and redistribute it.
1005 There is NO WARRANTY, to the extent permitted by law.
1006
1007 Written by Tom Tromey <tromey\@redhat.com>
1008        and Alexandre Duret-Lutz <adl\@gnu.org>.
1009 EOF
1010   exit 0;
1011 }
1012
1013 # Parse command line.
1014 sub parse_arguments ()
1015 {
1016   my $print_and_exit = 0;
1017   my $diff_command;
1018
1019   my %cli_options =
1020     (
1021      'help'             => sub { usage(0); },
1022      'version'          => \&version,
1023      'system-acdir=s'   => sub { shift; @system_includes = @_; },
1024      'automake-acdir=s' => sub { shift; @automake_includes = @_; },
1025      'diff:s'           => \$diff_command,
1026      'dry-run'          => \$dry_run,
1027      'force'            => \$force_output,
1028      'I=s'              => \@user_includes,
1029      'install'          => \$install,
1030      'output=s'         => \$output_file,
1031      'print-ac-dir'     => \$print_and_exit,
1032      'verbose'          => sub { setup_channel 'verb', silent => 0; },
1033      'W|warnings=s'     => \&parse_warnings,
1034      );
1035
1036   use Automake::Getopt ();
1037   Automake::Getopt::parse_options %cli_options;
1038
1039   if (@ARGV > 0)
1040     {
1041       fatal ("non-option arguments are not accepted: '$ARGV[0]'.\n"
1042              . "Try '$0 --help' for more information.");
1043     }
1044
1045   if ($print_and_exit)
1046     {
1047       print "@system_includes\n";
1048       exit 0;
1049     }
1050
1051   if (defined $diff_command)
1052     {
1053       $diff_command = 'diff -u' if $diff_command eq '';
1054       @diff_command = split (' ', $diff_command);
1055       $install = 1;
1056       $dry_run = 1;
1057     }
1058
1059   # Finally, adds any directory listed in the 'dirlist' file.
1060   if (open (DIRLIST, "$system_includes[0]/dirlist"))
1061     {
1062       while (<DIRLIST>)
1063         {
1064           # Ignore '#' lines.
1065           next if /^#/;
1066           # strip off newlines and end-of-line comments
1067           s/\s*\#.*$//;
1068           chomp;
1069           foreach my $dir (glob)
1070             {
1071               push (@system_includes, $dir) if -d $dir;
1072             }
1073         }
1074       close (DIRLIST);
1075     }
1076 }
1077
1078 # Add any directory listed in the 'ACLOCAL_PATH' environment variable
1079 # to the list of system include directories.
1080 sub parse_ACLOCAL_PATH ()
1081 {
1082   return if not defined $ENV{"ACLOCAL_PATH"};
1083   # Directories in ACLOCAL_PATH should take precedence over system
1084   # directories, so we use unshift.  However, directories that
1085   # come first in ACLOCAL_PATH take precedence over directories
1086   # coming later, which is why the result of split is reversed.
1087   foreach my $dir (reverse split /:/, $ENV{"ACLOCAL_PATH"})
1088     {
1089       unshift (@system_includes, $dir) if $dir ne '' && -d $dir;
1090     }
1091 }
1092
1093 ################################################################
1094
1095 parse_WARNINGS;             # Parse the WARNINGS environment variable.
1096 parse_arguments;
1097 parse_ACLOCAL_PATH;
1098 $configure_ac = require_configure_ac;
1099
1100 # We may have to rerun aclocal if some file have been installed, but
1101 # it should not happen more than once.  The reason we must run again
1102 # is that once the file has been moved from /usr/share/aclocal/ to the
1103 # local m4/ directory it appears at a new place in the search path,
1104 # hence it should be output at a different position in aclocal.m4.  If
1105 # we did not rerun aclocal, the next run of aclocal would produce a
1106 # different aclocal.m4.
1107 my $loop = 0;
1108 my $rerun_due_to_macrodir = 0;
1109 while (1)
1110   {
1111     ++$loop;
1112     prog_error "too many loops" if $loop > 2 + $rerun_due_to_macrodir;
1113
1114     reset_maps;
1115     scan_m4_files;
1116     scan_configure;
1117     last if $exit_code;
1118     my %macro_traced = trace_used_macros;
1119
1120     if (!$rerun_due_to_macrodir && @ac_config_macro_dirs)
1121       {
1122         # The directory specified in calls to the AC_CONFIG_MACRO_DIRS
1123         # m4 macro (if any) must go after the user includes specified
1124         # explicitly with the '-I' option.
1125         push @user_includes, @ac_config_macro_dirs;
1126         # We might have to scan some new directory of .m4 files.
1127         $rerun_due_to_macrodir++;
1128         next;
1129       }
1130
1131     if ($install && !@user_includes)
1132       {
1133         fatal "installation of third-party macros impossible without " .
1134               "-I options nor AC_CONFIG_MACRO_DIR{,S} m4 macro(s)";
1135       }
1136
1137     last if write_aclocal ($output_file, keys %macro_traced);
1138     last if $dry_run;
1139   }
1140 check_acinclude;
1141
1142 exit $exit_code;
1143
1144 ### Setup "GNU" style for perl-mode and cperl-mode.
1145 ## Local Variables:
1146 ## perl-indent-level: 2
1147 ## perl-continued-statement-offset: 2
1148 ## perl-continued-brace-offset: 0
1149 ## perl-brace-offset: 0
1150 ## perl-brace-imaginary-offset: 0
1151 ## perl-label-offset: -2
1152 ## cperl-indent-level: 2
1153 ## cperl-brace-offset: 0
1154 ## cperl-continued-brace-offset: 0
1155 ## cperl-label-offset: -2
1156 ## cperl-extra-newline-before-brace: t
1157 ## cperl-merge-trailing-else: nil
1158 ## cperl-continued-statement-offset: 2
1159 ## End: