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