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