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