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