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