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