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