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