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