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