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