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