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