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