* aclocal.in ($acdir): Rename as ...
[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 #           Free Software Foundation, Inc.
12
13 # This program is free software; you can redistribute it and/or modify
14 # it under the terms of the GNU General Public License as published by
15 # the Free Software Foundation; either version 2, or (at your option)
16 # any later version.
17
18 # This program is distributed in the hope that it will be useful,
19 # but WITHOUT ANY WARRANTY; without even the implied warranty of
20 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
21 # GNU General Public License for more details.
22
23 # You should have received a copy of the GNU General Public License
24 # along with this program; if not, write to the Free Software
25 # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
26 # 02111-1307, USA.
27
28 # Written by Tom Tromey <tromey@redhat.com>, and
29 # Alexandre Duret-Lutz <adl@gnu.org>.
30
31 BEGIN
32 {
33   my $perllibdir = $ENV{'perllibdir'} || '@datadir@/@PACKAGE@-@APIVERSION@';
34   unshift @INC, (split '@PATH_SEPARATOR@', $perllibdir);
35 }
36
37 use strict;
38
39 use Automake::Config;
40 use Automake::General;
41 use Automake::Configure_ac;
42 use Automake::Channels;
43 use Automake::ChannelDefs;
44 use Automake::XFile;
45 use Automake::FileUtils;
46 use File::Basename;
47 use File::stat;
48 use Cwd;
49
50 # Some globals.
51
52 # Include paths for searching macros.  We search macros in this order:
53 # user-supplied directories first, then the directory containing the
54 # automake macros, and finally the system-wide directories for
55 # third-party macro.  @user_includes can be augmented with -I.
56 # @system_includes can be augmented with the `dirlist' file.  Also
57 # --acdir will reset both @automake_includes and @system_includes.
58 my @user_includes = ();
59 my @automake_includes = ("@datadir@/aclocal-$APIVERSION");
60 my @system_includes = ('@datadir@/aclocal');
61
62 # configure.ac or configure.in.
63 my $configure_ac;
64
65 # Output file name.
66 my $output_file = 'aclocal.m4';
67
68 # Modification time of the youngest dependency.
69 my $greatest_mtime = 0;
70
71 # Option --force.
72 my $force_output = 0;
73
74 # Which macros have been seen.
75 my %macro_seen = ();
76
77 # Which files have been seen.
78 my %file_seen = ();
79
80 # Remember the order into which we scanned the files.
81 # It's important to output the contents of aclocal.m4 in the opposite order.
82 # (Definitions in first files we have scanned should override those from
83 # later files.  So they must appear last in the output.)
84 my @file_order = ();
85
86 # Map macro names to file names.
87 my %map = ();
88
89 # Ditto, but records the last definition of each macro as returned by --trace.
90 my %map_traced_defs = ();
91
92 # Map file names to file contents.
93 my %file_contents = ();
94
95 # Map file names to included files (transitively closed).
96 my %file_includes = ();
97
98 # Matches a macro definition.
99 #   AC_DEFUN([macroname], ...)
100 # or
101 #   AC_DEFUN(macroname, ...)
102 # When macroname is `['-quoted , we accept any character in the name,
103 # except `]'.  Otherwise macroname stops on the first `]', `,', `)',
104 # or `\n' encountered.
105 my $ac_defun_rx =
106   "(?:A[CU]_DEFUN|AC_DEFUN_ONCE)\\((?:\\[([^]]+)\\]|([^],)\n]+))";
107
108 # Matches an AC_REQUIRE line.
109 my $ac_require_rx = "AC_REQUIRE\\((?:\\[([^]]+)\\]|([^],)\n]+))\\)";
110
111 # Matches an m4_include line
112 my $m4_include_rx = "(?:m4_)?s?include\\((?:\\[([^]]+)\\]|([^],)\n]+))\\)";
113
114 \f
115 ################################################################
116
117 # Check macros in acinclude.m4.  If one is not used, warn.
118 sub check_acinclude ()
119 {
120   foreach my $key (keys %map)
121     {
122       # FIXME: should print line number of acinclude.m4.
123       msg ('syntax', "warning: macro `$key' defined in "
124            . "acinclude.m4 but never used")
125         if $map{$key} eq 'acinclude.m4' && ! exists $macro_seen{$key};
126     }
127 }
128
129 ################################################################
130
131 # Scan all the installed m4 files and construct a map.
132 sub scan_m4_files (@)
133 {
134   my @dirlist = @_;
135
136   # First, scan configure.ac.  It may contain macro definitions,
137   # or may include other files that define macros.
138   &scan_file ($configure_ac, 'aclocal');
139
140   # Then, scan acinclude.m4 if it exists.
141   if (-f 'acinclude.m4')
142     {
143       &scan_file ('acinclude.m4', 'aclocal');
144     }
145
146   # Finally, scan all files in our search path.
147   foreach my $m4dir (@dirlist)
148     {
149       if (! opendir (DIR, $m4dir))
150         {
151           fatal "couldn't open directory `$m4dir': $!";
152         }
153
154       # We reverse the directory contents so that foo2.m4 gets
155       # used in preference to foo1.m4.
156       foreach my $file (reverse sort grep (! /^\./, readdir (DIR)))
157         {
158           # Only examine .m4 files.
159           next unless $file =~ /\.m4$/;
160
161           # Skip some files when running out of srcdir.
162           next if $file eq 'aclocal.m4';
163
164           my $fullfile = File::Spec->canonpath ("$m4dir/$file");
165             &scan_file ($fullfile, 'aclocal');
166         }
167       closedir (DIR);
168     }
169
170   # Construct a new function that does the searching.  We use a
171   # function (instead of just evaluating $search in the loop) so that
172   # "die" is correctly and easily propagated if run.
173   my $search = "sub search {\nmy \$found = 0;\n";
174   foreach my $key (reverse sort keys %map)
175     {
176       $search .= ('if (/\b\Q' . $key . '\E(?!\w)/) { & add_macro ("' . $key
177                   . '"); $found = 1; }' . "\n");
178     }
179   $search .= "return \$found;\n};\n";
180   eval $search;
181   prog_error "$@\n search is $search" if $@;
182 }
183
184 ################################################################
185
186 # Add a macro to the output.
187 sub add_macro ($)
188 {
189   my ($macro) = @_;
190
191   # Ignore unknown required macros.  Either they are not really
192   # needed (e.g., a conditional AC_REQUIRE), in which case aclocal
193   # should be quiet, or they are needed and Autoconf itself will
194   # complain when we trace for macro usage later.
195   return unless defined $map{$macro};
196
197   verb "saw macro $macro";
198   $macro_seen{$macro} = 1;
199   &add_file ($map{$macro});
200 }
201
202 # scan_configure_dep ($file)
203 # --------------------------
204 # Scan a configure dependency (configure.ac, or separate m4 files)
205 # for uses of know macros and AC_REQUIREs of possibly unknown macros.
206 # Recursively scan m4_included files.
207 my %scanned_configure_dep = ();
208 sub scan_configure_dep ($)
209 {
210   my ($file) = @_;
211   # Do not scan a file twice.
212   return ()
213     if exists $scanned_configure_dep{$file};
214   $scanned_configure_dep{$file} = 1;
215
216   my $mtime = mtime $file;
217   $greatest_mtime = $mtime if $greatest_mtime < $mtime;
218
219   my $contents = exists $file_contents{$file} ?
220     $file_contents{$file} : contents $file;
221
222   my $line = 0;
223   my @rlist = ();
224   my @ilist = ();
225   foreach (split ("\n", $contents))
226     {
227       ++$line;
228       # Remove comments from current line.
229       s/\bdnl\b.*$//;
230       s/\#.*$//;
231
232       while (/$m4_include_rx/go)
233         {
234           push (@ilist, $1 || $2);
235         }
236
237       while (/$ac_require_rx/go)
238         {
239           push (@rlist, $1 || $2);
240         }
241
242       # The search function is constructed dynamically by
243       # scan_m4_files.  The last parenthetical match makes sure we
244       # don't match things that look like macro assignments or
245       # AC_SUBSTs.
246       if (! &search && /(^|\s+)(AM_[A-Z0-9_]+)($|[^\]\)=A-Z0-9_])/)
247         {
248           # Macro not found, but AM_ prefix found.
249           # Make this just a warning, because we do not know whether
250           # the macro is actually used (it could be called conditionally).
251           msg ('unsupported', "$file:$line",
252                "warning: macro `$2' not found in library");
253         }
254     }
255
256   add_macro ($_) foreach (@rlist);
257   my $dirname = dirname $file;
258   &scan_configure_dep (File::Spec->rel2abs ($_, $dirname)) foreach (@ilist);
259 }
260
261 # Add a file to output.
262 sub add_file ($)
263 {
264   my ($file) = @_;
265
266   # Only add a file once.
267   return if ($file_seen{$file});
268   $file_seen{$file} = 1;
269
270   scan_configure_dep $file;
271 }
272
273 # Point to the documentation for underquoted AC_DEFUN only once.
274 my $underquoted_manual_once = 0;
275
276 # scan_file ($FILE, $WHERE)
277 # -------------------------
278 # Scan a single M4 file ($FILE), and all files it includes.
279 # Return the list of included files.
280 # $WHERE is the location to use in the diagnostic if the file
281 # does not exist.
282 sub scan_file ($$)
283 {
284   my ($file, $where) = @_;
285   my $base = dirname $file;
286
287   # Do not scan the same file twice.
288   return @{$file_includes{$file}} if exists $file_includes{$file};
289   # Prevent potential infinite recursion (if two files include each other).
290   return () if exists $file_contents{$file};
291
292   unshift @file_order, $file;
293
294   fatal "$where: file `$file' does not exist" if ! -e $file;
295
296   my $fh = new Automake::XFile $file;
297   my $contents = '';
298   my @inc_files = ();
299   my %inc_lines = ();
300   while ($_ = $fh->getline)
301     {
302       # Ignore `##' lines.
303       next if /^##/;
304
305       $contents .= $_;
306       my $line = $_;
307
308       while ($line =~ /$ac_defun_rx/go)
309         {
310           if (! defined $1)
311             {
312               msg ('syntax', "$file:$.", "warning: underquoted definition of $2"
313                    . "\n  run info '(automake)Extending aclocal'\n"
314                    . "  or see http://sources.redhat.com/automake/"
315                    . "automake.html#Extending-aclocal")
316                 unless $underquoted_manual_once;
317               $underquoted_manual_once = 1;
318             }
319           my $macro = $1 || $2;
320           if (! defined $map{$macro})
321             {
322               verb "found macro $macro in $file: $.";
323               $map{$macro} = $file;
324             }
325           else
326             {
327               # Note: we used to give an error here if we saw a
328               # duplicated macro.  However, this turns out to be
329               # extremely unpopular.  It causes actual problems which
330               # are hard to work around, especially when you must
331               # mix-and-match tool versions.
332               verb "ignoring macro $macro in $file: $.";
333             }
334         }
335
336       while ($line =~ /$m4_include_rx/go)
337         {
338           my $ifile = $1 || $2;
339           # m4_include is relative to the directory of the file which
340           # perform the include, but we want paths relative to the
341           # directory where aclocal is run.  Do not use
342           # File::Spec->rel2abs, because we want to store relative
343           # paths (they might be used later of aclocal outputs an
344           # m4_include for this file, or if the user itself includes
345           # this file).
346           $ifile = "$base/$ifile"
347             unless $base eq '.' || File::Spec->file_name_is_absolute ($ifile);
348           push (@inc_files, $ifile);
349           $inc_lines{$ifile} = $.;
350         }
351     }
352   $file_contents{$file} = $contents;
353
354   # For some reason I don't understand, it does not work
355   # to do `map { scan_file ($_, ...) } @inc_files' below.
356   # With Perl 5.8.2 it undefines @inc_files.
357   my @copy = @inc_files;
358   my @all_inc_files = (@inc_files,
359                        map { scan_file ($_, "$file:$inc_lines{$_}") } @copy);
360   $file_includes{$file} = \@all_inc_files;
361   return @all_inc_files;
362 }
363
364 # strip_redundant_includes (%FILES)
365 # ---------------------------------
366 # Each key in %FILES is a file that must be present in the output.
367 # However some of these files might already include other files in %FILES,
368 # so there is no point in including them another time.
369 # This removes items of %FILES which are already included by another file.
370 sub strip_redundant_includes (%)
371 {
372   my %files = @_;
373   # Files at the end of @file_order should override those at the beginning,
374   # so it is important to preserve these trailing files.  We can remove
375   # a file A if it is going to be output before a file B that includes
376   # file A, not the converse.
377   foreach my $file (reverse @file_order)
378     {
379       next unless exists $files{$file};
380       foreach my $ifile (@{$file_includes{$file}})
381         {
382           next unless exists $files{$ifile};
383           delete $files{$ifile};
384           verb "$ifile is already included by $file";
385         }
386     }
387   return %files;
388 }
389
390 sub trace_used_macros ()
391 {
392   my %files = map { $map{$_} => 1 } keys %macro_seen;
393   $files{'acinclude.m4'} = 1 if -f 'acinclude.m4';
394   %files = strip_redundant_includes %files;
395   # configure.ac is implicitly included.
396   delete $files{$configure_ac};
397
398   my $traces = ($ENV{AUTOM4TE} || 'autom4te');
399   $traces .= " --language Autoconf-without-aclocal-m4 ";
400   # All candidate files.
401   $traces .= join (' ', grep { exists $files{$_} } @file_order) . " ";
402   # All candidate macros.
403   $traces .= join (' ',
404                    (map { "--trace='$_:\$f::\$n::\$1'" } ('AC_DEFUN',
405                                                           'AC_DEFUN_ONCE',
406                                                           'AU_DEFUN')),
407                    # Do not trace $1 for all other macros as we do
408                    # not need it and it might contains harmful
409                    # characters (like newlines).
410                    (map { "--trace='$_:\$f::\$n'" } (keys %macro_seen)));
411
412   verb "running $traces $configure_ac";
413
414   my $tracefh = new Automake::XFile ("$traces $configure_ac |");
415
416   my %traced = ();
417
418   while ($_ = $tracefh->getline)
419     {
420       chomp;
421       my ($file, $macro, $arg1) = split (/::/);
422
423       $traced{$macro} = 1 if exists $macro_seen{$macro};
424
425       $map_traced_defs{$arg1} = $file
426         if ($macro eq 'AC_DEFUN'
427             || $macro eq 'AC_DEFUN_ONCE'
428             || $macro eq 'AU_DEFUN');
429     }
430
431   $tracefh->close;
432
433   return %traced;
434 }
435
436 sub scan_configure ()
437 {
438   # Make sure we include acinclude.m4 if it exists.
439   if (-f 'acinclude.m4')
440     {
441       add_file ('acinclude.m4');
442     }
443   scan_configure_dep ($configure_ac);
444 }
445
446 ################################################################
447
448 # Write output.
449 sub write_aclocal ($@)
450 {
451   my ($output_file, @macros) = @_;
452   my $output = '';
453
454   my %files = ();
455   # Get the list of files containing definitions for the macros used.
456   # (Filter out unused macro definitions with $map_traced_defs.  This
457   # can happen when an Autoconf macro is conditionally defined:
458   # aclocal sees the potential definition, but this definition is
459   # actually never processed and the Autoconf implementation is used
460   # instead.)
461   for my $m (@macros)
462     {
463       $files{$map{$m}} = 1
464         if (exists $map_traced_defs{$m}
465             && $map{$m} eq $map_traced_defs{$m});
466     }
467   $files{'acinclude.m4'} = 1 if -f 'acinclude.m4';
468   %files = strip_redundant_includes %files;
469   delete $files{$configure_ac};
470
471   for my $file (grep { exists $files{$_} } @file_order)
472     {
473       # Check the time stamp of this file, and all files it includes.
474       for my $ifile ($file, @{$file_includes{$file}})
475         {
476           my $mtime = mtime $ifile;
477           $greatest_mtime = $mtime if $greatest_mtime < $mtime;
478         }
479
480       # If the file to add looks like outside the project, copy it
481       # to the output.  The regex catches filenames starting with
482       # things like `/', `\', or `c:\'.
483       if ($file =~ m,^(?:\w:)?[\\/],)
484         {
485           $output .= $file_contents{$file} . "\n";
486         }
487       else
488         {
489           # Otherwise, simply include the file.
490           $output .= "m4_include([$file])\n";
491         }
492     }
493
494   # Nothing to output?!
495   # FIXME: Shouldn't we diagnose this?
496   return if ! length ($output);
497
498   # We used to print `# $output_file generated automatically etc.'  But
499   # this creates spurious differences when using autoreconf.  Autoreconf
500   # creates aclocal.m4t and then rename it to aclocal.m4, but the
501   # rebuild rules generated by Automake create aclocal.m4 directly --
502   # this would gives two ways to get the same file, with a different
503   # name in the header.
504   $output = "# generated automatically by aclocal $VERSION -*- Autoconf -*-
505
506 # Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004
507 # Free Software Foundation, Inc.
508 # This file is free software; the Free Software Foundation
509 # gives unlimited permission to copy and/or distribute it,
510 # with or without modifications, as long as this notice is preserved.
511
512 # This program is distributed in the hope that it will be useful,
513 # but WITHOUT ANY WARRANTY, to the extent permitted by law; without
514 # even the implied warranty of MERCHANTABILITY or FITNESS FOR A
515 # PARTICULAR PURPOSE.
516
517 $output";
518
519   # We try not to update $output_file unless necessary, because
520   # doing so invalidate Autom4te's cache and therefore slows down
521   # tools called after aclocal.
522   #
523   # We need to overwrite $output_file in the following situations.
524   #   * The --force option is in use.
525   #   * One of the dependencies is younger.
526   #     (Not updating $output_file in this situation would cause
527   #     make to call aclocal in loop.)
528   #   * The contents of the current file are different from what
529   #     we have computed.
530   if (!$force_output
531       && $greatest_mtime < mtime ($output_file)
532       && $output eq contents ($output_file))
533     {
534       verb "$output_file unchanged";
535       return;
536     }
537
538   verb "writing $output_file";
539
540   my $out = new Automake::XFile "> $output_file";
541   print $out $output;
542   return;
543 }
544
545 ################################################################
546
547 # Print usage and exit.
548 sub usage ($)
549 {
550   my ($status) = @_;
551
552   print "Usage: aclocal [OPTIONS] ...
553
554 Generate `aclocal.m4' by scanning `configure.ac' or `configure.in'
555
556 Options:
557       --acdir=DIR           directory holding config files (for debugging)
558       --force               always update output file
559       --help                print this help, then exit
560   -I DIR                    add directory to search list for .m4 files
561       --output=FILE         put output in FILE (default aclocal.m4)
562       --print-ac-dir        print name of directory holding m4 files, then exit
563       --verbose             don't be silent
564       --version             print version number, then exit
565   -W, --warnings=CATEGORY   report the warnings falling in CATEGORY
566
567 Warning categories include:
568   `syntax'        dubious syntactic constructs (default)
569   `unsupported'   unknown macros (default)
570   `all'           all the warnings (default)
571   `no-CATEGORY'   turn off warnings in CATEGORY
572   `none'          turn off all the warnings
573   `error'         treat warnings as errors
574
575 Report bugs to <bug-automake\@gnu.org>.\n";
576
577   exit $status;
578 }
579
580 # Print version and exit.
581 sub version()
582 {
583   print "\
584 aclocal (GNU $PACKAGE) $VERSION
585 Written by Tom Tromey <tromey\@redhat.com>
586        and Alexandre Duret-Lutz <adl\@gnu.org>
587 Copyright (C) 2004 Free Software Foundation, Inc.
588 This is free software; see the source for copying conditions.  There is NO
589 warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.";
590   exit 0;
591 }
592
593 # Parse command line.
594 sub parse_arguments ()
595 {
596   my $print_and_exit = 0;
597
598   my %cli_options =
599     (
600      'acdir=s'          => sub # Setting --acdir overrides both the
601                              { # automake (versioned) directory and the
602                                # public (unversioned) system directory.
603                                @automake_includes = ();
604                                @system_includes = ($_[1])
605                              },
606      'force'            => \$force_output,
607      'I=s'              => \@user_includes,
608      'output=s'         => \$output_file,
609      'print_ac_dir'     => \$print_and_exit,
610      'verbose'          => sub { setup_channel 'verb', silent => 0; },
611      'W|warnings:s'     => \&parse_warnings,
612      );
613   use Getopt::Long;
614   Getopt::Long::config ("bundling", "pass_through");
615
616   # See if --version or --help is used.  We want to process these before
617   # anything else because the GNU Coding Standards require us to
618   # `exit 0' after processing these options, and we can't guarantee this
619   # if we treat other options first.  (Handling other options first
620   # could produce error diagnostics, and in this condition it is
621   # confusing if aclocal does `exit 0'.)
622   my %cli_options_1st_pass =
623     (
624      'version' => \&version,
625      'help'    => sub { usage(0); },
626      # Recognize all other options (and their arguments) but do nothing.
627      map { $_ => sub {} } (keys %cli_options)
628      );
629   my @ARGV_backup = @ARGV;
630   Getopt::Long::GetOptions %cli_options_1st_pass
631     or exit 1;
632   @ARGV = @ARGV_backup;
633
634   # Now *really* process the options.  This time we know
635   # that --help and --version are not present.
636   Getopt::Long::GetOptions %cli_options
637     or exit 1;
638
639   if (@ARGV)
640     {
641       fatal ("unrecognized option `$ARGV[0]'\n"
642              . "Try `$0 --help' for more information.");
643     }
644
645   if ($print_and_exit)
646     {
647       print "@system_includes\n";
648       exit 0;
649     }
650
651   if (! -d $system_includes[0])
652     {
653       # By default $(datadir)/aclocal doesn't exist.  We don't want to
654       # get an error in the case where we are searching the default
655       # directory and it hasn't been created.  (We know
656       # @system_includes has its default value if @automake_includes
657       # is not empty, because --acdir is the only way to change this.)
658       @system_includes = () unless @automake_includes;
659     }
660   else
661     {
662       # Finally, adds any directory listed in the `dirlist' file.
663       if (open (DIRLIST, "$system_includes[0]/dirlist"))
664         {
665           while (<DIRLIST>)
666             {
667               # Ignore '#' lines.
668               next if /^#/;
669               # strip off newlines and end-of-line comments
670               s/\s*\#.*$//;
671               chomp;
672               push (@system_includes, $_) if -d $_;
673             }
674           close (DIRLIST);
675         }
676     }
677 }
678
679 ################################################################
680
681 parse_WARNINGS;             # Parse the WARNINGS environment variable.
682 parse_arguments;
683 $configure_ac = require_configure_ac;
684 scan_m4_files (@user_includes, @automake_includes, @system_includes);
685 scan_configure;
686 if (! $exit_code)
687   {
688     my %macro_traced = trace_used_macros;
689     write_aclocal ($output_file, keys %macro_traced);
690   }
691 check_acinclude;
692
693 exit $exit_code;
694
695 ### Setup "GNU" style for perl-mode and cperl-mode.
696 ## Local Variables:
697 ## perl-indent-level: 2
698 ## perl-continued-statement-offset: 2
699 ## perl-continued-brace-offset: 0
700 ## perl-brace-offset: 0
701 ## perl-brace-imaginary-offset: 0
702 ## perl-label-offset: -2
703 ## cperl-indent-level: 2
704 ## cperl-brace-offset: 0
705 ## cperl-continued-brace-offset: 0
706 ## cperl-label-offset: -2
707 ## cperl-extra-newline-before-brace: t
708 ## cperl-merge-trailing-else: nil
709 ## cperl-continued-statement-offset: 2
710 ## End: