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