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