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