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