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