* lib/Automake/Configure_ac.pm
[platform/upstream/automake.git] / automake.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 # automake - create Makefile.in from Makefile.am
9 # Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003
10 # 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, write to the Free Software
24 # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
25 # 02111-1307, USA.
26
27 # Originally written by David Mackenzie <djm@gnu.ai.mit.edu>.
28 # Perl reimplementation by Tom Tromey <tromey@redhat.com>.
29
30 package Language;
31
32 BEGIN
33 {
34   my $perllibdir = $ENV{'perllibdir'} || '@datadir@/@PACKAGE@-@APIVERSION@';
35   unshift @INC, $perllibdir;
36
37   # Override SHELL.  This is required on DJGPP so that system() uses
38   # bash, not COMMAND.COM which doesn't quote arguments properly.
39   # Other systems aren't expected to use $SHELL when Automake
40   # runs, but it should be safe to drop the `if DJGPP' guard if
41   # it turns up other systems need the same thing.  After all,
42   # if SHELL is used, ./configure's SHELL is always better than
43   # the user's SHELL (which may be something like tcsh).
44   $ENV{'SHELL'} = '@SHELL@' if exists $ENV{'DJGPP'};
45 }
46
47 use Automake::Struct;
48 struct (# Short name of the language (c, f77...).
49         'name' => "\$",
50         # Nice name of the language (C, Fortran 77...).
51         'Name' => "\$",
52
53         # List of configure variables which must be defined.
54         'config_vars' => '@',
55
56         'ansi'    => "\$",
57         # `pure' is `1' or `'.  A `pure' language is one where, if
58         # all the files in a directory are of that language, then we
59         # do not require the C compiler or any code to call it.
60         'pure'   => "\$",
61
62         'autodep' => "\$",
63
64         # Name of the compiling variable (COMPILE).
65         'compiler'  => "\$",
66         # Content of the compiling variable.
67         'compile'  => "\$",
68         # Flag to require compilation without linking (-c).
69         'compile_flag' => "\$",
70         'extensions' => '@',
71         # A subroutine to compute a list of possible extensions of
72         # the product given the input extensions.
73         # (defaults to a subroutine which returns ('.$(OBJEXT)', '.lo'))
74         'output_extensions' => "\$",
75         # A list of flag variables used in 'compile'.
76         # (defaults to [])
77         'flags' => "@",
78
79         # The file to use when generating rules for this language.
80         # The default is 'depend2'.
81         'rule_file' => "\$",
82
83         # Name of the linking variable (LINK).
84         'linker' => "\$",
85         # Content of the linking variable.
86         'link' => "\$",
87
88         # Name of the linker variable (LD).
89         'lder' => "\$",
90         # Content of the linker variable ($(CC)).
91         'ld' => "\$",
92
93         # Flag to specify the output file (-o).
94         'output_flag' => "\$",
95         '_finish' => "\$",
96
97         # This is a subroutine which is called whenever we finally
98         # determine the context in which a source file will be
99         # compiled.
100         '_target_hook' => "\$");
101
102
103 sub finish ($)
104 {
105   my ($self) = @_;
106   if (defined $self->_finish)
107     {
108       &{$self->_finish} ();
109     }
110 }
111
112 sub target_hook ($$$$)
113 {
114     my ($self) = @_;
115     if (defined $self->_target_hook)
116     {
117         &{$self->_target_hook} (@_);
118     }
119 }
120
121 package Automake;
122
123 use strict;
124 use Automake::General;
125 use Automake::XFile;
126 use Automake::Channels;
127 use Automake::ChannelDefs;
128 use Automake::Configure_ac;
129 use Automake::Location;
130 use Automake::Condition qw/TRUE FALSE/;
131 use Automake::DisjConditions;
132 use Automake::Version;
133 use Automake::Variable;
134 use Automake::VarDef;
135 use Automake::Wrap 'makefile_wrap';
136 use File::Basename;
137 use Tie::RefHash;
138 use Carp;
139
140 ## ----------- ##
141 ## Constants.  ##
142 ## ----------- ##
143
144 # Parameters set by configure.  Not to be changed.  NOTE: assign
145 # VERSION as string so that e.g. version 0.30 will print correctly.
146 my $VERSION = '@VERSION@';
147 my $PACKAGE = '@PACKAGE@';
148 my $libdir = '@datadir@/@PACKAGE@-@APIVERSION@';
149
150 # Some regular expressions.  One reason to put them here is that it
151 # makes indentation work better in Emacs.
152
153 # Writing singled-quoted-$-terminated regexes is a pain because
154 # perl-mode thinks of $' as the ${'} variable (instead of a $ followed
155 # by a closing quote.  Letting perl-mode think the quote is not closed
156 # leads to all sort of misindentations.  On the other hand, defining
157 # regexes as double-quoted strings is far less readable.  So usually
158 # we will write:
159 #
160 #  $REGEX = '^regex_value' . "\$";
161
162 my $IGNORE_PATTERN = '^\s*##([^#\n].*)?\n';
163 my $WHITE_PATTERN = '^\s*' . "\$";
164 my $COMMENT_PATTERN = '^#';
165 my $TARGET_PATTERN='[$a-zA-Z_.@%][-.a-zA-Z0-9_(){}/$+@%]*';
166 # A rule has three parts: a list of targets, a list of dependencies,
167 # and optionally actions.
168 my $RULE_PATTERN =
169   "^($TARGET_PATTERN(?:(?:\\\\\n|\\s)+$TARGET_PATTERN)*) *:([^=].*|)\$";
170
171 my $SUFFIX_RULE_PATTERN =
172     '^(\.[a-zA-Z0-9_(){}$+@]+)(\.[a-zA-Z0-9_(){}$+@]+)' . "\$";
173 # Only recognize leading spaces, not leading tabs.  If we recognize
174 # leading tabs here then we need to make the reader smarter, because
175 # otherwise it will think rules like `foo=bar; \' are errors.
176 my $ASSIGNMENT_PATTERN = '^ *([^ \t=:+]*)\s*([:+]?)=\s*(.*)' . "\$";
177 # This pattern recognizes a Gnits version id and sets $1 if the
178 # release is an alpha release.  We also allow a suffix which can be
179 # used to extend the version number with a "fork" identifier.
180 my $GNITS_VERSION_PATTERN = '\d+\.\d+([a-z]|\.\d+)?(-[A-Za-z0-9]+)?';
181
182 my $IF_PATTERN = '^if\s+(!?)\s*([A-Za-z][A-Za-z0-9_]*)\s*(?:#.*)?' . "\$";
183 my $ELSE_PATTERN =
184   '^else(?:\s+(!?)\s*([A-Za-z][A-Za-z0-9_]*))?\s*(?:#.*)?' . "\$";
185 my $ENDIF_PATTERN =
186   '^endif(?:\s+(!?)\s*([A-Za-z][A-Za-z0-9_]*))?\s*(?:#.*)?' . "\$";
187 my $PATH_PATTERN = '(\w|[/.-])+';
188 # This will pass through anything not of the prescribed form.
189 my $INCLUDE_PATTERN = ('^include\s+'
190                        . '((\$\(top_srcdir\)/' . $PATH_PATTERN . ')'
191                        . '|(\$\(srcdir\)/' . $PATH_PATTERN . ')'
192                        . '|([^/\$]' . $PATH_PATTERN . '))\s*(#.*)?' . "\$");
193
194 # This handles substitution references like ${foo:.a=.b}.
195 my $SUBST_REF_PATTERN = "^([^:]*):([^=]*)=(.*)\$";
196
197 # Match `-d' as a command-line argument in a string.
198 my $DASH_D_PATTERN = "(^|\\s)-d(\\s|\$)";
199 # Directories installed during 'install-exec' phase.
200 my $EXEC_DIR_PATTERN =
201   '^(?:bin|sbin|libexec|sysconf|localstate|lib|pkglib|.*exec.*)' . "\$";
202
203 # Constants to define the "strictness" level.
204 use constant FOREIGN => 0;
205 use constant GNU     => 1;
206 use constant GNITS   => 2;
207
208 # Values for AC_CANONICAL_*
209 use constant AC_CANONICAL_HOST   => 1;
210 use constant AC_CANONICAL_SYSTEM => 2;
211
212 # Values indicating when something should be cleaned.
213 use constant MOSTLY_CLEAN     => 0;
214 use constant CLEAN            => 1;
215 use constant DIST_CLEAN       => 2;
216 use constant MAINTAINER_CLEAN => 3;
217
218 # Libtool files.
219 my @libtool_files = qw(ltmain.sh config.guess config.sub);
220 # ltconfig appears here for compatibility with old versions of libtool.
221 my @libtool_sometimes = qw(ltconfig ltcf-c.sh ltcf-cxx.sh ltcf-gcj.sh);
222
223 # Commonly found files we look for and automatically include in
224 # DISTFILES.
225 my @common_files =
226     (qw(ABOUT-GNU ABOUT-NLS AUTHORS BACKLOG COPYING COPYING.DOC COPYING.LIB
227         COPYING.LESSER ChangeLog INSTALL NEWS README THANKS TODO
228         ansi2knr.1 ansi2knr.c compile config.guess config.rpath config.sub
229         configure configure.ac configure.in depcomp elisp-comp
230         install-sh libversion.in mdate-sh missing mkinstalldirs
231         py-compile texinfo.tex ylwrap),
232      @libtool_files, @libtool_sometimes);
233
234 # Commonly used files we auto-include, but only sometimes.
235 my @common_sometimes =
236     qw(aclocal.m4 acconfig.h config.h.top config.h.bot stamp-vti);
237
238 # Standard directories from the GNU Coding Standards, and additional
239 # pkg* directories from Automake.  Stored in a hash for fast member check.
240 my %standard_prefix =
241     map { $_ => 1 } (qw(bin data exec include info lib libexec lisp
242                         localstate man man1 man2 man3 man4 man5 man6
243                         man7 man8 man9 oldinclude pkgdatadir
244                         pkgincludedir pkglibdir sbin sharedstate
245                         sysconf));
246
247 # Copyright on generated Makefile.ins.
248 my $gen_copyright = "\
249 # Copyright 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003
250 # Free Software Foundation, Inc.
251 # This Makefile.in is free software; the Free Software Foundation
252 # gives unlimited permission to copy and/or distribute it,
253 # with or without modifications, as long as this notice is preserved.
254
255 # This program is distributed in the hope that it will be useful,
256 # but WITHOUT ANY WARRANTY, to the extent permitted by law; without
257 # even the implied warranty of MERCHANTABILITY or FITNESS FOR A
258 # PARTICULAR PURPOSE.
259 ";
260
261 # These constants are returned by lang_*_rewrite functions.
262 # LANG_SUBDIR means that the resulting object file should be in a
263 # subdir if the source file is.  In this case the file name cannot
264 # have `..' components.
265 use constant LANG_IGNORE  => 0;
266 use constant LANG_PROCESS => 1;
267 use constant LANG_SUBDIR  => 2;
268
269 # These are used when keeping track of whether an object can be built
270 # by two different paths.
271 use constant COMPILE_LIBTOOL  => 1;
272 use constant COMPILE_ORDINARY => 2;
273
274 # We can't always associate a location to a variable or a rule,
275 # when its defined by Automake.  We use INTERNAL in this case.
276 use constant INTERNAL => new Automake::Location;
277 \f
278
279 ## ---------------------------------- ##
280 ## Variables related to the options.  ##
281 ## ---------------------------------- ##
282
283 # TRUE if we should always generate Makefile.in.
284 my $force_generation = 1;
285
286 # Strictness level as set on command line.
287 my $default_strictness = GNU;
288
289 # Name of strictness level, as set on command line.
290 my $default_strictness_name = 'gnu';
291
292 # This is TRUE if automatic dependency generation code should be
293 # included in generated Makefile.in.
294 my $cmdline_use_dependencies = 1;
295
296 # From the Perl manual.
297 my $symlink_exists = (eval 'symlink ("", "");', $@ eq '');
298
299 # TRUE if missing standard files should be installed.
300 my $add_missing = 0;
301
302 # TRUE if we should copy missing files; otherwise symlink if possible.
303 my $copy_missing = 0;
304
305 # TRUE if we should always update files that we know about.
306 my $force_missing = 0;
307
308
309 ## ---------------------------------------- ##
310 ## Variables filled during files scanning.  ##
311 ## ---------------------------------------- ##
312
313 # Files found by scanning configure.ac for LIBOBJS.
314 my %libsources = ();
315
316 # Names used in AC_CONFIG_HEADER call.
317 my @config_headers = ();
318 # Where AC_CONFIG_HEADER appears.
319 my $config_header_location;
320
321 # Directory where output files go.  Actually, output files are
322 # relative to this directory.
323 my $output_directory;
324
325 # List of Makefile.am's to process, and their corresponding outputs.
326 my @input_files = ();
327 my %output_files = ();
328
329 # Complete list of Makefile.am's that exist.
330 my @configure_input_files = ();
331
332 # List of files in AC_CONFIG_FILES/AC_OUTPUT without Makefile.am's,
333 # and their outputs.
334 my @other_input_files = ();
335 # Where the last AC_CONFIG_FILES/AC_OUTPUT appears.
336 my $ac_config_files_location;
337
338 # List of directories to search for configure-required files.  This
339 # can be set by AC_CONFIG_AUX_DIR.
340 my @config_aux_path = qw(. .. ../..);
341 my $config_aux_dir = '';
342 my $config_aux_dir_set_in_configure_in = 0;
343
344 # Whether AM_GNU_GETTEXT has been seen in configure.ac.
345 my $seen_gettext = 0;
346 # Whether AM_GNU_GETTEXT([external]) is used.
347 my $seen_gettext_external = 0;
348 # Where AM_GNU_GETTEXT appears.
349 my $ac_gettext_location;
350
351 # TRUE if we've seen AC_CANONICAL_(HOST|SYSTEM).
352 my $seen_canonical = 0;
353 my $canonical_location;
354
355 # Where AM_MAINTAINER_MODE appears.
356 my $seen_maint_mode;
357
358 # Actual version we've seen.
359 my $package_version = '';
360
361 # Where version is defined.
362 my $package_version_location;
363
364 # TRUE if we've seen AC_ENABLE_MULTILIB.
365 my $seen_multilib = 0;
366
367 # TRUE if we've seen AM_PROG_CC_C_O
368 my $seen_cc_c_o = 0;
369
370 # Where AM_INIT_AUTOMAKE is called;
371 my $seen_init_automake = 0;
372
373 # TRUE if we've seen AM_AUTOMAKE_VERSION.
374 my $seen_automake_version = 0;
375
376 # Hash table of discovered configure substitutions.  Keys are names,
377 # values are `FILE:LINE' strings which are used by error message
378 # generation.
379 my %configure_vars = ();
380
381 # TRUE if --cygnus seen.
382 my $cygnus_mode = 0;
383
384 # Files included by @configure.
385 my @configure_deps = ();
386
387 # Hash table of AM_CONDITIONAL variables seen in configure.
388 my %configure_cond = ();
389
390 # This maps extensions onto language names.
391 my %extension_map = ();
392
393 # List of the DIST_COMMON files we discovered while reading
394 # configure.in
395 my $configure_dist_common = '';
396
397 # This maps languages names onto objects.
398 my %languages = ();
399
400 # List of targets we must always output.
401 # FIXME: Complete, and remove falsely required targets.
402 my %required_targets =
403   (
404    'all'          => 1,
405    'dvi'          => 1,
406    'pdf'          => 1,
407    'ps'           => 1,
408    'info'         => 1,
409    'install-info' => 1,
410    'install'      => 1,
411    'install-data' => 1,
412    'install-exec' => 1,
413    'uninstall'    => 1,
414
415    # FIXME: Not required, temporary hacks.
416    # Well, actually they are sort of required: the -recursive
417    # targets will run them anyway...
418    'dvi-am'          => 1,
419    'pdf-am'          => 1,
420    'ps-am'           => 1,
421    'info-am'         => 1,
422    'install-data-am' => 1,
423    'install-exec-am' => 1,
424    'installcheck-am' => 1,
425    'uninstall-am' => 1,
426
427    'install-man' => 1,
428   );
429
430 # This is set to 1 when Automake needs to be run again.
431 # (For instance, this happens when an auxiliary file such as
432 # depcomp is added after the toplevel Makefile.in -- which
433 # should distribute depcomp -- has been generated.)
434 my $automake_needs_to_reprocess_all_files = 0;
435
436 # Options set via AM_INIT_AUTOMAKE.
437 my $global_options = '';
438
439 # Same as $suffix_rules (declared below), but records only the
440 # default rules supplied by the languages Automake supports.
441 my $suffix_rules_default;
442
443 # If a file name appears as a key in this hash, then it has already
444 # been checked for.  This variable is local to the "require file"
445 # functions.
446 my %require_file_found = ();
447
448 # The name of the Makefile currently being processed.
449 my $am_file = 'BUG';
450 \f
451
452 ################################################################
453
454 ## ------------------------------------------ ##
455 ## Variables reset by &initialize_per_input.  ##
456 ## ------------------------------------------ ##
457
458 # Basename and relative dir of the input file.
459 my $am_file_name;
460 my $am_relative_dir;
461
462 # Same but wrt Makefile.in.
463 my $in_file_name;
464 my $relative_dir;
465
466 # These two variables are used when generating each Makefile.in.
467 # They hold the Makefile.in until it is ready to be printed.
468 my $output_rules;
469 my $output_vars;
470 my $output_trailer;
471 my $output_all;
472 my $output_header;
473
474 # Suffixes found during a run.
475 my @suffixes;
476
477 # This holds the names which are targets.  These also appear in
478 # %contents.  $targets{TARGET}{COND} is the location of the definition
479 # of TARGET for condition COND.  TARGETs should not include
480 # a trailing $(EXEEXT), we record this in %target_name.
481 my %targets;       tie %targets, 'Tie::RefHash::Nestable';
482
483 # $target_source{TARGET}{COND} is the filename where TARGET
484 # were defined for condition COND.  Note this must be a
485 # filename, *without* any line number.
486 my %target_source; tie %target_source, 'Tie::RefHash::Nestable';
487
488 # $target_name{TARGET}{COND} is the real name of TARGET (in condition COND).
489 # The real name is often TARGET or TARGET$(EXEEXT), and TARGET never
490 # contain $(EXEEXT)
491 my %target_name;   tie %target_name, 'Tie::RefHash::Nestable';
492
493 # $target_owner{TARGET}{COND} the owner of TARGET in condition COND.
494 my %target_owner;  tie %target_owner, 'Tie::RefHash::Nestable';
495 use constant TARGET_AUTOMAKE => 0; # Target defined by Automake.
496 use constant TARGET_USER => 1;  # Target defined in the user's Makefile.am.
497
498 # This is the conditional stack, updated on if/else/endif, and
499 # used to build Condition objects.
500 my @cond_stack;
501
502 # This holds the set of included files.
503 my @include_stack;
504
505 # This holds a list of directories which we must create at `dist'
506 # time.  This is used in some strange scenarios involving weird
507 # AC_OUTPUT commands.
508 my %dist_dirs;
509
510 # List of dependencies for the obvious targets.
511 my @all;
512 my @check;
513 my @check_tests;
514
515 # Holds the dependencies of targets which dependencies are factored.
516 # Typically, `.PHONY' will appear in plenty of *.am files, but must
517 # be output once.  Arguably all pure dependencies could be subject
518 # to this factorization, but it is not unpleasant to have paragraphs
519 # in Makefile: keeping related stuff altogether.
520 my %dependencies;
521
522 # Holds the factored actions.  Tied to %DEPENDENCIES, i.e., filled
523 # only when keys exists in %DEPENDENCIES.
524 my %actions;
525
526 # Keys in this hash table are files to delete.  The associated
527 # value tells when this should happen (MOSTLY_CLEAN, DIST_CLEAN, etc.)
528 my %clean_files;
529
530 # Keys in this hash table are object files or other files in
531 # subdirectories which need to be removed.  This only holds files
532 # which are created by compilations.  The value in the hash indicates
533 # when the file should be removed.
534 my %compile_clean_files;
535
536 # Keys in this hash table are directories where we expect to build a
537 # libtool object.  We use this information to decide what directories
538 # to delete.
539 my %libtool_clean_directories;
540
541 # Value of `$(SOURCES)', used by tags.am.
542 my @sources;
543 # Sources which go in the distribution.
544 my @dist_sources;
545
546 # This hash maps object file names onto their corresponding source
547 # file names.  This is used to ensure that each object is created
548 # by a single source file.
549 my %object_map;
550
551 # This hash maps object file names onto an integer value representing
552 # whether this object has been built via ordinary compilation or
553 # libtool compilation (the COMPILE_* constants).
554 my %object_compilation_map;
555
556
557 # This keeps track of the directories for which we've already
558 # created dirstamp code.
559 my %directory_map;
560
561 # All .P files.
562 my %dep_files;
563
564 # Strictness levels.
565 my $strictness;
566 my $strictness_name;
567
568 # Options from AUTOMAKE_OPTIONS.
569 my %options;
570
571 # Whether or not dependencies are handled.  Can be further changed
572 # in handle_options.
573 my $use_dependencies;
574
575 # This is a list of all targets to run during "make dist".
576 my @dist_targets;
577
578 # Keys in this hash are the basenames of files which must depend on
579 # ansi2knr.  Values are either the empty string, or the directory in
580 # which the ANSI source file appears; the directory must have a
581 # trailing `/'.
582 my %de_ansi_files;
583
584 # This maps the source extension for all suffix rule seen to
585 # a \hash whose keys are the possible output extensions.
586 #
587 # Note that this is transitively closed by construction:
588 # if we have
589 #       exists $suffix_rules{$ext1}{$ext2}
590 #    && exists $suffix_rules{$ext2}{$ext3}
591 # then we also have
592 #       exists $suffix_rules{$ext1}{$ext3}
593 #
594 # So it's easy to check whether '.foo' can be transformed to '.$(OBJEXT)'
595 # by checking whether $suffix_rules{'.foo'}{'.$(OBJEXT)'} exist.  This
596 # will work even if transforming '.foo' to '.$(OBJEXT)' involves a chain
597 # of several suffix rules.
598 #
599 # The value of `$suffix_rules{$ext1}{$ext2}' is the a pair
600 # `[ $next_sfx, $dist ]' where `$next_sfx' is target suffix
601 # for the next rule to use to reach '$ext2', and `$dist' the
602 # distance to `$ext2'.
603 my $suffix_rules;
604
605 # This is the name of the redirect `all' target to use.
606 my $all_target;
607
608 # This keeps track of which extensions we've seen (that we care
609 # about).
610 my %extension_seen;
611
612 # This is random scratch space for the language finish functions.
613 # Don't randomly overwrite it; examine other uses of keys first.
614 my %language_scratch;
615
616 # We keep track of which objects need special (per-executable)
617 # handling on a per-language basis.
618 my %lang_specific_files;
619
620 # This is set when `handle_dist' has finished.  Once this happens,
621 # we should no longer push on dist_common.
622 my $handle_dist_run;
623
624 # Used to store a set of linkers needed to generate the sources currently
625 # under consideration.
626 my %linkers_used;
627
628 # True if we need `LINK' defined.  This is a hack.
629 my $need_link;
630
631 # Was get_object_extension run?
632 # FIXME: This is a hack. a better switch should be found.
633 my $get_object_extension_was_run;
634
635 # This keeps track of all variables defined by gen_varname.
636 # $gen_varname{$base} is a hash for all variable defined with
637 # prefix `$base'.  Values stored this this hash are the variable names.
638 # Keys have the form "(COND1)VAL1(COND2)VAL2..." where VAL1 and VAL2
639 # are the values of the variable for condition COND1 and COND2.
640 my %gen_varname = ();
641
642 ################################################################
643
644 # Pattern that matches all know input extensions (i.e. extensions used
645 # by the languages supported by Automake).  Using this pattern
646 # (instead of `\..*$') to match extensions allows Automake to support
647 # dot-less extensions.
648 my $KNOWN_EXTENSIONS_PATTERN = "";
649 my @known_extensions_list = ();
650
651 # accept_extensions (@EXTS)
652 # -------------------------
653 # Update $KNOWN_EXTENSIONS_PATTERN to recognize the extensions
654 # listed @EXTS.  Extensions should contain a dot if needed.
655 sub accept_extensions (@)
656 {
657     push @known_extensions_list, @_;
658     $KNOWN_EXTENSIONS_PATTERN =
659         '(?:' . join ('|', map (quotemeta, @known_extensions_list)) . ')';
660 }
661
662 # var_SUFFIXES_trigger ($TYPE, $VALUE)
663 # ------------------------------------
664 # This is called automagically by macro_define() when SUFFIXES
665 # is defined ($TYPE eq '') or appended ($TYPE eq '+').
666 # The work here needs to be performed as a side-effect of the
667 # macro_define() call because SUFFIXES definitions impact
668 # on $KNOWN_EXTENSIONS_PATTERN, and $KNOWN_EXTENSIONS_PATTERN
669 # are used when parsing the input am file.
670 sub var_SUFFIXES_trigger ($$)
671 {
672     my ($type, $value) = @_;
673     accept_extensions (split (' ', $value));
674 }
675 Automake::Variable::hook ('SUFFIXES', &var_SUFFIXES_trigger);
676
677 ################################################################
678
679 ## --------------------------------- ##
680 ## Forward subroutine declarations.  ##
681 ## --------------------------------- ##
682 sub register_language (%);
683 sub file_contents_internal ($$$%);
684
685
686 # &initialize_per_input ()
687 # ------------------------
688 # (Re)-Initialize per-Makefile.am variables.
689 sub initialize_per_input ()
690 {
691     reset_local_duplicates ();
692
693     $am_file_name = '';
694     $am_relative_dir = '';
695
696     $in_file_name = '';
697     $relative_dir = '';
698
699     $output_rules = '';
700     $output_vars = '';
701     $output_trailer = '';
702     $output_all = '';
703     $output_header = '';
704
705     @suffixes = ();
706
707     Automake::Variable::reset ();
708
709     %targets = ();
710     %target_source = ();
711     %target_name = ();
712     %target_owner = ();
713
714     @cond_stack = ();
715
716     @include_stack = ();
717
718     %dist_dirs = ();
719
720     @all = ();
721     @check = ();
722     @check_tests = ();
723
724     %dependencies =
725       (
726        # Texinfoing.
727        'dvi'      => [],
728        'dvi-am'   => [],
729        'pdf'      => [],
730        'pdf-am'   => [],
731        'ps'       => [],
732        'ps-am'    => [],
733        'info'     => [],
734        'info-am'  => [],
735        'html'     => [],
736        'html-am'  => [],
737
738        # Installing/uninstalling.
739        'install-data-am'      => [],
740        'install-exec-am'      => [],
741        'uninstall-am'         => [],
742
743        'install-man'          => [],
744        'uninstall-man'        => [],
745
746        'install-info'         => [],
747        'install-info-am'      => [],
748        'uninstall-info'       => [],
749
750        'installcheck-am'      => [],
751
752        # Cleaning.
753        'clean-am'             => [],
754        'mostlyclean-am'       => [],
755        'maintainer-clean-am'  => [],
756        'distclean-am'         => [],
757        'clean'                => [],
758        'mostlyclean'          => [],
759        'maintainer-clean'     => [],
760        'distclean'            => [],
761
762        # Tarballing.
763        'dist-all'             => [],
764
765        # Phoning.
766        '.PHONY'               => []
767       );
768     %actions = ();
769
770     %clean_files = ();
771
772     @sources = ();
773     @dist_sources = ();
774
775     %object_map = ();
776     %object_compilation_map = ();
777
778     %directory_map = ();
779
780     %dep_files = ();
781
782     $strictness = $default_strictness;
783     $strictness_name = $default_strictness_name;
784
785     %options = ();
786
787     $use_dependencies = $cmdline_use_dependencies;
788
789     @dist_targets = ();
790
791     %de_ansi_files = ();
792
793
794     # The first time we initialize the variables,
795     # we save the value of $suffix_rules.
796     if (defined $suffix_rules_default)
797       {
798         $suffix_rules = $suffix_rules_default;
799       }
800     else
801       {
802         $suffix_rules_default = $suffix_rules;
803       }
804
805     $all_target = '';
806
807     %extension_seen = ();
808
809     %language_scratch = ();
810
811     %lang_specific_files = ();
812
813     $handle_dist_run = 0;
814
815     $need_link = 0;
816
817     $get_object_extension_was_run = 0;
818
819     %compile_clean_files = ();
820
821     # We always include `.'.  This isn't strictly correct.
822     %libtool_clean_directories = ('.' => 1);
823
824     %gen_varname = ();
825 }
826
827
828 ################################################################
829
830 # Initialize our list of languages that are internally supported.
831
832 # C.
833 register_language ('name' => 'c',
834                    'Name' => 'C',
835                    'config_vars' => ['CC'],
836                    'ansi' => 1,
837                    'autodep' => '',
838                    'flags' => ['CFLAGS', 'CPPFLAGS'],
839                    'compiler' => 'COMPILE',
840                    'compile' => '$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS)',
841                    'lder' => 'CCLD',
842                    'ld' => '$(CC)',
843                    'linker' => 'LINK',
844                    'link' => '$(CCLD) $(AM_CFLAGS) $(CFLAGS) $(AM_LDFLAGS) $(LDFLAGS) -o $@',
845                    'compile_flag' => '-c',
846                    'extensions' => ['.c'],
847                    '_finish' => \&lang_c_finish);
848
849 # C++.
850 register_language ('name' => 'cxx',
851                    'Name' => 'C++',
852                    'config_vars' => ['CXX'],
853                    'linker' => 'CXXLINK',
854                    'link' => '$(CXXLD) $(AM_CXXFLAGS) $(CXXFLAGS) $(AM_LDFLAGS) $(LDFLAGS) -o $@',
855                    'autodep' => 'CXX',
856                    'flags' => ['CXXFLAGS', 'CPPFLAGS'],
857                    'compile' => '$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS)',
858                    'compiler' => 'CXXCOMPILE',
859                    'compile_flag' => '-c',
860                    'output_flag' => '-o',
861                    'lder' => 'CXXLD',
862                    'ld' => '$(CXX)',
863                    'pure' => 1,
864                    'extensions' => ['.c++', '.cc', '.cpp', '.cxx', '.C']);
865
866 # Objective C.
867 register_language ('name' => 'objc',
868                    'Name' => 'Objective C',
869                    'config_vars' => ['OBJC'],
870                    'linker' => 'OBJCLINK',,
871                    'link' => '$(OBJCLD) $(AM_OBJCFLAGS) $(OBJCFLAGS) $(AM_LDFLAGS) $(LDFLAGS) -o $@',
872                    'autodep' => 'OBJC',
873                    'flags' => ['OBJCFLAGS', 'CPPFLAGS'],
874                    'compile' => '$(OBJC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_OBJCFLAGS) $(OBJCFLAGS)',
875                    'compiler' => 'OBJCCOMPILE',
876                    'compile_flag' => '-c',
877                    'output_flag' => '-o',
878                    'lder' => 'OBJCLD',
879                    'ld' => '$(OBJC)',
880                    'pure' => 1,
881                    'extensions' => ['.m']);
882
883 # Headers.
884 register_language ('name' => 'header',
885                    'Name' => 'Header',
886                    'extensions' => ['.h', '.H', '.hxx', '.h++', '.hh',
887                                     '.hpp', '.inc'],
888                    # No output.
889                    'output_extensions' => sub { return () },
890                    # Nothing to do.
891                    '_finish' => sub { });
892
893 # Yacc (C & C++).
894 register_language ('name' => 'yacc',
895                    'Name' => 'Yacc',
896                    'config_vars' => ['YACC'],
897                    'flags' => ['YFLAGS'],
898                    'compile' => '$(YACC) $(YFLAGS) $(AM_YFLAGS)',
899                    'compiler' => 'YACCCOMPILE',
900                    'extensions' => ['.y'],
901                    'output_extensions' => sub { (my $ext = $_[0]) =~ tr/y/c/;
902                                                 return ($ext,) },
903                    'rule_file' => 'yacc',
904                    '_finish' => \&lang_yacc_finish,
905                    '_target_hook' => \&lang_yacc_target_hook);
906 register_language ('name' => 'yaccxx',
907                    'Name' => 'Yacc (C++)',
908                    'config_vars' => ['YACC'],
909                    'rule_file' => 'yacc',
910                    'flags' => ['YFLAGS'],
911                    'compiler' => 'YACCCOMPILE',
912                    'compile' => '$(YACC) $(YFLAGS) $(AM_YFLAGS)',
913                    'extensions' => ['.y++', '.yy', '.yxx', '.ypp'],
914                    'output_extensions' => sub { (my $ext = $_[0]) =~ tr/y/c/;
915                                                 return ($ext,) },
916                    '_finish' => \&lang_yacc_finish,
917                    '_target_hook' => \&lang_yacc_target_hook);
918
919 # Lex (C & C++).
920 register_language ('name' => 'lex',
921                    'Name' => 'Lex',
922                    'config_vars' => ['LEX'],
923                    'rule_file' => 'lex',
924                    'flags' => ['LFLAGS'],
925                    'compile' => '$(LEX) $(LFLAGS) $(AM_LFLAGS)',
926                    'compiler' => 'LEXCOMPILE',
927                    'extensions' => ['.l'],
928                    'output_extensions' => sub { (my $ext = $_[0]) =~ tr/l/c/;
929                                                 return ($ext,) },
930                    '_finish' => \&lang_lex_finish,
931                    '_target_hook' => \&lang_lex_target_hook);
932 register_language ('name' => 'lexxx',
933                    'Name' => 'Lex (C++)',
934                    'config_vars' => ['LEX'],
935                    'rule_file' => 'lex',
936                    'flags' => ['LFLAGS'],
937                    'compile' => '$(LEX) $(LFLAGS) $(AM_LFLAGS)',
938                    'compiler' => 'LEXCOMPILE',
939                    'extensions' => ['.l++', '.ll', '.lxx', '.lpp'],
940                    'output_extensions' => sub { (my $ext = $_[0]) =~ tr/l/c/;
941                                                 return ($ext,) },
942                    '_finish' => \&lang_lex_finish,
943                    '_target_hook' => \&lang_lex_target_hook);
944
945 # Assembler.
946 register_language ('name' => 'asm',
947                    'Name' => 'Assembler',
948                    'config_vars' => ['CCAS', 'CCASFLAGS'],
949
950                    'flags' => ['CCASFLAGS'],
951                    # Users can set AM_ASFLAGS to includes DEFS, INCLUDES,
952                    # or anything else required.  They can also set AS.
953                    'compile' => '$(CCAS) $(AM_CCASFLAGS) $(CCASFLAGS)',
954                    'compiler' => 'CCASCOMPILE',
955                    'compile_flag' => '-c',
956                    'extensions' => ['.s', '.S'],
957
958                    # With assembly we still use the C linker.
959                    '_finish' => \&lang_c_finish);
960
961 # Fortran 77
962 register_language ('name' => 'f77',
963                    'Name' => 'Fortran 77',
964                    'linker' => 'F77LINK',
965                    'link' => '$(F77LD) $(AM_FFLAGS) $(FFLAGS) $(AM_LDFLAGS) $(LDFLAGS) -o $@',
966                    'flags' => ['FFLAGS'],
967                    'compile' => '$(F77) $(AM_FFLAGS) $(FFLAGS)',
968                    'compiler' => 'F77COMPILE',
969                    'compile_flag' => '-c',
970                    'output_flag' => '-o',
971                    'lder' => 'F77LD',
972                    'ld' => '$(F77)',
973                    'pure' => 1,
974                    'extensions' => ['.f', '.for', '.f90']);
975
976 # Preprocessed Fortran 77
977 #
978 # The current support for preprocessing Fortran 77 just involves
979 # passing `$(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS)
980 # $(CPPFLAGS)' as additional flags to the Fortran 77 compiler, since
981 # this is how GNU Make does it; see the `GNU Make Manual, Edition 0.51
982 # for `make' Version 3.76 Beta' (specifically, from info file
983 # `(make)Catalogue of Rules').
984 #
985 # A better approach would be to write an Autoconf test
986 # (i.e. AC_PROG_FPP) for a Fortran 77 preprocessor, because not all
987 # Fortran 77 compilers know how to do preprocessing.  The Autoconf
988 # macro AC_PROG_FPP should test the Fortran 77 compiler first for
989 # preprocessing capabilities, and then fall back on cpp (if cpp were
990 # available).
991 register_language ('name' => 'ppf77',
992                    'Name' => 'Preprocessed Fortran 77',
993                    'config_vars' => ['F77'],
994                    'linker' => 'F77LINK',
995                    'link' => '$(F77LD) $(AM_FFLAGS) $(FFLAGS) $(AM_LDFLAGS) $(LDFLAGS) -o $@',
996                    'lder' => 'F77LD',
997                    'ld' => '$(F77)',
998                    'flags' => ['FFLAGS', 'CPPFLAGS'],
999                    'compiler' => 'PPF77COMPILE',
1000                    'compile' => '$(F77) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_FFLAGS) $(FFLAGS)',
1001                    'compile_flag' => '-c',
1002                    'output_flag' => '-o',
1003                    'pure' => 1,
1004                    'extensions' => ['.F']);
1005
1006 # Ratfor.
1007 register_language ('name' => 'ratfor',
1008                    'Name' => 'Ratfor',
1009                    'config_vars' => ['F77'],
1010                    'linker' => 'F77LINK',
1011                    'link' => '$(F77LD) $(AM_FFLAGS) $(FFLAGS) $(AM_LDFLAGS) $(LDFLAGS) -o $@',
1012                    'lder' => 'F77LD',
1013                    'ld' => '$(F77)',
1014                    'flags' => ['RFLAGS', 'FFLAGS'],
1015                    # FIXME also FFLAGS.
1016                    'compile' => '$(F77) $(AM_FFLAGS) $(FFLAGS) $(AM_RFLAGS) $(RFLAGS)',
1017                    'compiler' => 'RCOMPILE',
1018                    'compile_flag' => '-c',
1019                    'output_flag' => '-o',
1020                    'pure' => 1,
1021                    'extensions' => ['.r']);
1022
1023 # Java via gcj.
1024 register_language ('name' => 'java',
1025                    'Name' => 'Java',
1026                    'config_vars' => ['GCJ'],
1027                    'linker' => 'GCJLINK',
1028                    'link' => '$(GCJLD) $(AM_GCJFLAGS) $(GCJFLAGS) $(AM_LDFLAGS) $(LDFLAGS) -o $@',
1029                    'autodep' => 'GCJ',
1030                    'flags' => ['GCJFLAGS'],
1031                    'compile' => '$(GCJ) $(AM_GCJFLAGS) $(GCJFLAGS)',
1032                    'compiler' => 'GCJCOMPILE',
1033                    'compile_flag' => '-c',
1034                    'output_flag' => '-o',
1035                    'lder' => 'GCJLD',
1036                    'ld' => '$(GCJ)',
1037                    'pure' => 1,
1038                    'extensions' => ['.java', '.class', '.zip', '.jar']);
1039
1040 ################################################################
1041
1042 # Error reporting functions.
1043
1044 # err_target ($TARGETNAME, $MESSAGE, [%OPTIONS])
1045 # ----------------------------------------------
1046 # Uncategorized errors about targets.
1047 sub err_target ($$;%)
1048 {
1049   msg_target ('error', @_);
1050 }
1051
1052 # err_cond_target ($COND, $TARGETNAME, $MESSAGE, [%OPTIONS])
1053 # ----------------------------------------------------------
1054 # Uncategorized errors about conditional targets.
1055 sub err_cond_target ($$$;%)
1056 {
1057   msg_cond_target ('error', @_);
1058 }
1059
1060 # err_am ($MESSAGE, [%OPTIONS])
1061 # -----------------------------
1062 # Uncategorized errors about the current Makefile.am.
1063 sub err_am ($;%)
1064 {
1065   msg_am ('error', @_);
1066 }
1067
1068 # err_ac ($MESSAGE, [%OPTIONS])
1069 # -----------------------------
1070 # Uncategorized errors about configure.ac.
1071 sub err_ac ($;%)
1072 {
1073   msg_ac ('error', @_);
1074 }
1075
1076 # msg_cond_target ($CHANNEL, $COND, $TARGETNAME, $MESSAGE, [%OPTIONS])
1077 # --------------------------------------------------------------------
1078 # Messages about conditional targets.
1079 sub msg_cond_target ($$$$;%)
1080 {
1081   my ($channel, $cond, $target, $msg, %opts) = @_;
1082   msg $channel, $targets{$target}{$cond}, $msg, %opts;
1083 }
1084
1085 # msg_target ($CHANNEL, $TARGETNAME, $MESSAGE, [%OPTIONS])
1086 # --------------------------------------------------------
1087 # Messages about targets.
1088 sub msg_target ($$$;%)
1089 {
1090   my ($channel, $target, $msg, %opts) = @_;
1091   # Don't know which condition is concerned.  Pick any.
1092   my $cond = target_conditions ($target)->one_cond;
1093   msg_cond_target ($channel, $cond, $target, $msg, %opts);
1094 }
1095
1096 # msg_am ($CHANNEL, $MESSAGE, [%OPTIONS])
1097 # ---------------------------------------
1098 # Messages about about the current Makefile.am.
1099 sub msg_am ($$;%)
1100 {
1101   my ($channel, $msg, %opts) = @_;
1102   msg $channel, "${am_file}.am", $msg, %opts;
1103 }
1104
1105 # msg_ac ($CHANNEL, $MESSAGE, [%OPTIONS])
1106 # ---------------------------------------
1107 # Messages about about configure.ac.
1108 sub msg_ac ($$;%)
1109 {
1110   my ($channel, $msg, %opts) = @_;
1111   msg $channel, $configure_ac, $msg, %opts;
1112 }
1113
1114 # $BOOL
1115 # reject_target ($VAR, $ERROR_MSG)
1116 # --------------------------------
1117 sub reject_target ($$)
1118 {
1119   my ($target, $msg) = @_;
1120   if (target_defined ($target))
1121     {
1122       err_target $target, $msg;
1123       return 1;
1124     }
1125   return 0;
1126 }
1127
1128 ################################################################
1129
1130 # subst ($TEXT)
1131 # -------------
1132 # Return a configure-style substitution using the indicated text.
1133 # We do this to avoid having the substitutions directly in automake.in;
1134 # when we do that they are sometimes removed and this causes confusion
1135 # and bugs.
1136 sub subst ($)
1137 {
1138     my ($text) = @_;
1139     return '@' . $text . '@';
1140 }
1141
1142 ################################################################
1143
1144
1145 # $BACKPATH
1146 # &backname ($REL-DIR)
1147 # --------------------
1148 # If I `cd $REL-DIR', then to come back, I should `cd $BACKPATH'.
1149 # For instance `src/foo' => `../..'.
1150 # Works with non strictly increasing paths, i.e., `src/../lib' => `..'.
1151 sub backname ($)
1152 {
1153     my ($file) = @_;
1154     my @res;
1155     foreach (split (/\//, $file))
1156     {
1157         next if $_ eq '.' || $_ eq '';
1158         if ($_ eq '..')
1159         {
1160             pop @res;
1161         }
1162         else
1163         {
1164             push (@res, '..');
1165         }
1166     }
1167     return join ('/', @res) || '.';
1168 }
1169
1170 ################################################################
1171
1172 # Generate a Makefile.in given the name of the corresponding Makefile and
1173 # the name of the file output by config.status.
1174 sub generate_makefile
1175 {
1176     my ($output, $makefile) = @_;
1177
1178     # Reset all the Makefile.am related variables.
1179     &initialize_per_input;
1180
1181     # Any warning setting now local to this Makefile.am.
1182     &dup_channel_setup;
1183     # AUTOMAKE_OPTIONS can contains -W flags to disable or enable
1184     # warnings for this file.  So hold any warning issued before
1185     # we have processed AUTOMAKE_OPTIONS.
1186     &buffer_messages ('warning');
1187
1188     # Name of input file ("Makefile.am") and output file
1189     # ("Makefile.in").  These have no directory components.
1190     $am_file_name = basename ($makefile) . '.am';
1191     $in_file_name = basename ($makefile) . '.in';
1192
1193     # $OUTPUT is encoded.  If it contains a ":" then the first element
1194     # is the real output file, and all remaining elements are input
1195     # files.  We don't scan or otherwise deal with these input file,
1196     # other than to mark them as dependencies.  See
1197     # &scan_autoconf_files for details.
1198     my (@secondary_inputs);
1199     ($output, @secondary_inputs) = split (/:/, $output);
1200
1201     $relative_dir = dirname ($output);
1202     $am_relative_dir = dirname ($makefile);
1203
1204     &read_main_am_file ($makefile . '.am');
1205     if (&handle_options)
1206     {
1207       # Process buffered warnings.
1208       &flush_messages;
1209       # Fatal error.  Just return, so we can continue with next file.
1210       return;
1211     }
1212     # Process buffered warnings.
1213     &flush_messages;
1214
1215     # There are a few install-related variables that you should not define.
1216     foreach my $var ('PRE_INSTALL', 'POST_INSTALL', 'NORMAL_INSTALL')
1217       {
1218         my $v = var $var;
1219         if ($v)
1220           {
1221             my $def = $v->def (TRUE);
1222             prog_error "$var not defined in condition TRUE"
1223               unless $def;
1224             reject_var $var, "`$var' should not be defined"
1225               if $def->owner != VAR_AUTOMAKE;
1226           }
1227       }
1228
1229     # Catch some obsolete variables.
1230     msg_var ('obsolete', 'INCLUDES',
1231              "`INCLUDES' is the old name for `AM_CPPFLAGS'")
1232       if variable_defined ('INCLUDES');
1233
1234     # At the toplevel directory, we might need config.guess, config.sub
1235     # or libtool scripts (ltconfig and ltmain.sh).
1236     if ($relative_dir eq '.')
1237     {
1238         # AC_CANONICAL_HOST and AC_CANONICAL_SYSTEM need config.guess and
1239         # config.sub.
1240         require_conf_file ($canonical_location, FOREIGN,
1241                            'config.guess', 'config.sub')
1242           if $seen_canonical;
1243     }
1244
1245     # We still need Makefile.in here, because sometimes the `dist'
1246     # target doesn't re-run automake.
1247     if ($am_relative_dir eq $relative_dir)
1248     {
1249         # Only distribute the files if they are in the same subdir as
1250         # the generated makefile.
1251         &push_dist_common ($in_file_name, $am_file_name);
1252     }
1253
1254     push (@sources, '$(SOURCES)')
1255         if variable_defined ('SOURCES');
1256
1257     # Must do this after reading .am file.
1258     &define_variable ('subdir', $relative_dir, INTERNAL);
1259
1260     # Check first, because we might modify some state.
1261     &check_cygnus;
1262     &check_gnu_standards;
1263     &check_gnits_standards;
1264
1265     &handle_configure ($output, $makefile, @secondary_inputs);
1266     &handle_gettext;
1267     &handle_libraries;
1268     &handle_ltlibraries;
1269     &handle_programs;
1270     &handle_scripts;
1271
1272     # This must run first so that the ANSI2KNR definition is generated
1273     # before it is used by the _.c rules.  We have to do this because
1274     # a variable which is used in a dependency must be defined before
1275     # the target, or else make won't properly see it.
1276     &handle_compile;
1277     # This must be run after all the sources are scanned.
1278     &handle_languages;
1279
1280     # We have to run this after dealing with all the programs.
1281     &handle_libtool;
1282
1283     # Re-init SOURCES.  FIXME: other code shouldn't depend on this
1284     # (but currently does).
1285     Automake::Variable::define ('SOURCES', VAR_AUTOMAKE, '', TRUE,
1286                                 "@sources", '', INTERNAL, VAR_PRETTY);
1287     define_pretty_variable ('DIST_SOURCES', TRUE, INTERNAL, @dist_sources);
1288
1289     &handle_multilib;
1290     &handle_texinfo;
1291     &handle_emacs_lisp;
1292     &handle_python;
1293     &handle_java;
1294     &handle_man_pages;
1295     &handle_data;
1296     &handle_headers;
1297     &handle_subdirs;
1298     &handle_tags;
1299     &handle_minor_options;
1300     &handle_tests;
1301
1302     # This must come after most other rules.
1303     &handle_dist ($makefile);
1304
1305     &handle_footer;
1306     &do_check_merge_target;
1307     &handle_all ($output);
1308
1309     # FIXME: Gross!
1310     if (variable_defined ('lib_LTLIBRARIES') &&
1311         variable_defined ('bin_PROGRAMS'))
1312     {
1313         $output_rules .= "install-binPROGRAMS: install-libLTLIBRARIES\n\n";
1314     }
1315
1316     &handle_install;
1317     &handle_clean;
1318     &handle_factored_dependencies;
1319
1320     # Comes last, because all the above procedures may have
1321     # defined or overridden variables.
1322     $output_vars .= output_variables;
1323
1324     check_typos ();
1325
1326     if (! -d ($output_directory . '/' . $am_relative_dir))
1327     {
1328         mkdir ($output_directory . '/' . $am_relative_dir, 0755);
1329     }
1330
1331     my ($out_file) = $output_directory . '/' . $makefile . ".in";
1332     if (! $force_generation && -e $out_file)
1333     {
1334         my ($am_time) = (stat ($makefile . '.am'))[9];
1335         my ($in_time) = (stat ($out_file))[9];
1336         # FIXME: should cache these times.
1337         my ($conf_time) = (stat ($configure_ac))[9];
1338         # FIXME: how to do unsigned comparison?
1339         if ($am_time < $in_time || $am_time < $conf_time)
1340         {
1341             # No need to update.
1342             return;
1343         }
1344         if (-f 'aclocal.m4')
1345         {
1346             my ($acl_time) = (stat _)[9];
1347             return if ($am_time < $acl_time);
1348         }
1349     }
1350
1351     if (-e "$out_file")
1352     {
1353         unlink ($out_file)
1354             or fatal "cannot remove $out_file: $!\n";
1355     }
1356     my $gm_file = new Automake::XFile "> $out_file";
1357     verb "creating $makefile.in";
1358
1359     print $gm_file $output_vars;
1360     # We make sure that `all:' is the first target.
1361     print $gm_file $output_all;
1362     print $gm_file $output_header;
1363     print $gm_file $output_rules;
1364     print $gm_file $output_trailer;
1365
1366     # Back out any warning setting.
1367     &drop_channel_setup;
1368 }
1369
1370 ################################################################
1371
1372 # $BOOL
1373 # process_option_list ($CONFIG, @OPTIONS)
1374 # ------------------------------
1375 # Process a list of options.  Return 1 on error, 0 otherwise.
1376 # This is a helper for handle_options.  CONFIG is true if we're
1377 # handling global options.
1378 sub process_option_list
1379 {
1380   my ($config, @list) = @_;
1381
1382   # FIXME: We should disallow conditional deffinitions of AUTOMAKE_OPTIONS.
1383   my $where = ($config ?
1384                $seen_init_automake :
1385                rvar ('AUTOMAKE_OPTIONS')->rdef (TRUE)->location);
1386
1387   foreach (@list)
1388     {
1389       $options{$_} = 1;
1390       if ($_ eq 'gnits' || $_ eq 'gnu' || $_ eq 'foreign')
1391         {
1392           &set_strictness ($_);
1393         }
1394       elsif ($_ eq 'cygnus')
1395         {
1396           $cygnus_mode = 1;
1397         }
1398       elsif (/^(.*\/)?ansi2knr$/)
1399         {
1400           # An option like "../lib/ansi2knr" is allowed.  With no
1401           # path prefix, we assume the required programs are in this
1402           # directory.  We save the actual option for later.
1403           $options{'ansi2knr'} = $_;
1404         }
1405       elsif ($_ eq 'no-installman' || $_ eq 'no-installinfo'
1406              || $_ eq 'dist-shar' || $_ eq 'dist-zip'
1407              || $_ eq 'dist-tarZ' || $_ eq 'dist-bzip2'
1408              || $_ eq 'dejagnu' || $_ eq 'no-texinfo.tex'
1409              || $_ eq 'readme-alpha' || $_ eq 'check-news'
1410              || $_ eq 'subdir-objects' || $_ eq 'nostdinc'
1411              || $_ eq 'no-exeext' || $_ eq 'no-define'
1412              || $_ eq 'std-options')
1413         {
1414           # Explicitly recognize these.
1415         }
1416       elsif ($_ eq 'no-dependencies')
1417         {
1418           $use_dependencies = 0;
1419         }
1420       elsif (/^\d+\.\d+(?:\.\d+)?[a-z]?(?:-[A-Za-z0-9]+)?$/)
1421         {
1422           # Got a version number.
1423           if (Automake::Version::check ($VERSION, $&))
1424             {
1425               error ($where, "require Automake $_, but have $VERSION",
1426                      uniq_scope => US_GLOBAL);
1427                 return 1;
1428             }
1429         }
1430       elsif (/^(?:--warnings=|-W)(.*)$/)
1431         {
1432           foreach my $cat (split (',', $1))
1433             {
1434               msg 'unsupported', $where, "unknown warning category `$cat'"
1435                 if switch_warning $cat;
1436             }
1437         }
1438       else
1439         {
1440           error ($where, "option `$_' not recognized",
1441                  uniq_scope => US_GLOBAL);
1442           return 1;
1443         }
1444     }
1445 }
1446
1447 # Handle AUTOMAKE_OPTIONS variable.  Return 1 on error, 0 otherwise.
1448 sub handle_options
1449 {
1450     # Process global options first so that more specific options can
1451     # override.
1452     if (&process_option_list (1, split (' ', $global_options)))
1453     {
1454         return 1;
1455     }
1456
1457     if (variable_defined ('AUTOMAKE_OPTIONS'))
1458     {
1459         if (&process_option_list (0, &variable_value_as_list_recursive ('AUTOMAKE_OPTIONS', TRUE)))
1460         {
1461             return 1;
1462         }
1463     }
1464
1465     if ($strictness == GNITS)
1466     {
1467         $options{'readme-alpha'} = 1;
1468         $options{'std-options'} = 1;
1469         $options{'check-news'} = 1;
1470     }
1471
1472     return 0;
1473 }
1474
1475
1476 # get_object_extension ($OUT)
1477 # ---------------------------
1478 # Return object extension.  Just once, put some code into the output.
1479 # OUT is the name of the output file
1480 sub get_object_extension
1481 {
1482     my ($out) = @_;
1483
1484     # Maybe require libtool library object files.
1485     my $extension = '.$(OBJEXT)';
1486     $extension = '.lo' if ($out =~ /\.la$/);
1487
1488     # Check for automatic de-ANSI-fication.
1489     $extension = '$U' . $extension
1490       if defined $options{'ansi2knr'};
1491
1492     $get_object_extension_was_run = 1;
1493
1494     return $extension;
1495 }
1496
1497
1498 # Call finish function for each language that was used.
1499 sub handle_languages
1500 {
1501     if ($use_dependencies)
1502     {
1503         # Include auto-dep code.  Don't include it if DEP_FILES would
1504         # be empty.
1505         if (&saw_sources_p (0) && keys %dep_files)
1506         {
1507             # Set location of depcomp.
1508             &define_variable ('depcomp', "\$(SHELL) $config_aux_dir/depcomp",
1509                               INTERNAL);
1510             &define_variable ('am__depfiles_maybe', 'depfiles', INTERNAL);
1511
1512             require_conf_file ("$am_file.am", FOREIGN, 'depcomp');
1513
1514             my @deplist = sort keys %dep_files;
1515
1516             # We define this as a conditional variable because BSD
1517             # make can't handle backslashes for continuing comments on
1518             # the following line.
1519             define_pretty_variable ('DEP_FILES',
1520                                     new Automake::Condition ('AMDEP_TRUE'),
1521                                     INTERNAL, @deplist);
1522
1523             # Generate each `include' individually.  Irix 6 make will
1524             # not properly include several files resulting from a
1525             # variable expansion; generating many separate includes
1526             # seems safest.
1527             $output_rules .= "\n";
1528             foreach my $iter (@deplist)
1529             {
1530                 $output_rules .= (subst ('AMDEP_TRUE')
1531                                   . subst ('am__include')
1532                                   . ' '
1533                                   . subst ('am__quote')
1534                                   . $iter
1535                                   . subst ('am__quote')
1536                                   . "\n");
1537             }
1538
1539             # Compute the set of directories to remove in distclean-depend.
1540             my @depdirs = uniq (map { dirname ($_) } @deplist);
1541             $output_rules .= &file_contents ('depend',
1542                                              new Automake::Location,
1543                                              DEPDIRS => "@depdirs");
1544         }
1545     }
1546     else
1547     {
1548         &define_variable ('depcomp', '', INTERNAL);
1549         &define_variable ('am__depfiles_maybe', '', INTERNAL);
1550     }
1551
1552     my %done;
1553
1554     # Is the c linker needed?
1555     my $needs_c = 0;
1556     foreach my $ext (sort keys %extension_seen)
1557     {
1558         next unless $extension_map{$ext};
1559
1560         my $lang = $languages{$extension_map{$ext}};
1561
1562         my $rule_file = $lang->rule_file || 'depend2';
1563
1564         # Get information on $LANG.
1565         my $pfx = $lang->autodep;
1566         my $fpfx = ($pfx eq '') ? 'CC' : $pfx;
1567
1568         my $AMDEP = (($use_dependencies && $lang->autodep ne 'no')
1569                      ? 'AMDEP' : 'FALSE');
1570         my $FASTDEP = (($use_dependencies && $lang->autodep ne 'no')
1571                        ? ('am__fastdep' . $fpfx) : 'FALSE');
1572
1573         my %transform = ('EXT'     => $ext,
1574                          'PFX'     => $pfx,
1575                          'FPFX'    => $fpfx,
1576                          'AMDEP'   => $AMDEP,
1577                          'FASTDEP' => $FASTDEP,
1578                          '-c'      => $lang->compile_flag || '',
1579                          'MORE-THAN-ONE'
1580                                    => (count_files_for_language ($lang->name) > 1));
1581
1582         # Generate the appropriate rules for this extension.
1583         if (($use_dependencies && $lang->autodep ne 'no')
1584             || defined $lang->compile)
1585         {
1586             # Some C compilers don't support -c -o.  Use it only if really
1587             # needed.
1588             my $output_flag = $lang->output_flag || '';
1589             $output_flag = '-o'
1590               if (! $output_flag
1591                   && $lang->name eq 'c'
1592                   && defined $options{'subdir-objects'});
1593
1594             # Compute a possible derived extension.
1595             # This is not used by depend2.am.
1596             my $der_ext = (&{$lang->output_extensions} ($ext))[0];
1597
1598             $output_rules .=
1599               file_contents ($rule_file,
1600                              new Automake::Location,
1601                              %transform,
1602                              GENERIC   => 1,
1603
1604                              'DERIVED-EXT' => $der_ext,
1605
1606                              # In this situation we know that the
1607                              # object is in this directory, so
1608                              # $(DEPDIR) is the correct location for
1609                              # dependencies.
1610                              DEPBASE   => '$(DEPDIR)/$*',
1611                              BASE      => '$*',
1612                              SOURCE    => '$<',
1613                              OBJ       => '$@',
1614                              OBJOBJ    => '$@',
1615                              LTOBJ     => '$@',
1616
1617                              COMPILE   => '$(' . $lang->compiler . ')',
1618                              LTCOMPILE => '$(LT' . $lang->compiler . ')',
1619                              -o        => $output_flag);
1620         }
1621
1622         # Now include code for each specially handled object with this
1623         # language.
1624         my %seen_files = ();
1625         foreach my $file (@{$lang_specific_files{$lang->name}})
1626         {
1627             my ($derived, $source, $obj, $myext) = split (' ', $file);
1628
1629             # We might see a given object twice, for instance if it is
1630             # used under different conditions.
1631             next if defined $seen_files{$obj};
1632             $seen_files{$obj} = 1;
1633
1634             prog_error ("found " . $lang->name .
1635                         " in handle_languages, but compiler not defined")
1636               unless defined $lang->compile;
1637
1638             my $obj_compile = $lang->compile;
1639
1640             # Rewrite each occurence of `AM_$flag' in the compile
1641             # rule into `${derived}_$flag' if it exists.
1642             for my $flag (@{$lang->flags})
1643               {
1644                 my $val = "${derived}_$flag";
1645                 $obj_compile =~ s/\(AM_$flag\)/\($val\)/
1646                   if variable_defined ($val);
1647               }
1648
1649             my $obj_ltcompile = '$(LIBTOOL) --mode=compile ' . $obj_compile;
1650
1651             # We _need_ `-o' for per object rules.
1652             my $output_flag = $lang->output_flag || '-o';
1653
1654             my $depbase = dirname ($obj);
1655             $depbase = ''
1656                 if $depbase eq '.';
1657             $depbase .= '/'
1658                 unless $depbase eq '';
1659             $depbase .= '$(DEPDIR)/' . basename ($obj);
1660
1661             # Support for deansified files in subdirectories is ugly
1662             # enough to deserve an explanation.
1663             #
1664             # A Note about normal ansi2knr processing first.  On
1665             #
1666             #   AUTOMAKE_OPTIONS = ansi2knr
1667             #   bin_PROGRAMS = foo
1668             #   foo_SOURCES = foo.c
1669             #
1670             # we generate rules similar to:
1671             #
1672             #   foo: foo$U.o; link ...
1673             #   foo$U.o: foo$U.c; compile ...
1674             #   foo_.c: foo.c; ansi2knr ...
1675             #
1676             # this is fairly compact, and will call ansi2knr depending
1677             # on the value of $U (`' or `_').
1678             #
1679             # It's harder with subdir sources. On
1680             #
1681             #   AUTOMAKE_OPTIONS = ansi2knr
1682             #   bin_PROGRAMS = foo
1683             #   foo_SOURCES = sub/foo.c
1684             #
1685             # we have to create foo_.c in the current directory.
1686             # (Unless the user asks 'subdir-objects'.)  This is important
1687             # in case the same file (`foo.c') is compiled from other
1688             # directories with different cpp options: foo_.c would
1689             # be preprocessed for only one set of options if it were
1690             # put in the subdirectory.
1691             #
1692             # Because foo$U.o must be built from either foo_.c or
1693             # sub/foo.c we can't be as concise as in the first example.
1694             # Instead we output
1695             #
1696             #   foo: foo$U.o; link ...
1697             #   foo_.o: foo_.c; compile ...
1698             #   foo.o: sub/foo.c; compile ...
1699             #   foo_.c: foo.c; ansi2knr ...
1700             #
1701             # This is why we'll now transform $rule_file twice
1702             # if we detect this case.
1703             # A first time we output the compile rule with `$U'
1704             # replaced by `_' and the source directory removed,
1705             # and another time we simply remove `$U'.
1706             #
1707             # Note that at this point $source (as computed by
1708             # &handle_single_transform_list) is `sub/foo$U.c'.
1709             # This can be confusing: it can be used as-is when
1710             # subdir-objects is set, otherwise you have to know
1711             # it really means `foo_.c' or `sub/foo.c'.
1712             my $objdir = dirname ($obj);
1713             my $srcdir = dirname ($source);
1714             if ($lang->ansi && $obj =~ /\$U/)
1715               {
1716                 prog_error "`$obj' contains \$U, but `$source' doesn't."
1717                   if $source !~ /\$U/;
1718
1719                 (my $source_ = $source) =~ s/\$U/_/g;
1720                 # Explicitely clean the _.c files if they are in
1721                 # a subdirectory. (In the current directory they get
1722                 # erased by a `rm -f *_.c' rule.)
1723                 $clean_files{$source_} = MOSTLY_CLEAN
1724                   if $objdir ne '.';
1725                 # Output an additional rule if _.c and .c are not in
1726                 # the same directory.  (_.c is always in $objdir.)
1727                 if ($objdir ne $srcdir)
1728                   {
1729                     (my $obj_ = $obj) =~ s/\$U/_/g;
1730                     (my $depbase_ = $depbase) =~ s/\$U/_/g;
1731                     $source_ = basename ($source_);
1732
1733                     $output_rules .=
1734                       file_contents ($rule_file,
1735                                      new Automake::Location,
1736                                      %transform,
1737                                      GENERIC   => 0,
1738
1739                                      DEPBASE   => $depbase_,
1740                                      BASE      => $obj_,
1741                                      SOURCE    => $source_,
1742                                      OBJ       => "$obj_$myext",
1743                                      OBJOBJ    => "$obj_.obj",
1744                                      LTOBJ     => "$obj_.lo",
1745
1746                                      COMPILE   => $obj_compile,
1747                                      LTCOMPILE => $obj_ltcompile,
1748                                      -o        => $output_flag);
1749                     $obj =~ s/\$U//g;
1750                     $depbase =~ s/\$U//g;
1751                     $source =~ s/\$U//g;
1752                   }
1753               }
1754
1755             $output_rules .=
1756               file_contents ($rule_file,
1757                              new Automake::Location,
1758                              %transform,
1759                              GENERIC   => 0,
1760
1761                              DEPBASE   => $depbase,
1762                              BASE      => $obj,
1763                              SOURCE    => $source,
1764                              # Use $myext and not `.o' here, in case
1765                              # we are actually building a new source
1766                              # file -- e.g. via yacc.
1767                              OBJ       => "$obj$myext",
1768                              OBJOBJ    => "$obj.obj",
1769                              LTOBJ     => "$obj.lo",
1770
1771                              COMPILE   => $obj_compile,
1772                              LTCOMPILE => $obj_ltcompile,
1773                              -o        => $output_flag);
1774         }
1775
1776         # The rest of the loop is done once per language.
1777         next if defined $done{$lang};
1778         $done{$lang} = 1;
1779
1780         # Load the language dependent Makefile chunks.
1781         my %lang = map { uc ($_) => 0 } keys %languages;
1782         $lang{uc ($lang->name)} = 1;
1783         $output_rules .= file_contents ('lang-compile',
1784                                         new Automake::Location,
1785                                         %transform, %lang);
1786
1787         # If the source to a program consists entirely of code from a
1788         # `pure' language, for instance C++ for Fortran 77, then we
1789         # don't need the C compiler code.  However if we run into
1790         # something unusual then we do generate the C code.  There are
1791         # probably corner cases here that do not work properly.
1792         # People linking Java code to Fortran code deserve pain.
1793         $needs_c ||= ! $lang->pure;
1794
1795         define_compiler_variable ($lang)
1796           if ($lang->compile);
1797
1798         define_linker_variable ($lang)
1799           if ($lang->link);
1800
1801         require_variables ("$am_file.am", $lang->Name . " source seen",
1802                            TRUE, @{$lang->config_vars});
1803
1804         # Call the finisher.
1805         $lang->finish;
1806
1807         # Flags listed in `->flags' are user variables (per GNU Standards),
1808         # they should not be overriden in the Makefile...
1809         my @dont_override = @{$lang->flags};
1810         # ... and so is LDFLAGS.
1811         push @dont_override, 'LDFLAGS' if $lang->link;
1812
1813         foreach my $flag (@dont_override)
1814           {
1815             my $var = var $flag;
1816             if ($var)
1817               {
1818                 for my $cond ($var->conditions->conds)
1819                   {
1820                     if ($var->rdef ($cond)->owner == VAR_MAKEFILE)
1821                       {
1822                         msg_cond_var ('gnu', $cond, $flag,
1823                                       "`$flag' is a user variable, "
1824                                       . "you should not override it;\n"
1825                                       . "use `AM_$flag' instead.");
1826                       }
1827                   }
1828               }
1829           }
1830     }
1831
1832     # If the project is entirely C++ or entirely Fortran 77 (i.e., 1
1833     # suffix rule was learned), don't bother with the C stuff.  But if
1834     # anything else creeps in, then use it.
1835     $needs_c = 1
1836       if $need_link || ((scalar keys %$suffix_rules)
1837                         - (scalar keys %$suffix_rules_default)) > 1;
1838
1839     if ($needs_c)
1840       {
1841         &define_compiler_variable ($languages{'c'})
1842           unless defined $done{$languages{'c'}};
1843         define_linker_variable ($languages{'c'});
1844       }
1845 }
1846
1847 # Check to make sure a source defined in LIBOBJS is not explicitly
1848 # mentioned.  This is a separate function (as opposed to being inlined
1849 # in handle_source_transform) because it isn't always appropriate to
1850 # do this check.
1851 sub check_libobjs_sources
1852 {
1853   my ($one_file, $unxformed) = @_;
1854
1855   foreach my $prefix ('', 'EXTRA_', 'dist_', 'nodist_',
1856                       'dist_EXTRA_', 'nodist_EXTRA_')
1857     {
1858         my @files;
1859         if (variable_defined ($prefix . $one_file . '_SOURCES'))
1860         {
1861             @files = &variable_value_as_list_recursive (
1862                                 ($prefix . $one_file . '_SOURCES'),
1863                                 'all');
1864         }
1865         elsif ($prefix eq '')
1866         {
1867             @files = ($unxformed . '.c');
1868         }
1869         else
1870         {
1871             next;
1872         }
1873
1874         foreach my $file (@files)
1875         {
1876           err_var ($prefix . $one_file . '_SOURCES',
1877                    "automatically discovered file `$file' should not" .
1878                    " be explicitly mentioned")
1879             if defined $libsources{$file};
1880         }
1881     }
1882 }
1883
1884
1885 # @OBJECTS
1886 # handle_single_transform_list ($VAR, $TOPPARENT, $DERIVED, $OBJ, @FILES)
1887 # -----------------------------------------------------------------------
1888 # Does much of the actual work for handle_source_transform.
1889 # Arguments are:
1890 #   $VAR is the name of the variable that the source filenames come from
1891 #   $TOPPARENT is the name of the _SOURCES variable which is being processed
1892 #   $DERIVED is the name of resulting executable or library
1893 #   $OBJ is the object extension (e.g., `$U.lo')
1894 #   @FILES is the list of source files to transform
1895 # Result is a list of the names of objects
1896 # %linkers_used will be updated with any linkers needed
1897 sub handle_single_transform_list ($$$$@)
1898 {
1899     my ($var, $topparent, $derived, $obj, @files) = @_;
1900     my @result = ();
1901     my $nonansi_obj = $obj;
1902     $nonansi_obj =~ s/\$U//g;
1903
1904     # Turn sources into objects.  We use a while loop like this
1905     # because we might add to @files in the loop.
1906     while (scalar @files > 0)
1907     {
1908         $_ = shift @files;
1909
1910         # Configure substitutions in _SOURCES variables are errors.
1911         if (/^\@.*\@$/)
1912         {
1913             err_var ($var,
1914                      "`$var' includes configure substitution `$_', and is " .
1915                      "referred to\nfrom `$topparent': configure " .
1916                      "substitutions are not allowed\nin _SOURCES variables");
1917             next;
1918         }
1919
1920         # If the source file is in a subdirectory then the `.o' is put
1921         # into the current directory, unless the subdir-objects option
1922         # is in effect.
1923
1924         # Split file name into base and extension.
1925         next if ! /^(?:(.*)\/)?([^\/]*)($KNOWN_EXTENSIONS_PATTERN)$/;
1926         my $full = $_;
1927         my $directory = $1 || '';
1928         my $base = $2;
1929         my $extension = $3;
1930
1931         # We must generate a rule for the object if it requires its own flags.
1932         my $renamed = 0;
1933         my ($linker, $object);
1934
1935         # This records whether we've seen a derived source file (e.g.
1936         # yacc output).
1937         my $derived_source = 0;
1938
1939         # This holds the `aggregate context' of the file we are
1940         # currently examining.  If the file is compiled with
1941         # per-object flags, then it will be the name of the object.
1942         # Otherwise it will be `AM'.  This is used by the target hook
1943         # language function.
1944         my $aggregate = 'AM';
1945
1946         $extension = &derive_suffix ($extension, $nonansi_obj);
1947         my $lang;
1948         if ($extension_map{$extension} &&
1949             ($lang = $languages{$extension_map{$extension}}))
1950         {
1951             # Found the language, so see what it says.
1952             &saw_extension ($extension);
1953
1954             # Note: computed subr call.  The language rewrite function
1955             # should return one of the LANG_* constants.  It could
1956             # also return a list whose first value is such a constant
1957             # and whose second value is a new source extension which
1958             # should be applied.  This means this particular language
1959             # generates another source file which we must then process
1960             # further.
1961             my $subr = \&{'lang_' . $lang->name . '_rewrite'};
1962             my ($r, $source_extension)
1963                 = &$subr ($directory, $base, $extension);
1964             # Skip this entry if we were asked not to process it.
1965             next if $r == LANG_IGNORE;
1966
1967             # Now extract linker and other info.
1968             $linker = $lang->linker;
1969
1970             my $this_obj_ext;
1971             if (defined $source_extension)
1972             {
1973                 $this_obj_ext = $source_extension;
1974                 $derived_source = 1;
1975             }
1976             elsif ($lang->ansi)
1977             {
1978                 $this_obj_ext = $obj;
1979             }
1980             else
1981             {
1982                 $this_obj_ext = $nonansi_obj;
1983             }
1984             $object = $base . $this_obj_ext;
1985
1986             # Do we have per-executable flags for this executable?
1987             my $have_per_exec_flags = 0;
1988             foreach my $flag (@{$lang->flags})
1989               {
1990                 if (variable_defined ("${derived}_$flag"))
1991                   {
1992                     $have_per_exec_flags = 1;
1993                     last;
1994                   }
1995               }
1996
1997             if ($have_per_exec_flags)
1998             {
1999                 # We have a per-executable flag in effect for this
2000                 # object.  In this case we rewrite the object's
2001                 # name to ensure it is unique.  We also require
2002                 # the `compile' program to deal with compilers
2003                 # where `-c -o' does not work.
2004
2005                 # We choose the name `DERIVED_OBJECT' to ensure
2006                 # (1) uniqueness, and (2) continuity between
2007                 # invocations.  However, this will result in a
2008                 # name that is too long for losing systems, in
2009                 # some situations.  So we provide _SHORTNAME to
2010                 # override.
2011
2012                 my $dname = $derived;
2013                 if (variable_defined ($derived . '_SHORTNAME'))
2014                 {
2015                     # FIXME: should use the same Condition as
2016                     # the _SOURCES variable.  But this is really
2017                     # silly overkill -- nobody should have
2018                     # conditional shortnames.
2019                     $dname = &variable_value ($derived . '_SHORTNAME');
2020                 }
2021                 $object = $dname . '-' . $object;
2022
2023                 require_conf_file ("$am_file.am", FOREIGN, 'compile')
2024                     if $lang->name eq 'c';
2025
2026                 prog_error ($lang->name . " flags defined without compiler")
2027                   if ! defined $lang->compile;
2028
2029                 $renamed = 1;
2030             }
2031
2032             # If rewrite said it was ok, put the object into a
2033             # subdir.
2034             if ($r == LANG_SUBDIR && $directory ne '')
2035             {
2036                 $object = $directory . '/' . $object;
2037             }
2038
2039             # If doing dependency tracking, then we can't print
2040             # the rule.  If we have a subdir object, we need to
2041             # generate an explicit rule.  Actually, in any case
2042             # where the object is not in `.' we need a special
2043             # rule.  The per-object rules in this case are
2044             # generated later, by handle_languages.
2045             if ($renamed || $directory ne '')
2046             {
2047                 my $obj_sans_ext = substr ($object, 0,
2048                                            - length ($this_obj_ext));
2049                 my $full_ansi = $full;
2050                 if ($lang->ansi && defined $options{'ansi2knr'})
2051                   {
2052                     $full_ansi =~ s/$KNOWN_EXTENSIONS_PATTERN$/\$U$&/;
2053                     $obj_sans_ext .= '$U';
2054                   }
2055
2056                 my $val = ("$full_ansi $obj_sans_ext "
2057                            # Only use $this_obj_ext in the derived
2058                            # source case because in the other case we
2059                            # *don't* want $(OBJEXT) to appear here.
2060                            . ($derived_source ? $this_obj_ext : '.o'));
2061
2062                 # If we renamed the object then we want to use the
2063                 # per-executable flag name.  But if this is simply a
2064                 # subdir build then we still want to use the AM_ flag
2065                 # name.
2066                 if ($renamed)
2067                 {
2068                     $val = "$derived $val";
2069                     $aggregate = $derived;
2070                 }
2071                 else
2072                 {
2073                     $val = "AM $val";
2074                 }
2075
2076                 # Each item on this list is a string consisting of
2077                 # four space-separated values: the derived flag prefix
2078                 # (e.g. for `foo_CFLAGS', it is `foo'), the name of the
2079                 # source file, the base name of the output file, and
2080                 # the extension for the object file.
2081                 push (@{$lang_specific_files{$lang->name}}, $val);
2082             }
2083         }
2084         elsif ($extension eq $nonansi_obj)
2085         {
2086             # This is probably the result of a direct suffix rule.
2087             # In this case we just accept the rewrite.
2088             $object = "$base$extension";
2089             $linker = '';
2090         }
2091         else
2092         {
2093             # No error message here.  Used to have one, but it was
2094             # very unpopular.
2095             # FIXME: we could potentially do more processing here,
2096             # perhaps treating the new extension as though it were a
2097             # new source extension (as above).  This would require
2098             # more restructuring than is appropriate right now.
2099             next;
2100         }
2101
2102         err_am "object `$object' created by `$full' and `$object_map{$object}'"
2103           if (defined $object_map{$object}
2104               && $object_map{$object} ne $full);
2105
2106         my $comp_val = (($object =~ /\.lo$/)
2107                         ? COMPILE_LIBTOOL : COMPILE_ORDINARY);
2108         (my $comp_obj = $object) =~ s/\.lo$/.\$(OBJEXT)/;
2109         if (defined $object_compilation_map{$comp_obj}
2110             && $object_compilation_map{$comp_obj} != 0
2111             # Only see the error once.
2112             && ($object_compilation_map{$comp_obj}
2113                 != (COMPILE_LIBTOOL | COMPILE_ORDINARY))
2114             && $object_compilation_map{$comp_obj} != $comp_val)
2115           {
2116             err_am "object `$object' created both with libtool and without";
2117           }
2118         $object_compilation_map{$comp_obj} |= $comp_val;
2119
2120         if (defined $lang)
2121         {
2122             # Let the language do some special magic if required.
2123             $lang->target_hook ($aggregate, $object, $full);
2124         }
2125
2126         if ($derived_source)
2127           {
2128             prog_error ($lang->name . " has automatic dependency tracking")
2129               if $lang->autodep ne 'no';
2130             # Make sure this new source file is handled next.  That will
2131             # make it appear to be at the right place in the list.
2132             unshift (@files, $object);
2133             # Distribute derived sources unless the source they are
2134             # derived from is not.
2135             &push_dist_common ($object)
2136               unless ($topparent =~ /^(?:nobase_)?nodist_/);
2137             next;
2138           }
2139
2140         $linkers_used{$linker} = 1;
2141
2142         push (@result, $object);
2143
2144         if (! defined $object_map{$object})
2145         {
2146             my @dep_list = ();
2147             $object_map{$object} = $full;
2148
2149             # If resulting object is in subdir, we need to make
2150             # sure the subdir exists at build time.
2151             if ($object =~ /\//)
2152             {
2153                 # FIXME: check that $DIRECTORY is somewhere in the
2154                 # project
2155
2156                 # For Java, the way we're handling it right now, a
2157                 # `..' component doesn't make sense.
2158                 if ($lang->name eq 'java' && $object =~ /(\/|^)\.\.\//)
2159                   {
2160                     err_am "`$full' should not contain a `..' component";
2161                   }
2162
2163                 # Make sure object is removed by `make mostlyclean'.
2164                 $compile_clean_files{$object} = MOSTLY_CLEAN;
2165                 # If we have a libtool object then we also must remove
2166                 # the ordinary .o.
2167                 if ($object =~ /\.lo$/)
2168                 {
2169                     (my $xobj = $object) =~ s,lo$,\$(OBJEXT),;
2170                     $compile_clean_files{$xobj} = MOSTLY_CLEAN;
2171
2172                     # Remove any libtool object in this directory.
2173                     $libtool_clean_directories{$directory} = 1;
2174                 }
2175
2176                 push (@dep_list, require_build_directory ($directory));
2177
2178                 # If we're generating dependencies, we also want
2179                 # to make sure that the appropriate subdir of the
2180                 # .deps directory is created.
2181                 push (@dep_list,
2182                       require_build_directory ($directory . '/$(DEPDIR)'))
2183                     if $use_dependencies;
2184             }
2185
2186             &pretty_print_rule ($object . ':', "\t", @dep_list)
2187                 if scalar @dep_list > 0;
2188         }
2189
2190         # Transform .o or $o file into .P file (for automatic
2191         # dependency code).
2192         if ($lang && $lang->autodep ne 'no')
2193         {
2194             my $depfile = $object;
2195             $depfile =~ s/\.([^.]*)$/.P$1/;
2196             $depfile =~ s/\$\(OBJEXT\)$/o/;
2197             $dep_files{dirname ($depfile) . '/$(DEPDIR)/'
2198                            . basename ($depfile)} = 1;
2199         }
2200     }
2201
2202     return @result;
2203 }
2204
2205 # traverse_variable_recursively ($VAR, &FUN_ITEM, &FUN_COLLECT, [$COND_FILTER])
2206 # -----------------------------------------------------------------------------
2207 # Split the value of the variable named VAR on space, and traverse its
2208 # componants recursively.  If $COND_FILTER is an Automake::Condition,
2209 # process any conditions which are true when $COND_FILTER is true.
2210 # Otherwise, process all conditions.
2211 #
2212 # We distinguish to kinds of items in the content of VARNAME.
2213 # Terms that look like `$(foo)' or `${foo}' are subvarible
2214 # and cause recursion.  Other terms are assumed to be filenames.
2215 #
2216 # Each time a filename is encountered, &FUN_ITEM is called with the
2217 # following arguments:
2218 #   ($var,        -- the variable we are currently traversing
2219 #    $val,        -- the item (i.e., filename) to process
2220 #    $cond,       -- the Condition for the $var definition we are examinating
2221 #                    (ignoring the recursion context)
2222 #    $full_cond)  -- the full Condition, taking into account conditions
2223 #                    inherited from parent variables during recursion
2224 # &FUN_ITEM may return a list of items, they will be passed to &FUN_STRORE
2225 # later on.   Define &FUN_ITEM as `undef' when it serve no purpose, this
2226 # will speed things up.
2227 #
2228 # Once all items of a variable have been processed, the
2229 # result (of the calls to &FUN_ITEMS, or of recursive
2230 # traversals of subvariables) are passed to &FUN_COLLECT.
2231 # &FUN_COLLECT receives three arguments:
2232 #   ($var,         -- the variable being traversed
2233 #    $parent_cond, -- the Condition inherited from parent variables during
2234 #                     recursion
2235 #    @condlist)    -- a list of [$cond, @results] pairs
2236 #                     where each $cond appear only once, and @result
2237 #                     are all the results for this condition.
2238 # Typically you should do `$cond->merge ($parent_cond)' to recompute
2239 # the `$full_cond' associated to @result.
2240 # &FUN_COLLECT may return a list of items, that will be used as the
2241 # result of &traverse_variable_recursively (the top-level, or
2242 # it's recursive calls).
2243
2244 # Contains a stack of `from' and `to' parts of variable
2245 # substitutions currently in force.
2246 my @substfroms;
2247 my @substtos;
2248 # This is used to keep track of which variable definitions we are
2249 # scanning.
2250 my %vars_scanned = ();
2251
2252 sub traverse_variable_recursively ($&&;$)
2253 {
2254   %vars_scanned = ();
2255   @substfroms = ();
2256   @substtos = ();
2257   my ($var, $fun_item, $fun_collect, $cond_filter) = @_;
2258   return traverse_variable_recursively_worker ($var, $var,
2259                                                $fun_item, $fun_collect,
2260                                                $cond_filter, TRUE)
2261 }
2262
2263 # The guts of &traverse_variable_recursively.
2264 sub traverse_variable_recursively_worker ($$&&$$)
2265 {
2266   my ($var, $parent, $fun_item, $fun_collect, $cond_filter, $parent_cond) = @_;
2267
2268   # Don't recurse into undefined variables.
2269   # This will also mark existing variables as examined.
2270   return () if ! variable_defined ($var);
2271
2272   if (defined $vars_scanned{$var})
2273     {
2274       err_var $var, "variable `$var' recursively defined";
2275       return undef;
2276     }
2277   $vars_scanned{$var} = 1;
2278
2279   my @allresults = ();
2280   my $cond_once = 0;
2281   my $v = rvar $var;
2282   foreach my $cond ($v->conditions->conds)
2283     {
2284       if (ref $cond_filter)
2285         {
2286           # Ignore conditions that don't match $cond_filter.
2287           next if ! $cond->true_when ($cond_filter);
2288           # If we found out several definitions of $var
2289           # match $cond_filter then we are in trouble.
2290           # Tell the user we don't support this.
2291           $v->check_defined_unconditionally ($parent, $parent_cond)
2292             if $cond_once;
2293           $cond_once = 1;
2294         }
2295       my @result = ();
2296       my $full_cond = $cond->merge ($parent_cond);
2297       foreach my $val ($v->value_as_list ($cond, $parent, $parent_cond))
2298         {
2299           # If $val is a variable (i.e. ${foo} or $(bar), not a filename),
2300           # handle the sub variable recursively.
2301           # (Backslashes between bracklets, before `}' and `)' are required
2302           # only of Emacs's indentation.)
2303           if ($val =~ /^\$\{([^\}]*)\}$/ || $val =~ /^\$\(([^\)]*)\)$/)
2304             {
2305               my $subvar = $1;
2306
2307               # If the user uses a losing variable name, just ignore it.
2308               # This isn't ideal, but people have requested it.
2309               next if ($subvar =~ /\@.*\@/);
2310
2311
2312               # See if the variable is actually a substitution reference
2313               my ($from, $to);
2314               my @temp_list;
2315               if ($subvar =~ /$SUBST_REF_PATTERN/o)
2316                 {
2317                   $subvar = $1;
2318                   $to = $3;
2319                   $from = quotemeta $2;
2320                 }
2321               push @substfroms, $from;
2322               push @substtos, $to;
2323
2324               my @res =
2325                 &traverse_variable_recursively_worker ($subvar, $parent,
2326                                                        $fun_item, $fun_collect,
2327                                                        $cond_filter,
2328                                                        $full_cond);
2329               push (@result, @res);
2330
2331               pop @substfroms;
2332               pop @substtos;
2333             }
2334             elsif ($fun_item) # $var is a filename we must process
2335             {
2336               my $substnum=$#substfroms;
2337               while ($substnum >= 0)
2338                 {
2339                   $val =~ s/$substfroms[$substnum]$/$substtos[$substnum]/
2340                     if defined $substfroms[$substnum];
2341                   $substnum -= 1;
2342                 }
2343
2344               # Make sure you update the doc of &traverse_variable_recursively
2345               # if you change the prototype of &fun_item.
2346               my @transformed = &$fun_item ($var, $val, $cond, $full_cond);
2347               push (@result, @transformed);
2348             }
2349         }
2350       push (@allresults, [$cond, @result]) if @result;
2351     }
2352
2353   # We only care about _recursive_ variable definitions.  The user
2354   # is free to use the same variable several times in the same definition.
2355   delete $vars_scanned{$var};
2356
2357   # Make sure you update the doc of &traverse_variable_recursively
2358   # if you change the prototype of &fun_collect.
2359   return &$fun_collect ($var, $parent_cond, @allresults);
2360 }
2361
2362 # $VARNAME
2363 # gen_varname ($BASE, @DEFINITIONS)
2364 # ---------------------------------
2365 # Return a variable name starting with $BASE, that will be
2366 # used to store definitions @DEFINITIONS.
2367 # @DEFINITIONS is a list of pair [$COND, @OBJECTS].
2368 #
2369 # If we already have a $BASE-variable containing @DEFINITIONS, reuse it.
2370 # This way, we avoid combinatorial explosion of the generated
2371 # variables.  Especially, in a Makefile such as:
2372 #
2373 # | if FOO1
2374 # | A1=1
2375 # | endif
2376 # |
2377 # | if FOO2
2378 # | A2=2
2379 # | endif
2380 # |
2381 # | ...
2382 # |
2383 # | if FOON
2384 # | AN=N
2385 # | endif
2386 # |
2387 # | B=$(A1) $(A2) ... $(AN)
2388 # |
2389 # | c_SOURCES=$(B)
2390 # | d_SOURCES=$(B)
2391 #
2392 # The generated c_OBJECTS and d_OBJECTS will share the same variable
2393 # definitions.
2394 #
2395 # This setup can be the case of a testsuite containing lots (>100) of
2396 # small C programs, all testing the same set of source files.
2397 sub gen_varname ($@)
2398 {
2399   my $base = shift;
2400   my $key = '';
2401   foreach my $pair (@_)
2402     {
2403       my ($cond, @values) = @$pair;
2404       $key .= "($cond)@values";
2405     }
2406
2407   return $gen_varname{$base}{$key} if exists $gen_varname{$base}{$key};
2408
2409   my $num = 1 + keys (%{$gen_varname{$base}});
2410   my $name = "${base}_${num}";
2411   $gen_varname{$base}{$key} = $name;
2412   return $name;
2413 }
2414
2415 # $RESVAR
2416 # transform_variable_recursively ($VAR, $RESVAR, $BASE,
2417 #                                 $NODEFINE, $WHERE, &FUN_ITEM)
2418 # -------------------------------------------------------------
2419 # Traverse $VAR recursively, and create a $RESVAR variable in which
2420 # each filename in $VAR have been transformed using &FUN_ITEM.
2421 # Helper variables (corresponding to sub-variables of $VAR) are
2422 # created as needed, using $BASE as prefix.
2423 #
2424 # Arguments are:
2425 #   $VAR       source variable to traverse
2426 #   $RESVAR    resulting variable to define
2427 #   $BASE      prefix to use when naming subvariables of $RESVAR
2428 #   $NODEFINE  if true, traverse $VAR but do not define any variable
2429 #              (this assumes &FUN_ITEM has some useful side-effect)
2430 #   $WHERE     context into which variable definitions are done
2431 #   &FUN_ITEM  a transformation function -- see the documentation
2432 #              of &FUN_ITEM in traverse_variable_recursively.
2433 #
2434 # This returns the string "\$($RESVAR)".
2435 sub transform_variable_recursively ($$$$$&)
2436 {
2437   my ($var, $resvar, $base, $nodefine, $where, $fun_item) = @_;
2438
2439   my $res = &traverse_variable_recursively
2440     ($var,
2441      $fun_item,
2442      # The code that define the variable holding the result
2443      # of the recursive transformation of a subvariable.
2444      sub {
2445        my ($subvar, $parent_cond, @allresults) = @_;
2446        # Find a name for the variable, unless this is the top-variable
2447        # for which we want to use $resvar.
2448        my $varname =
2449          ($var ne $subvar) ? gen_varname ($base, @allresults) : $resvar;
2450        # Define the variable if required.
2451        unless ($nodefine)
2452          {
2453            # If the new variable is the source variable, we assume
2454            # we are trying to override a user variable.  Delete
2455            # the old variable first.
2456            variable_delete ($varname) if $varname eq $var;
2457            # Define for all conditions.
2458            foreach my $pair (@allresults)
2459              {
2460                my ($cond, @result) = @$pair;
2461                define_pretty_variable ($varname, $cond, $where, @result);
2462              }
2463          }
2464        return "\$($varname)";
2465      });
2466   return $res;
2467 }
2468
2469 # $LINKER
2470 # define_objects_from_sources ($VAR, $OBJVAR, $NODEFINE, $ONE_FILE,
2471 #                              $OBJ, $PARENT, $TOPPARENT, $WHERE)
2472 # ---------------------------------------------------------------------
2473 # Define an _OBJECTS variable for a _SOURCES variable (or subvariable)
2474 #
2475 # Arguments are:
2476 #   $VAR is the name of the _SOURCES variable
2477 #   $OBJVAR is the name of the _OBJECTS variable if known (otherwise
2478 #     it will be generated and returned).
2479 #   $NODEFINE is a boolean: if true, $OBJVAR will not be defined (but
2480 #     work done to determine the linker will be).
2481 #   $ONE_FILE is the canonical (transformed) name of object to build
2482 #   $OBJ is the object extension (i.e. either `.o' or `.lo').
2483 #   $TOPPARENT is the _SOURCES variable being processed.
2484 #   $WHERE context into which this definition is done
2485 #
2486 # Result is a pair ($LINKER, $OBJVAR):
2487 #    $LINKER is a boolean, true if a linker is needed to deal with the objects
2488 sub define_objects_from_sources ($$$$$$$)
2489 {
2490   my ($var, $objvar, $nodefine, $one_file, $obj, $topparent, $where) = @_;
2491
2492   my $needlinker = "";
2493
2494   transform_variable_recursively
2495     ($var, $objvar, 'am__objects', $nodefine, $where,
2496      # The transfom code to run on each filename.
2497      sub {
2498        my ($subvar, $val, $cond, $full_cond) = @_;
2499        my @trans = &handle_single_transform_list ($subvar, $topparent,
2500                                                   $one_file, $obj, $val);
2501        $needlinker = "true" if @trans;
2502        return @trans;
2503      });
2504
2505   return $needlinker;
2506 }
2507
2508
2509 # Handle SOURCE->OBJECT transform for one program or library.
2510 # Arguments are:
2511 #   canonical (transformed) name of object to build
2512 #   actual name of object to build
2513 #   object extension (i.e. either `.o' or `$o'.
2514 # Return result is name of linker variable that must be used.
2515 # Empty return means just use `LINK'.
2516 sub handle_source_transform
2517 {
2518     # one_file is canonical name.  unxformed is given name.  obj is
2519     # object extension.
2520     my ($one_file, $unxformed, $obj, $where) = @_;
2521
2522     my ($linker) = '';
2523
2524     # No point in continuing if _OBJECTS is defined.
2525     return if reject_var ($one_file . '_OBJECTS',
2526                           $one_file . '_OBJECTS should not be defined');
2527
2528     my %used_pfx = ();
2529     my $needlinker;
2530     %linkers_used = ();
2531     foreach my $prefix ('', 'EXTRA_', 'dist_', 'nodist_',
2532                         'dist_EXTRA_', 'nodist_EXTRA_')
2533     {
2534         my $var = $prefix . $one_file . "_SOURCES";
2535         next
2536           if !variable_defined ($var);
2537
2538         # We are going to define _OBJECTS variables using the prefix.
2539         # Then we glom them all together.  So we can't use the null
2540         # prefix here as we need it later.
2541         my $xpfx = ($prefix eq '') ? 'am_' : $prefix;
2542
2543         # Keep track of which prefixes we saw.
2544         $used_pfx{$xpfx} = 1
2545           unless $prefix =~ /EXTRA_/;
2546
2547         push @sources, "\$($var)";
2548         if ($prefix !~ /^nodist_/)
2549           {
2550             # If the VAR wasn't definined conditionally, we add
2551             # it to DIST_SOURCES as is.  Otherwise we create a
2552             # am__VAR_DIST variable which contains all possible values,
2553             # and add this variable to DIST_SOURCES.
2554             my $distvar = "$var";
2555             if (variable_conditionally_defined ($var))
2556               {
2557                 $distvar = "am__${var}_DIST";
2558                 my @files =
2559                   uniq (variable_value_as_list_recursive ($var, 'all'));
2560                 define_pretty_variable ($distvar, TRUE, $where, @files);
2561               }
2562             push @dist_sources, "\$($distvar)"
2563           }
2564
2565         $needlinker |=
2566             define_objects_from_sources ($var,
2567                                          $xpfx . $one_file . '_OBJECTS',
2568                                          $prefix =~ /EXTRA_/,
2569                                          $one_file, $obj, $var, $where);
2570     }
2571     if ($needlinker)
2572     {
2573         $linker ||= &resolve_linker (%linkers_used);
2574     }
2575
2576     my @keys = sort keys %used_pfx;
2577     if (scalar @keys == 0)
2578     {
2579         &define_variable ($one_file . "_SOURCES", $unxformed . ".c", $where);
2580         push (@sources, $unxformed . '.c');
2581         push (@dist_sources, $unxformed . '.c');
2582
2583         %linkers_used = ();
2584         my (@result) =
2585           &handle_single_transform_list ($one_file . '_SOURCES',
2586                                          $one_file . '_SOURCES',
2587                                          $one_file, $obj,
2588                                          "$unxformed.c");
2589         $linker ||= &resolve_linker (%linkers_used);
2590         define_pretty_variable ($one_file . '_OBJECTS', TRUE, $where, @result);
2591     }
2592     else
2593     {
2594         grep ($_ = '$(' . $_ . $one_file . '_OBJECTS)', @keys);
2595         define_pretty_variable ($one_file . '_OBJECTS', TRUE, $where, @keys);
2596     }
2597
2598     # If we want to use `LINK' we must make sure it is defined.
2599     if ($linker eq '')
2600     {
2601         $need_link = 1;
2602     }
2603
2604     return $linker;
2605 }
2606
2607
2608 # handle_lib_objects ($XNAME, $VAR)
2609 # ---------------------------------
2610 # Special-case ALLOCA and LIBOBJS substitutions in _LDADD or _LIBADD variables.
2611 # Also, generate _DEPENDENCIES variable if appropriate.
2612 # Arguments are:
2613 #   transformed name of object being built, or empty string if no object
2614 #   name of _LDADD/_LIBADD-type variable to examine
2615 # Returns 1 if LIBOBJS seen, 0 otherwise.
2616 sub handle_lib_objects
2617 {
2618   my ($xname, $var) = @_;
2619
2620   prog_error "handle_lib_objects: `$var' undefined"
2621     if ! variable_defined ($var);
2622   prog_error ("handle_lib_objects: unexpected variable name `$var'")
2623     unless $var =~ /^(.*)(?:LIB|LD)ADD$/;
2624   my $prefix = $1 || 'AM_';
2625
2626   my $seen_libobjs = 0;
2627   my $flagvar = 0;
2628
2629   transform_variable_recursively
2630     ($var, $xname . '_DEPENDENCIES', 'am__DEPENDENCIES', ! $xname, INTERNAL,
2631      # Transformation function, run on each filename.
2632      sub {
2633        my ($subvar, $val, $cond, $full_cond) = @_;
2634
2635        if ($val =~ /^-/)
2636          {
2637            # Skip -lfoo and -Ldir silently; these are explicitly allowed.
2638            if ($val !~ /^-[lL]/ &&
2639                # Skip -dlopen and -dlpreopen; these are explicitly allowed
2640                # for Libtool libraries or programs.  (Actually we are a bit
2641                # laxest here since this code also applies to non-libtool
2642                # libraries or programs, for which -dlopen and -dlopreopen
2643                # are pure non-sence.  Diagnosting this doesn't seems very
2644                # important: the developer will quickly get complaints from
2645                # the linker.)
2646                $val !~ /^-dl(?:pre)?open$/ &&
2647                # Only get this error once.
2648                ! $flagvar)
2649              {
2650                $flagvar = 1;
2651                # FIXME: should display a stack of nested variables
2652                # as context when $var != $subvar.
2653                err_var ($var, "linker flags such as `$val' belong in "
2654                         . "`${prefix}LDFLAGS");
2655              }
2656            return ();
2657          }
2658        elsif ($val !~ /^\@.*\@$/)
2659          {
2660            # Assume we have a file of some sort, and output it into the
2661            # dependency variable.  Autoconf substitutions are not output;
2662            # rarely is a new dependency substituted into e.g. foo_LDADD
2663            # -- but bad things (e.g. -lX11) are routinely substituted.
2664            # Note that LIBOBJS and ALLOCA are exceptions to this rule,
2665            # and handled specially below.
2666            return $val;
2667          }
2668        elsif ($val =~ /^\@(LT)?LIBOBJS\@$/)
2669          {
2670            handle_LIBOBJS ($subvar, $full_cond, $1);
2671            $seen_libobjs = 1;
2672            return $val;
2673          }
2674        elsif ($val =~ /^\@(LT)?ALLOCA\@$/)
2675          {
2676            handle_ALLOCA ($subvar, $full_cond, $1);
2677            return $val;
2678          }
2679        else
2680          {
2681            return ();
2682          }
2683      });
2684
2685   return $seen_libobjs;
2686 }
2687
2688 sub handle_LIBOBJS ($$$)
2689 {
2690   my ($var, $cond, $lt) = @_;
2691   $lt ||= '';
2692   my $myobjext = ($1 ? 'l' : '') . 'o';
2693
2694   if (! keys %libsources && ! variable_defined ($lt . 'LIBOBJS'))
2695     {
2696       err_var ($var, "\@${lt}LIBOBJS\@ seen but never set in "
2697                . "`$configure_ac'");
2698     }
2699
2700   foreach my $iter (keys %libsources)
2701     {
2702       if ($iter =~ /\.[cly]$/)
2703         {
2704           &saw_extension ($&);
2705           &saw_extension ('.c');
2706         }
2707
2708       if ($iter =~ /\.h$/)
2709         {
2710           require_file_with_macro ($cond, $var, FOREIGN, $iter);
2711         }
2712       elsif ($iter ne 'alloca.c')
2713         {
2714           my $rewrite = $iter;
2715           $rewrite =~ s/\.c$/.P$myobjext/;
2716           $dep_files{'$(DEPDIR)/' . $rewrite} = 1;
2717           $rewrite = "^" . quotemeta ($iter) . "\$";
2718           # Only require the file if it is not a built source.
2719           if (! variable_defined ('BUILT_SOURCES')
2720               || ! grep (/$rewrite/,
2721                          &variable_value_as_list_recursive ('BUILT_SOURCES',
2722                                                             'all')))
2723             {
2724               require_file_with_macro ($cond, $var, FOREIGN, $iter);
2725             }
2726         }
2727     }
2728 }
2729
2730 sub handle_ALLOCA ($$$)
2731 {
2732   my ($var, $cond, $lt) = @_;
2733   my $myobjext = ($1 ? 'l' : '') . 'o';
2734
2735   err_var ($var, "\@${lt}ALLOCA\@ seen but `AC_FUNC_ALLOCA' not in "
2736            . "`$configure_ac'")
2737     if ! defined $libsources{'alloca.c'};
2738   $dep_files{'$(DEPDIR)/alloca.P' . $myobjext} = 1;
2739   require_file_with_macro ($cond, $var, FOREIGN, 'alloca.c');
2740   &saw_extension ('c');
2741 }
2742
2743 # Canonicalize the input parameter
2744 sub canonicalize
2745 {
2746     my ($string) = @_;
2747     $string =~ tr/A-Za-z0-9_\@/_/c;
2748     return $string;
2749 }
2750
2751 # Canonicalize a name, and check to make sure the non-canonical name
2752 # is never used.  Returns canonical name.  Arguments are name and a
2753 # list of suffixes to check for.
2754 sub check_canonical_spelling
2755 {
2756   my ($name, @suffixes) = @_;
2757
2758   my $xname = &canonicalize ($name);
2759   if ($xname ne $name)
2760     {
2761       foreach my $xt (@suffixes)
2762         {
2763           reject_var ("$name$xt", "use `$xname$xt', not `$name$xt'");
2764         }
2765     }
2766
2767   return $xname;
2768 }
2769
2770
2771 # handle_compile ()
2772 # -----------------
2773 # Set up the compile suite.
2774 sub handle_compile ()
2775 {
2776     return
2777       unless $get_object_extension_was_run;
2778
2779     # Boilerplate.
2780     my $default_includes = '';
2781     if (! defined $options{'nostdinc'})
2782       {
2783         $default_includes = ' -I. -I$(srcdir)';
2784
2785         if (variable_defined ('CONFIG_HEADER'))
2786           {
2787             foreach my $hdr (split (' ', &variable_value ('CONFIG_HEADER')))
2788               {
2789                 $default_includes .= ' -I' . dirname ($hdr);
2790               }
2791           }
2792       }
2793
2794     my (@mostly_rms, @dist_rms);
2795     foreach my $item (sort keys %compile_clean_files)
2796     {
2797         if ($compile_clean_files{$item} == MOSTLY_CLEAN)
2798         {
2799             push (@mostly_rms, "\t-rm -f $item");
2800         }
2801         elsif ($compile_clean_files{$item} == DIST_CLEAN)
2802         {
2803             push (@dist_rms, "\t-rm -f $item");
2804         }
2805         else
2806         {
2807           prog_error 'invalid entry in %compile_clean_files';
2808         }
2809     }
2810
2811     my ($coms, $vars, $rules) =
2812       &file_contents_internal (1, "$libdir/am/compile.am",
2813                                new Automake::Location,
2814                                ('DEFAULT_INCLUDES' => $default_includes,
2815                                 'MOSTLYRMS' => join ("\n", @mostly_rms),
2816                                 'DISTRMS' => join ("\n", @dist_rms)));
2817     $output_vars .= $vars;
2818     $output_rules .= "$coms$rules";
2819
2820     # Check for automatic de-ANSI-fication.
2821     if (defined $options{'ansi2knr'})
2822       {
2823         require_variables_for_variable ('AUTOMAKE_OPTIONS',
2824                                         "option `ansi2knr' is used",
2825                                         "ANSI2KNR", "U");
2826
2827         # topdir is where ansi2knr should be.
2828         if ($options{'ansi2knr'} eq 'ansi2knr')
2829           {
2830             # Only require ansi2knr files if they should appear in
2831             # this directory.
2832             require_file_with_macro (TRUE, 'AUTOMAKE_OPTIONS', FOREIGN,
2833                                      'ansi2knr.c', 'ansi2knr.1');
2834
2835             # ansi2knr needs to be built before subdirs, so unshift it.
2836             unshift (@all, '$(ANSI2KNR)');
2837           }
2838
2839         my $ansi2knr_dir = '';
2840         $ansi2knr_dir = dirname ($options{'ansi2knr'})
2841           if $options{'ansi2knr'} ne 'ansi2knr';
2842
2843         $output_rules .= &file_contents ('ansi2knr',
2844                                          new Automake::Location,
2845                                          'ANSI2KNR-DIR' => $ansi2knr_dir);
2846
2847     }
2848 }
2849
2850 # handle_libtool ()
2851 # -----------------
2852 # Handle libtool rules.
2853 sub handle_libtool
2854 {
2855   return unless variable_defined ('LIBTOOL');
2856
2857   # Libtool requires some files, but only at top level.
2858   require_conf_file_with_macro (TRUE, 'LIBTOOL', FOREIGN, @libtool_files)
2859     if $relative_dir eq '.';
2860
2861   my @libtool_rms;
2862   foreach my $item (sort keys %libtool_clean_directories)
2863     {
2864       my $dir = ($item eq '.') ? '' : "$item/";
2865       # .libs is for Unix, _libs for DOS.
2866       push (@libtool_rms, "\t-rm -rf ${dir}.libs ${dir}_libs");
2867     }
2868
2869   # Output the libtool compilation rules.
2870   $output_rules .= &file_contents ('libtool',
2871                                    new Automake::Location,
2872                                    LTRMS => join ("\n", @libtool_rms));
2873 }
2874
2875 # handle_programs ()
2876 # ------------------
2877 # Handle C programs.
2878 sub handle_programs
2879 {
2880   my @proglist = &am_install_var ('progs', 'PROGRAMS',
2881                                   'bin', 'sbin', 'libexec', 'pkglib',
2882                                   'noinst', 'check');
2883   return if ! @proglist;
2884
2885   my $seen_global_libobjs =
2886     variable_defined ('LDADD') && &handle_lib_objects ('', 'LDADD');
2887
2888   foreach my $pair (@proglist)
2889     {
2890       my ($where, $one_file) = @$pair;
2891
2892       my $seen_libobjs = 0;
2893       my $obj = &get_object_extension ($one_file);
2894
2895       # Strip any $(EXEEXT) suffix the user might have added, or this
2896       # will confuse &handle_source_transform and &check_canonical_spelling.
2897       # We'll add $(EXEEXT) back later anyway.
2898       $one_file =~ s/\$\(EXEEXT\)$//;
2899
2900       # Canonicalize names and check for misspellings.
2901       my $xname = &check_canonical_spelling ($one_file, '_LDADD', '_LDFLAGS',
2902                                              '_SOURCES', '_OBJECTS',
2903                                              '_DEPENDENCIES');
2904
2905       $where->push_context ("while processing program `$one_file'");
2906       $where->set (INTERNAL->get);
2907
2908       my $linker = &handle_source_transform ($xname, $one_file, $obj, $where);
2909
2910       my $xt = '';
2911       if (variable_defined ($xname . "_LDADD"))
2912         {
2913           $seen_libobjs = &handle_lib_objects ($xname, $xname . '_LDADD');
2914           $xt = '_LDADD';
2915         }
2916       else
2917         {
2918           # User didn't define prog_LDADD override.  So do it.
2919           &define_variable ($xname . '_LDADD', '$(LDADD)', $where);
2920
2921           # This does a bit too much work.  But we need it to
2922           # generate _DEPENDENCIES when appropriate.
2923           if (variable_defined ('LDADD'))
2924             {
2925               $seen_libobjs = &handle_lib_objects ($xname, 'LDADD');
2926             }
2927           elsif (! variable_defined ($xname . '_DEPENDENCIES'))
2928             {
2929               &define_variable ($xname . '_DEPENDENCIES', '', $where);
2930             }
2931           $xt = '_SOURCES';
2932         }
2933
2934       reject_var ($xname . '_LIBADD',
2935                   "use `${xname}_LDADD', not `${xname}_LIBADD'");
2936
2937       if (! variable_defined ($xname . '_LDFLAGS'))
2938         {
2939           # Define the prog_LDFLAGS variable.
2940           &define_variable ($xname . '_LDFLAGS', '', $where);
2941         }
2942
2943       # Determine program to use for link.
2944       my $xlink;
2945       if (variable_defined ($xname . '_LINK'))
2946         {
2947           $xlink = $xname . '_LINK';
2948         }
2949       else
2950         {
2951           $xlink = $linker ? $linker : 'LINK';
2952         }
2953
2954       # If the resulting program lies into a subdirectory,
2955       # make sure this directory will exist.
2956       my $dirstamp = require_build_directory_maybe ($one_file);
2957
2958       $output_rules .= &file_contents ('program',
2959                                        $where,
2960                                        PROGRAM  => $one_file,
2961                                        XPROGRAM => $xname,
2962                                        XLINK    => $xlink,
2963                                        DIRSTAMP => $dirstamp,
2964                                        EXEEXT   => '$(EXEEXT)');
2965
2966       if ($seen_libobjs || $seen_global_libobjs)
2967         {
2968           if (variable_defined ($xname . '_LDADD'))
2969             {
2970               &check_libobjs_sources ($xname, $xname . '_LDADD');
2971             }
2972           elsif (variable_defined ('LDADD'))
2973             {
2974               &check_libobjs_sources ($xname, 'LDADD');
2975             }
2976         }
2977     }
2978 }
2979
2980
2981 # handle_libraries ()
2982 # -------------------
2983 # Handle libraries.
2984 sub handle_libraries
2985 {
2986   my @liblist = &am_install_var ('libs', 'LIBRARIES',
2987                                  'lib', 'pkglib', 'noinst', 'check');
2988   return if ! @liblist;
2989
2990   my @prefix = am_primary_prefixes ('LIBRARIES', 0, 'lib', 'pkglib',
2991                                     'noinst', 'check');
2992
2993   require_variables_for_variable ($prefix[0] . '_LIBRARIES',
2994                                   'library used', 'RANLIB')
2995     if (@prefix);
2996
2997   foreach my $pair (@liblist)
2998     {
2999       my ($where, $onelib) = @$pair;
3000
3001       my $seen_libobjs = 0;
3002       # Check that the library fits the standard naming convention.
3003       if (basename ($onelib) !~ /^lib.*\.a/)
3004         {
3005           error $where, "`$onelib' is not a standard library name";
3006         }
3007
3008       $where->push_context ("while processing library `$onelib'");
3009       $where->set (INTERNAL->get);
3010
3011       my $obj = &get_object_extension ($onelib);
3012
3013       # Canonicalize names and check for misspellings.
3014       my $xlib = &check_canonical_spelling ($onelib, '_LIBADD', '_SOURCES',
3015                                             '_OBJECTS', '_DEPENDENCIES',
3016                                             '_AR');
3017
3018       if (! variable_defined ($xlib . '_AR'))
3019         {
3020           &define_variable ($xlib . '_AR', '$(AR) $(ARFLAGS)', $where);
3021         }
3022
3023       # Generate support for conditional object inclusion in
3024       # libraries.
3025       if (variable_defined ($xlib . '_LIBADD'))
3026         {
3027           if (&handle_lib_objects ($xlib, $xlib . '_LIBADD'))
3028             {
3029               $seen_libobjs = 1;
3030             }
3031         }
3032       else
3033         {
3034           &define_variable ($xlib . "_LIBADD", '', $where);
3035         }
3036
3037       reject_var ($xlib . '_LDADD',
3038                   "use `${xlib}_LIBADD', not `${xlib}_LDADD'");
3039
3040       # Make sure we at look at this.
3041       &examine_variable ($xlib . '_DEPENDENCIES');
3042
3043       &handle_source_transform ($xlib, $onelib, $obj, $where);
3044
3045       # If the resulting library lies into a subdirectory,
3046       # make sure this directory will exist.
3047       my $dirstamp = require_build_directory_maybe ($onelib);
3048
3049       $output_rules .= &file_contents ('library',
3050                                        $where,
3051                                        LIBRARY  => $onelib,
3052                                        XLIBRARY => $xlib,
3053                                        DIRSTAMP => $dirstamp);
3054
3055       if ($seen_libobjs)
3056         {
3057           if (variable_defined ($xlib . '_LIBADD'))
3058             {
3059               &check_libobjs_sources ($xlib, $xlib . '_LIBADD');
3060             }
3061         }
3062     }
3063 }
3064
3065
3066 # handle_ltlibraries ()
3067 # ---------------------
3068 # Handle shared libraries.
3069 sub handle_ltlibraries
3070 {
3071   my @liblist = &am_install_var ('ltlib', 'LTLIBRARIES',
3072                                  'noinst', 'lib', 'pkglib', 'check');
3073   return if ! @liblist;
3074
3075   my %instdirs;
3076   my @prefix = am_primary_prefixes ('LTLIBRARIES', 0, 'lib', 'pkglib',
3077                                     'noinst', 'check');
3078
3079   require_variables_for_variable ($prefix[0] . '_LTLIBRARIES',
3080                                   'Libtool library used', 'LIBTOOL')
3081     if (@prefix);
3082
3083   my %liblocations = ();        # Location (in Makefile.am) of each library.
3084
3085   foreach my $key (@prefix)
3086     {
3087       # Get the installation directory of each library.
3088       (my $dir = $key) =~ s/^nobase_//;
3089       for my $pair (variable_loc_and_value_as_list_recursive
3090                     ($key . '_LTLIBRARIES', 'all'))
3091         {
3092           my ($where, $lib) = @$pair;
3093           # We reject libraries which are installed in several places,
3094           # because we don't handle this in the rules (think `-rpath').
3095           #
3096           # However, we allow the same library to be listed many times
3097           # for the same directory.  This is for users who need setups
3098           # like
3099           #   if COND1
3100           #     lib_LTLIBRARIES = libfoo.la
3101           #   endif
3102           #   if COND2
3103           #     lib_LTLIBRARIES = libfoo.la
3104           #   endif
3105           #
3106           # Actually this will also allow
3107           #   lib_LTLIBRARIES = libfoo.la libfoo.la
3108           # Diagnosing this case doesn't seem worth the plain (we'd
3109           # have to fill $instdirs on a per-condition basis, check
3110           # implied conditions, etc.)
3111           if (defined $instdirs{$lib} && $instdirs{$lib} ne $dir)
3112             {
3113               error ($where, "`$lib' is already going to be installed in "
3114                      . "`$instdirs{$lib}'", partial => 1);
3115               error ($liblocations{$lib}, "`$lib' previously declared here");
3116             }
3117           else
3118             {
3119               $instdirs{$lib} = $dir;
3120               $liblocations{$lib} = $where->clone;
3121             }
3122         }
3123     }
3124
3125   foreach my $pair (@liblist)
3126     {
3127       my ($where, $onelib) = @$pair;
3128
3129       my $seen_libobjs = 0;
3130       my $obj = &get_object_extension ($onelib);
3131
3132       # Canonicalize names and check for misspellings.
3133       my $xlib = &check_canonical_spelling ($onelib, '_LIBADD', '_LDFLAGS',
3134                                             '_SOURCES', '_OBJECTS',
3135                                             '_DEPENDENCIES');
3136
3137       # Check that the library fits the standard naming convention.
3138       my $libname_rx = "^lib.*\.la";
3139       if ((variable_defined ($xlib . '_LDFLAGS')
3140            && grep (/-module/,
3141                     &variable_value_as_list_recursive ($xlib . '_LDFLAGS',
3142                                                        'all')))
3143           || (variable_defined ('LDFLAGS')
3144               && grep (/-module/,
3145                        &variable_value_as_list_recursive ('LDFLAGS', 'all'))))
3146         {
3147           # Relax name checking for libtool modules.
3148           $libname_rx = "\.la";
3149         }
3150       if (basename ($onelib) !~ /$libname_rx$/)
3151         {
3152           msg ($where, 'error-gnu/warn',
3153                "`$onelib' is not a standard libtool library name");
3154         }
3155
3156       $where->push_context ("while processing Libtool library `$onelib'");
3157       $where->set (INTERNAL->get);
3158
3159       if (! variable_defined ($xlib . '_LDFLAGS'))
3160         {
3161           # Define the lib_LDFLAGS variable.
3162           &define_variable ($xlib . '_LDFLAGS', '', $where);
3163         }
3164
3165       # Generate support for conditional object inclusion in
3166       # libraries.
3167       if (variable_defined ($xlib . '_LIBADD'))
3168         {
3169           if (&handle_lib_objects ($xlib, $xlib . '_LIBADD'))
3170             {
3171               $seen_libobjs = 1;
3172             }
3173         }
3174       else
3175         {
3176           &define_variable ($xlib . "_LIBADD", '', $where);
3177         }
3178
3179       reject_var ("${xlib}_LDADD",
3180                   "use `${xlib}_LIBADD', not `${xlib}_LDADD'");
3181
3182       # Make sure we at look at this.
3183       &examine_variable ($xlib . '_DEPENDENCIES');
3184
3185       my $linker = &handle_source_transform ($xlib, $onelib, $obj, $where);
3186
3187       # Determine program to use for link.
3188       my $xlink;
3189       if (variable_defined ($xlib . '_LINK'))
3190         {
3191           $xlink = $xlib . '_LINK';
3192         }
3193       else
3194         {
3195           $xlink = $linker ? $linker : 'LINK';
3196         }
3197
3198       my $rpath;
3199       if ($instdirs{$onelib} eq 'EXTRA'
3200           || $instdirs{$onelib} eq 'noinst'
3201           || $instdirs{$onelib} eq 'check')
3202         {
3203           # It's an EXTRA_ library, so we can't specify -rpath,
3204           # because we don't know where the library will end up.
3205           # The user probably knows, but generally speaking automake
3206           # doesn't -- and in fact configure could decide
3207           # dynamically between two different locations.
3208           $rpath = '';
3209         }
3210       else
3211         {
3212           $rpath = ('-rpath $(' . $instdirs{$onelib} . 'dir)');
3213         }
3214
3215       # If the resulting library lies into a subdirectory,
3216       # make sure this directory will exist.
3217       my $dirstamp = require_build_directory_maybe ($onelib);
3218
3219       # Remember to cleanup .libs/ in this directory.
3220       my $dirname = dirname $onelib;
3221       $libtool_clean_directories{$dirname} = 1;
3222
3223       $output_rules .= &file_contents ('ltlibrary',
3224                                        $where,
3225                                        LTLIBRARY  => $onelib,
3226                                        XLTLIBRARY => $xlib,
3227                                        RPATH      => $rpath,
3228                                        XLINK      => $xlink,
3229                                        DIRSTAMP   => $dirstamp);
3230       if ($seen_libobjs)
3231         {
3232           if (variable_defined ($xlib . '_LIBADD'))
3233             {
3234               &check_libobjs_sources ($xlib, $xlib . '_LIBADD');
3235             }
3236         }
3237     }
3238 }
3239
3240 # See if any _SOURCES variable were misspelled.
3241 sub check_typos ()
3242 {
3243   # It is ok if the user sets this particular variable.
3244   &examine_variable ('AM_LDFLAGS');
3245
3246   foreach my $varname (variables)
3247     {
3248       # A configure variable is always legitimate.
3249       next if exists $configure_vars{$varname};
3250
3251       my $check = 0;
3252       foreach my $primary ('_SOURCES', '_LIBADD', '_LDADD', '_LDFLAGS',
3253                            '_DEPENDENCIES')
3254         {
3255           if ($varname =~ /$primary$/)
3256             {
3257               $check = 1;
3258               last;
3259             }
3260         }
3261       next unless $check;
3262
3263       my $var = rvar $varname;
3264
3265       for my $cond ($var->conditions->conds)
3266         {
3267           msg_var 'syntax', $var, "unused variable: `$varname'"
3268             unless $var->rdef ($cond)->seen;
3269         }
3270     }
3271 }
3272
3273
3274 # Handle scripts.
3275 sub handle_scripts
3276 {
3277     # NOTE we no longer automatically clean SCRIPTS, because it is
3278     # useful to sometimes distribute scripts verbatim.  This happens
3279     # e.g. in Automake itself.
3280     &am_install_var ('-candist', 'scripts', 'SCRIPTS',
3281                      'bin', 'sbin', 'libexec', 'pkgdata',
3282                      'noinst', 'check');
3283 }
3284
3285
3286 # ($OUTFILE, $VFILE, @CLEAN_FILES)
3287 # &scan_texinfo_file ($FILENAME)
3288 # ------------------------------
3289 # $OUTFILE is the name of the info file produced by $FILENAME.
3290 # $VFILE is the name of the version.texi file used (empty if none).
3291 # @CLEAN_FILES is the list of by products (indexes etc.)
3292 sub scan_texinfo_file
3293 {
3294     my ($filename) = @_;
3295
3296     # Some of the following extensions are always created, no matter
3297     # whether indexes are used or not.  Other (like cps, fns, ... pgs)
3298     # are only created when they are used.  We used to scan $FILENAME
3299     # for their use, but that is not enough: they could be used in
3300     # included files.  We can't scan included files because we don't
3301     # know the include path.  Therefore we always erase these files,
3302     # no matter whether they are used or not.
3303     #
3304     # (tmp is only created if an @macro is used and a certain e-TeX
3305     # feature is not available.)
3306     my %clean_suffixes =
3307       map { $_ => 1 } (qw(aux log toc tmp
3308                           cp cps
3309                           fn fns
3310                           ky kys
3311                           vr vrs
3312                           tp tps
3313                           pg pgs)); # grep 'new.*index' texinfo.tex
3314
3315     my $texi = new Automake::XFile "< $filename";
3316     verb "reading $filename";
3317
3318     my ($outfile, $vfile);
3319     while ($_ = $texi->getline)
3320     {
3321       if (/^\@setfilename +(\S+)/)
3322       {
3323         # Honor only the first @setfilename.  (It's possible to have
3324         # more occurences later if the manual shows examples of how
3325         # to use @setfilename...)
3326         next if $outfile;
3327
3328         $outfile = $1;
3329         if ($outfile =~ /\.(.+)$/ && $1 ne 'info')
3330           {
3331             error ("$filename:$.",
3332                    "output `$outfile' has unrecognized extension");
3333             return;
3334           }
3335       }
3336       # A "version.texi" file is actually any file whose name
3337       # matches "vers*.texi".
3338       elsif (/^\@include\s+(vers[^.]*\.texi)\s*$/)
3339       {
3340         $vfile = $1;
3341       }
3342
3343       # Try to find new or unused indexes.
3344
3345       # Creating a new category of index.
3346       elsif (/^\@def(code)?index (\w+)/)
3347       {
3348         $clean_suffixes{$2} = 1;
3349         $clean_suffixes{"$2s"} = 1;
3350       }
3351
3352       # Merging an index into an another.
3353       elsif (/^\@syn(code)?index (\w+) (\w+)/)
3354       {
3355         delete $clean_suffixes{"$2s"};
3356         $clean_suffixes{"$3s"} = 1;
3357       }
3358
3359     }
3360
3361     if ($outfile eq '')
3362       {
3363         err_am "`$filename' missing \@setfilename";
3364         return;
3365       }
3366
3367     my $infobase = basename ($filename);
3368     $infobase =~ s/\.te?xi(nfo)?$//;
3369     return ($outfile, $vfile,
3370             map { "$infobase.$_" } (sort keys %clean_suffixes));
3371 }
3372
3373 # ($DIRSTAMP, @CLEAN_FILES)
3374 # output_texinfo_build_rules ($SOURCE, $DEST, @DEPENDENCIES)
3375 # ----------------------------------------------------------
3376 # SOURCE - the source Texinfo file
3377 # DEST - the destination Info file
3378 # DEPENDENCIES - known dependencies
3379 sub output_texinfo_build_rules ($$@)
3380 {
3381   my ($source, $dest, @deps) = @_;
3382
3383   # Split `a.texi' into `a' and `.texi'.
3384   my ($spfx, $ssfx) = ($source =~ /^(.*?)(\.[^.]*)?$/);
3385   my ($dpfx, $dsfx) = ($dest =~ /^(.*?)(\.[^.]*)?$/);
3386
3387   $ssfx ||= "";
3388   $dsfx ||= "";
3389
3390   # We can output two kinds of rules: the "generic" rules
3391   # use Make suffix rules and are appropritate when
3392   # $source and $dest lie in the current directory; the "specifix"
3393   # rules is needed in the other case.
3394   #
3395   # The former are output only once (this is not really apparent
3396   # here, but just remember that some logic deeper in Automake will
3397   # not output the same rule twice); while the later need to be output
3398   # for each Texinfo source.
3399   my $generic;
3400   my $makeinfoflags;
3401   my $sdir = dirname $source;
3402   if ($sdir eq '.' && dirname ($dest) eq '.')
3403     {
3404       $generic = 1;
3405       $makeinfoflags = '-I $(srcdir)';
3406     }
3407   else
3408     {
3409       $generic = 0;
3410       $makeinfoflags = "-I $sdir -I \$(srcdir)/$sdir";
3411     }
3412
3413   # We cannot use a suffix rule to build info files with
3414   # an empty extension.  Otherwise we would output a single suffix
3415   # inference rule, with separate dependencies, as in
3416   #    .texi:
3417   #            $(MAKEINFO) ...
3418   #    foo.info: foo.texi
3419   # which confuse Solaris make.  (See the Autoconf manual for details.)
3420   # Therefore we use a specific rule in this case.  This applies
3421   # to info files only (dvi and pdf files always have an extension).
3422   my $generic_info = ($generic && $dsfx) ? 1 : 0;
3423
3424   # If the resulting file lie into a subdirectory,
3425   # make sure this directory will exist.
3426   my $dirstamp = require_build_directory_maybe ($dest);
3427
3428   $output_rules .= &file_contents ('texibuild',
3429                                    new Automake::Location,
3430                                    GENERIC       => $generic,
3431                                    GENERIC_INFO  => $generic_info,
3432                                    SOURCE_SUFFIX => $ssfx,
3433                                    SOURCE => ($generic ? '$<' : $source),
3434                                    SOURCE_INFO   => ($generic_info ?
3435                                                      '$<' : $source),
3436                                    SOURCE_REAL   => $source,
3437                                    DEST_PREFIX   => $dpfx,
3438                                    DEST_SUFFIX   => $dsfx,
3439                                    MAKEINFOFLAGS => $makeinfoflags,
3440                                    DEPS          => "@deps",
3441                                    DIRSTAMP      => $dirstamp);
3442   return ($dirstamp, "$dpfx.dvi", "$dpfx.pdf", "$dpfx.ps", "$dpfx.html");
3443 }
3444
3445
3446 # ($DO-SOMETHING, $TEXICLEANS)
3447 # handle_texinfo_helper ()
3448 # ------------------------
3449 # Handle all Texinfo source; helper for handle_texinfo
3450 sub handle_texinfo_helper
3451 {
3452     reject_var 'TEXINFOS', "`TEXINFOS' is an anachronism; use `info_TEXINFOS'";
3453     reject_var 'html_TEXINFOS', "HTML generation not yet supported";
3454
3455     return (0, '') if ! variable_defined ('info_TEXINFOS');
3456
3457     my @texis = &variable_value_as_list_recursive ('info_TEXINFOS', 'all');
3458
3459     my (@info_deps_list, @texi_deps);
3460     my (@dvis_list, @pdfs_list, @pss_list, @htmls_list);
3461     my %versions;
3462     my $done = 0;
3463     my @texi_cleans;
3464     my $canonical;
3465
3466     foreach my $info_cursor (@texis)
3467     {
3468         my $infobase = $info_cursor;
3469         $infobase =~ s/\.(txi|texinfo|texi)$//;
3470
3471         if ($infobase eq $info_cursor)
3472           {
3473             # FIXME: report line number.
3474             err_am "texinfo file `$info_cursor' has unrecognized extension";
3475             next;
3476           }
3477
3478         # If 'version.texi' is referenced by input file, then include
3479         # automatic versioning capability.
3480         my ($out_file, $vtexi, @clean_files) =
3481           &scan_texinfo_file ("$relative_dir/$info_cursor")
3482             or next;
3483         push (@texi_cleans, @clean_files);
3484
3485         # If the Texinfo source is in a subdirectory, create the
3486         # resulting info in this subdirectory.  If it is in the
3487         # current directory, try hard to not prefix "./" because
3488         # it breaks the generic rules.
3489         my $outdir = dirname ($info_cursor) . '/';
3490         $outdir = "" if $outdir eq './';
3491         $out_file =  $outdir . $out_file;
3492
3493         # If user specified file_TEXINFOS, then use that as explicit
3494         # dependency list.
3495         @texi_deps = ();
3496         push (@texi_deps, "$outdir$vtexi") if $vtexi;
3497
3498         my $canonical = &canonicalize ($infobase);
3499         if (variable_defined ($canonical . "_TEXINFOS"))
3500         {
3501             push (@texi_deps, '$(' . $canonical . '_TEXINFOS)');
3502             &push_dist_common ('$(' . $canonical . '_TEXINFOS)');
3503         }
3504
3505         my ($dirstamp, @cfiles) =
3506           output_texinfo_build_rules ($info_cursor, $out_file, @texi_deps);
3507         push (@texi_cleans, @cfiles);
3508
3509         push (@info_deps_list, $out_file);
3510         push (@dvis_list, $infobase . '.dvi');
3511         push (@pdfs_list, $infobase . '.pdf');
3512         push (@pss_list, $infobase . '.ps');
3513         push (@htmls_list, $infobase . '.html');
3514
3515         # If a vers*.texi file is needed, emit the rule.
3516         if ($vtexi)
3517         {
3518             err_am ("`$vtexi', included in `$info_cursor', "
3519                     . "also included in `$versions{$vtexi}'")
3520               if defined $versions{$vtexi};
3521             $versions{$vtexi} = $info_cursor;
3522
3523             # We number the stamp-vti files.  This is doable since the
3524             # actual names don't matter much.  We only number starting
3525             # with the second one, so that the common case looks nice.
3526             my $vti = ($done ? $done : 'vti');
3527             ++$done;
3528
3529             # This is ugly, but it is our historical practice.
3530             if ($config_aux_dir_set_in_configure_in)
3531             {
3532                 require_conf_file_with_macro (TRUE, 'info_TEXINFOS', FOREIGN,
3533                                               'mdate-sh');
3534             }
3535             else
3536             {
3537                 require_file_with_macro (TRUE, 'info_TEXINFOS',
3538                                          FOREIGN, 'mdate-sh');
3539             }
3540
3541             my $conf_dir;
3542             if ($config_aux_dir_set_in_configure_in)
3543             {
3544                 $conf_dir = $config_aux_dir;
3545                 $conf_dir .= '/' unless $conf_dir =~ /\/$/;
3546             }
3547             else
3548             {
3549                 $conf_dir = '$(srcdir)/';
3550             }
3551             $output_rules .= &file_contents ('texi-vers',
3552                                              new Automake::Location,
3553                                              TEXI     => $info_cursor,
3554                                              VTI      => $vti,
3555                                              STAMPVTI => "${outdir}stamp-$vti",
3556                                              VTEXI    => "$outdir$vtexi",
3557                                              MDDIR    => $conf_dir,
3558                                              DIRSTAMP => $dirstamp);
3559         }
3560     }
3561
3562     # Handle location of texinfo.tex.
3563     my $need_texi_file = 0;
3564     my $texinfodir;
3565     if ($cygnus_mode)
3566     {
3567         $texinfodir = '$(top_srcdir)/../texinfo';
3568         &define_variable ('TEXINFO_TEX', "$texinfodir/texinfo.tex", INTERNAL);
3569     }
3570     elsif ($config_aux_dir_set_in_configure_in)
3571     {
3572         $texinfodir = $config_aux_dir;
3573         &define_variable ('TEXINFO_TEX', "$texinfodir/texinfo.tex", INTERNAL);
3574         $need_texi_file = 2; # so that we require_conf_file later
3575     }
3576     elsif (variable_defined ('TEXINFO_TEX'))
3577     {
3578         # The user defined TEXINFO_TEX so assume he knows what he is
3579         # doing.
3580         $texinfodir = ('$(srcdir)/'
3581                        . dirname (&variable_value ('TEXINFO_TEX')));
3582     }
3583     else
3584     {
3585         $texinfodir = '$(srcdir)';
3586         $need_texi_file = 1;
3587     }
3588     &define_variable ('am__TEXINFO_TEX_DIR', $texinfodir, INTERNAL);
3589
3590     # The return value.
3591     my $texiclean = makefile_wrap ("", "\t  ", @texi_cleans);
3592
3593     push (@dist_targets, 'dist-info');
3594
3595     if (! defined $options{'no-installinfo'})
3596     {
3597         # Make sure documentation is made and installed first.  Use
3598         # $(INFO_DEPS), not 'info', because otherwise recursive makes
3599         # get run twice during "make all".
3600         unshift (@all, '$(INFO_DEPS)');
3601     }
3602
3603     &define_variable ("INFO_DEPS", "@info_deps_list", INTERNAL);
3604     &define_variable ("DVIS", "@dvis_list", INTERNAL);
3605     &define_variable ("PDFS", "@pdfs_list", INTERNAL);
3606     &define_variable ("PSS", "@pss_list", INTERNAL);
3607     &define_variable ("HTMLS", "@htmls_list", INTERNAL);
3608     # This next isn't strictly needed now -- the places that look here
3609     # could easily be changed to look in info_TEXINFOS.  But this is
3610     # probably better, in case noinst_TEXINFOS is ever supported.
3611     &define_variable ("TEXINFOS", &variable_value ('info_TEXINFOS'), INTERNAL);
3612
3613     # Do some error checking.  Note that this file is not required
3614     # when in Cygnus mode; instead we defined TEXINFO_TEX explicitly
3615     # up above.
3616     if ($need_texi_file && ! defined $options{'no-texinfo.tex'})
3617     {
3618         if ($need_texi_file > 1)
3619         {
3620             require_conf_file_with_macro (TRUE, 'info_TEXINFOS', FOREIGN,
3621                                           'texinfo.tex');
3622         }
3623         else
3624         {
3625             require_file_with_macro (TRUE, 'info_TEXINFOS', FOREIGN,
3626                                      'texinfo.tex');
3627         }
3628     }
3629
3630     return (1, $texiclean);
3631 }
3632
3633 # handle_texinfo ()
3634 # -----------------
3635 # Handle all Texinfo source.
3636 sub handle_texinfo
3637 {
3638     my ($do_something, $texiclean) = handle_texinfo_helper ();
3639     $output_rules .=  &file_contents ('texinfos',
3640                                       new Automake::Location,
3641                                       TEXICLEAN => $texiclean,
3642                                       'LOCAL-TEXIS' => $do_something);
3643 }
3644
3645 # Handle any man pages.
3646 sub handle_man_pages
3647 {
3648     reject_var 'MANS', "`MANS' is an anachronism; use `man_MANS'";
3649
3650     # Find all the sections in use.  We do this by first looking for
3651     # "standard" sections, and then looking for any additional
3652     # sections used in man_MANS.
3653     my (%sections, %vlist);
3654     # We handle nodist_ for uniformity.  man pages aren't distributed
3655     # by default so it isn't actually very important.
3656     foreach my $pfx ('', 'dist_', 'nodist_')
3657     {
3658         # Add more sections as needed.
3659         foreach my $section ('0'..'9', 'n', 'l')
3660         {
3661             if (variable_defined ($pfx . 'man' . $section . '_MANS'))
3662             {
3663                 $sections{$section} = 1;
3664                 $vlist{'$(' . $pfx . 'man' . $section . '_MANS)'} = 1;
3665
3666                 &push_dist_common ('$(' . $pfx . 'man' . $section . '_MANS)')
3667                     if $pfx eq 'dist_';
3668             }
3669         }
3670
3671         if (variable_defined ($pfx . 'man_MANS'))
3672         {
3673             $vlist{'$(' . $pfx . 'man_MANS)'} = 1;
3674             foreach (&variable_value_as_list_recursive ($pfx . 'man_MANS', 'all'))
3675             {
3676                 # A page like `foo.1c' goes into man1dir.
3677                 if (/\.([0-9a-z])([a-z]*)$/)
3678                 {
3679                     $sections{$1} = 1;
3680                 }
3681             }
3682
3683             &push_dist_common ('$(' . $pfx . 'man_MANS)')
3684                 if $pfx eq 'dist_';
3685         }
3686     }
3687
3688     return unless %sections;
3689
3690     # Now for each section, generate an install and unintall rule.
3691     # Sort sections so output is deterministic.
3692     foreach my $section (sort keys %sections)
3693     {
3694         $output_rules .= &file_contents ('mans',
3695                                          new Automake::Location,
3696                                          SECTION => $section);
3697     }
3698
3699     my @mans = sort keys %vlist;
3700     $output_vars .= file_contents ('mans-vars',
3701                                    new Automake::Location,
3702                                    MANS => "@mans");
3703
3704     if (! defined $options{'no-installman'})
3705     {
3706         push (@all, '$(MANS)');
3707     }
3708 }
3709
3710 # Handle DATA variables.
3711 sub handle_data
3712 {
3713     &am_install_var ('-noextra', '-candist', 'data', 'DATA',
3714                      'data', 'sysconf', 'sharedstate', 'localstate',
3715                      'pkgdata', 'lisp', 'noinst', 'check');
3716 }
3717
3718 # Handle TAGS.
3719 sub handle_tags
3720 {
3721     my @tag_deps = ();
3722     my @ctag_deps = ();
3723     if (variable_defined ('SUBDIRS'))
3724     {
3725         $output_rules .= ("tags-recursive:\n"
3726                           . "\tlist=\'\$(SUBDIRS)\'; for subdir in \$\$list; do \\\n"
3727                           # Never fail here if a subdir fails; it
3728                           # isn't important.
3729                           . "\t  test \"\$\$subdir\" = . || (cd \$\$subdir"
3730                           . " && \$(MAKE) \$(AM_MAKEFLAGS) tags); \\\n"
3731                           . "\tdone\n");
3732         push (@tag_deps, 'tags-recursive');
3733         &depend ('.PHONY', 'tags-recursive');
3734
3735         $output_rules .= ("ctags-recursive:\n"
3736                           . "\tlist=\'\$(SUBDIRS)\'; for subdir in \$\$list; do \\\n"
3737                           # Never fail here if a subdir fails; it
3738                           # isn't important.
3739                           . "\t  test \"\$\$subdir\" = . || (cd \$\$subdir"
3740                           . " && \$(MAKE) \$(AM_MAKEFLAGS) ctags); \\\n"
3741                           . "\tdone\n");
3742         push (@ctag_deps, 'ctags-recursive');
3743         &depend ('.PHONY', 'ctags-recursive');
3744     }
3745
3746     if (&saw_sources_p (1)
3747         || variable_defined ('ETAGS_ARGS')
3748         || @tag_deps)
3749     {
3750         my @config;
3751         foreach my $spec (@config_headers)
3752         {
3753             my ($out, @ins) = split_config_file_spec ($spec);
3754             foreach my $in (@ins)
3755               {
3756                 # If the config header source is in this directory,
3757                 # require it.
3758                 push @config, basename ($in)
3759                   if $relative_dir eq dirname ($in);
3760               }
3761         }
3762         $output_rules .= &file_contents ('tags',
3763                                          new Automake::Location,
3764                                          CONFIG    => "@config",
3765                                          TAGSDIRS  => "@tag_deps",
3766                                          CTAGSDIRS => "@ctag_deps");
3767         &examine_variable ('TAGS_DEPENDENCIES');
3768     }
3769     elsif (reject_var ('TAGS_DEPENDENCIES',
3770                        "doesn't make sense to define `TAGS_DEPENDENCIES'"
3771                        . "without\nsources or `ETAGS_ARGS'"))
3772     {
3773     }
3774     else
3775     {
3776         # Every Makefile must define some sort of TAGS rule.
3777         # Otherwise, it would be possible for a top-level "make TAGS"
3778         # to fail because some subdirectory failed.
3779         $output_rules .= "tags: TAGS\nTAGS:\n\n";
3780         # Ditto ctags.
3781         $output_rules .= "ctags: CTAGS\nCTAGS:\n\n";
3782     }
3783 }
3784
3785 # Handle multilib support.
3786 sub handle_multilib
3787 {
3788     if ($seen_multilib && $relative_dir eq '.')
3789     {
3790         $output_rules .= &file_contents ('multilib', new Automake::Location);
3791     }
3792 }
3793
3794
3795 # $BOOLEAN
3796 # &for_dist_common ($A, $B)
3797 # -------------------------
3798 # Subroutine for &handle_dist: sort files to dist.
3799 #
3800 # We put README first because it then becomes easier to make a
3801 # Usenet-compliant shar file (in these, README must be first).
3802 #
3803 # FIXME: do more ordering of files here.
3804 sub for_dist_common
3805 {
3806     return 0
3807         if $a eq $b;
3808     return -1
3809         if $a eq 'README';
3810     return 1
3811         if $b eq 'README';
3812     return $a cmp $b;
3813 }
3814
3815
3816 # handle_dist ($MAKEFILE)
3817 # -----------------------
3818 # Handle 'dist' target.
3819 sub handle_dist
3820 {
3821     my ($makefile) = @_;
3822
3823     # `make dist' isn't used in a Cygnus-style tree.
3824     # Omit the rules so that people don't try to use them.
3825     return if $cygnus_mode;
3826
3827     # Look for common files that should be included in distribution.
3828     # If the aux dir is set, and it does not have a Makefile.am, then
3829     # we check for these files there as well.
3830     my $check_aux = 0;
3831     my $auxdir = '';
3832     if ($relative_dir eq '.'
3833         && $config_aux_dir_set_in_configure_in)
3834     {
3835         ($auxdir = $config_aux_dir) =~ s,^\$\(top_srcdir\)/,,;
3836         if (! &is_make_dir ($auxdir))
3837         {
3838             $check_aux = 1;
3839         }
3840     }
3841     foreach my $cfile (@common_files)
3842     {
3843         if (-f ($relative_dir . "/" . $cfile)
3844             # The file might be absent, but if it can be built it's ok.
3845             || exists $targets{$cfile})
3846         {
3847             &push_dist_common ($cfile);
3848         }
3849
3850         # Don't use `elsif' here because a file might meaningfully
3851         # appear in both directories.
3852         if ($check_aux && -f ($auxdir . '/' . $cfile))
3853         {
3854             &push_dist_common ($auxdir . '/' . $cfile);
3855         }
3856     }
3857
3858     # We might copy elements from $configure_dist_common to
3859     # %dist_common if we think we need to.  If the file appears in our
3860     # directory, we would have discovered it already, so we don't
3861     # check that.  But if the file is in a subdir without a Makefile,
3862     # we want to distribute it here if we are doing `.'.  Ugly!
3863     if ($relative_dir eq '.')
3864     {
3865        foreach my $file (split (' ' , $configure_dist_common))
3866        {
3867            push_dist_common ($file)
3868              unless is_make_dir (dirname ($file));
3869        }
3870     }
3871
3872     # Files to distributed.  Don't use &variable_value_as_list_recursive
3873     # as it recursively expands `$(dist_pkgdata_DATA)' etc.
3874     my @dist_common = split (' ', rvar ('DIST_COMMON')->variable_value);
3875     @dist_common = uniq (sort for_dist_common (@dist_common));
3876     define_pretty_variable ('DIST_COMMON', TRUE, INTERNAL, @dist_common);
3877
3878     # Now that we've processed DIST_COMMON, disallow further attempts
3879     # to set it.
3880     $handle_dist_run = 1;
3881
3882     # Scan EXTRA_DIST to see if we need to distribute anything from a
3883     # subdir.  If so, add it to the list.  I didn't want to do this
3884     # originally, but there were so many requests that I finally
3885     # relented.
3886     if (variable_defined ('EXTRA_DIST'))
3887     {
3888         # FIXME: This should be fixed to work with conditions.  That
3889         # will require only making the entries in %dist_dirs under the
3890         # appropriate condition.  This is meaningful if the nature of
3891         # the distribution should depend upon the configure options
3892         # used.
3893         foreach (&variable_value_as_list_recursive ('EXTRA_DIST', 'all'))
3894         {
3895             next if /^\@.*\@$/;
3896             next unless s,/+[^/]+$,,;
3897             $dist_dirs{$_} = 1
3898                 unless $_ eq '.';
3899         }
3900     }
3901
3902     # We have to check DIST_COMMON for extra directories in case the
3903     # user put a source used in AC_OUTPUT into a subdir.
3904     my $topsrcdir = backname ($relative_dir);
3905     foreach (&variable_value_as_list_recursive ('DIST_COMMON', 'all'))
3906     {
3907         next if /^\@.*\@$/;
3908         s/\$\(top_srcdir\)/$topsrcdir/;
3909         s/\$\(srcdir\)/./;
3910         # Strip any leading `./'.
3911         s,^(:?\./+)*,,;
3912         next unless s,/+[^/]+$,,;
3913         $dist_dirs{$_} = 1
3914             unless $_ eq '.';
3915     }
3916
3917     # Rule to check whether a distribution is viable.
3918     my %transform = ('DISTCHECK-HOOK' => &target_defined ('distcheck-hook'),
3919                      'GETTEXT' => $seen_gettext && !$seen_gettext_external);
3920
3921     # Prepend $(distdir) to each directory given.
3922     my %rewritten = map { '$(distdir)/' . "$_" => 1 } keys %dist_dirs;
3923     $transform{'DISTDIRS'} = join (' ', sort keys %rewritten);
3924
3925     # If we have SUBDIRS, create all dist subdirectories and do
3926     # recursive build.
3927     if (variable_defined ('SUBDIRS'))
3928     {
3929         # If SUBDIRS is conditionally defined, then set DIST_SUBDIRS
3930         # to all possible directories, and use it.  If DIST_SUBDIRS is
3931         # defined, just use it.
3932         my $dist_subdir_name;
3933         # Note that we check DIST_SUBDIRS first on purpose.  At least
3934         # one project uses so many conditional subdirectories that
3935         # calling variable_conditionally_defined on SUBDIRS will cause
3936         # automake to grow to 150Mb.  Sigh.
3937         if (variable_defined ('DIST_SUBDIRS')
3938             || variable_conditionally_defined ('SUBDIRS'))
3939         {
3940             $dist_subdir_name = 'DIST_SUBDIRS';
3941             if (! variable_defined ('DIST_SUBDIRS'))
3942             {
3943                 define_pretty_variable
3944                   ('DIST_SUBDIRS', TRUE, INTERNAL,
3945                    uniq (&variable_value_as_list_recursive ('SUBDIRS', 'all')));
3946             }
3947         }
3948         else
3949         {
3950             $dist_subdir_name = 'SUBDIRS';
3951             # We always define this because that is what `distclean'
3952             # wants.
3953             define_pretty_variable ('DIST_SUBDIRS', TRUE, INTERNAL,
3954                                     '$(SUBDIRS)');
3955         }
3956
3957         $transform{'DIST_SUBDIR_NAME'} = $dist_subdir_name;
3958     }
3959
3960     # If the target `dist-hook' exists, make sure it is run.  This
3961     # allows users to do random weird things to the distribution
3962     # before it is packaged up.
3963     push (@dist_targets, 'dist-hook')
3964       if &target_defined ('dist-hook');
3965     $transform{'DIST-TARGETS'} = join(' ', @dist_targets);
3966
3967     $output_rules .= &file_contents ('distdir',
3968                                      new Automake::Location,
3969                                      %transform);
3970 }
3971
3972
3973 # Handle subdirectories.
3974 sub handle_subdirs
3975 {
3976     return
3977       unless variable_defined ('SUBDIRS');
3978
3979     my @subdirs = &variable_value_as_list_recursive ('SUBDIRS', 'all');
3980     my @dsubdirs = ();
3981     @dsubdirs = &variable_value_as_list_recursive ('DIST_SUBDIRS', 'all')
3982       if variable_defined ('DIST_SUBDIRS');
3983
3984     # If an `obj/' directory exists, BSD make will enter it before
3985     # reading `Makefile'.  Hence the `Makefile' in the current directory
3986     # will not be read.
3987     #
3988     #  % cat Makefile
3989     #  all:
3990     #          echo Hello
3991     #  % cat obj/Makefile
3992     #  all:
3993     #          echo World
3994     #  % make      # GNU make
3995     #  echo Hello
3996     #  Hello
3997     #  % pmake     # BSD make
3998     #  echo World
3999     #  World
4000     msg_var ('portability', 'SUBDIRS',
4001              "naming a subdirectory `obj' causes troubles with BSD make")
4002       if grep ($_ eq 'obj', @subdirs);
4003     msg_var ('portability', 'DIST_SUBDIRS',
4004              "naming a subdirectory `obj' causes troubles with BSD make")
4005       if grep ($_ eq 'obj', @dsubdirs);
4006
4007     # Make sure each directory mentioned in SUBDIRS actually exists.
4008     foreach my $dir (@subdirs)
4009     {
4010         # Skip directories substituted by configure.
4011         next if $dir =~ /^\@.*\@$/;
4012
4013         if (! -d $am_relative_dir . '/' . $dir)
4014         {
4015             err_var ('SUBDIRS', "required directory $am_relative_dir/$dir "
4016                      . "does not exist");
4017             next;
4018         }
4019
4020         err_var 'SUBDIRS', "directory should not contain `/'"
4021           if $dir =~ /\//;
4022     }
4023
4024     $output_rules .= &file_contents ('subdirs', new Automake::Location);
4025     rvar ('RECURSIVE_TARGETS')->rdef (TRUE)->{'pretty'} = VAR_PRETTY; # Gross!
4026 }
4027
4028
4029 # ($REGEN, @DEPENDENCIES)
4030 # &scan_aclocal_m4
4031 # ----------------
4032 # If aclocal.m4 creation is automated, return the list of its dependencies.
4033 sub scan_aclocal_m4
4034 {
4035     my $regen_aclocal = 0;
4036
4037     &examine_variable ('CONFIG_STATUS_DEPENDENCIES');
4038     &examine_variable ('CONFIGURE_DEPENDENCIES');
4039
4040     if (-f 'aclocal.m4')
4041     {
4042         &push_dist_common ('aclocal.m4')
4043           if $relative_dir eq '.';
4044         &define_variable ("ACLOCAL_M4", '$(top_srcdir)/aclocal.m4', INTERNAL);
4045
4046         my $aclocal = new Automake::XFile "< aclocal.m4";
4047         my $line = $aclocal->getline;
4048         $regen_aclocal = $line =~ 'generated automatically by aclocal';
4049     }
4050
4051     my @ac_deps = ();
4052
4053     if (variable_defined ('ACLOCAL_M4_SOURCES'))
4054     {
4055         push (@ac_deps, '$(ACLOCAL_M4_SOURCES)');
4056         msg_var ('obsolete', 'ACLOCAL_M4_SOURCES',
4057                  "`ACLOCAL_M4_SOURCES' is obsolete.\n"
4058                  . "It should be safe to simply remove it.");
4059     }
4060
4061     # Note that it might be possible that aclocal.m4 doesn't exist but
4062     # should be auto-generated.  This case probably isn't very
4063     # important.
4064
4065     return ($regen_aclocal, @ac_deps);
4066 }
4067
4068
4069 # @DEPENDENCY
4070 # &rewrite_inputs_into_dependencies ($ADD_SRCDIR, @INPUTS)
4071 # --------------------------------------------------------
4072 # Rewrite a list of input files into a form suitable to put on a
4073 # dependency list.  The idea is that if an input file has a directory
4074 # part the same as the current directory, then the directory part is
4075 # simply removed.  But if the directory part is different, then
4076 # $(top_srcdir) is prepended.  Among other things, this is used to
4077 # generate the dependency list for the output files generated by
4078 # AC_OUTPUT.  Consider what the dependencies should look like in this
4079 # case:
4080 #   AC_OUTPUT(src/out:src/in1:lib/in2)
4081 # The first argument, ADD_SRCDIR, is 1 if $(top_srcdir) should be added.
4082 # If 0 then files that require this addition will simply be ignored.
4083 sub rewrite_inputs_into_dependencies ($@)
4084 {
4085     my ($add_srcdir, @inputs) = @_;
4086     my @newinputs;
4087
4088     foreach my $single (@inputs)
4089     {
4090         if (dirname ($single) eq $relative_dir)
4091         {
4092             push (@newinputs, basename ($single));
4093         }
4094         elsif ($add_srcdir)
4095         {
4096             push (@newinputs, '$(top_srcdir)/' . $single);
4097         }
4098     }
4099
4100     return @newinputs;
4101 }
4102
4103 # Handle remaking and configure stuff.
4104 # We need the name of the input file, to do proper remaking rules.
4105 sub handle_configure
4106 {
4107     my ($local, $input, @secondary_inputs) = @_;
4108
4109     my $input_base = basename ($input);
4110     my $local_base = basename ($local);
4111
4112     my $amfile = $input_base . '.am';
4113     # We know we can always add '.in' because it really should be an
4114     # error if the .in was missing originally.
4115     my $infile = '$(srcdir)/' . $input_base . '.in';
4116     my $colon_infile = '';
4117     if ($local ne $input || @secondary_inputs)
4118     {
4119         $colon_infile = ':' . $input . '.in';
4120     }
4121     $colon_infile .= ':' . join (':', @secondary_inputs)
4122         if @secondary_inputs;
4123
4124     my @rewritten = rewrite_inputs_into_dependencies (1, @secondary_inputs);
4125
4126     my ($regen_aclocal_m4, @aclocal_m4_deps) = scan_aclocal_m4 ();
4127
4128
4129     define_pretty_variable ('am__configure_deps', TRUE, INTERNAL,
4130                             @configure_deps);
4131
4132     $output_rules .=
4133       &file_contents ('configure',
4134                       new Automake::Location,
4135                       MAKEFILE              => $local_base,
4136                       'MAKEFILE-DEPS'       => "@rewritten",
4137                       'CONFIG-MAKEFILE'
4138                        => ($relative_dir eq '.') ? '$@' : '$(subdir)/$@',
4139                       'MAKEFILE-IN'         => $infile,
4140                       'MAKEFILE-IN-DEPS'    => "@include_stack",
4141                       'MAKEFILE-AM'         => $amfile,
4142                       STRICTNESS => $cygnus_mode ? 'cygnus' : $strictness_name,
4143                       'USE-DEPS'
4144                         => $cmdline_use_dependencies ? '' : ' --ignore-deps',
4145                       'MAKEFILE-AM-SOURCES' =>  "$input$colon_infile",
4146                       'REGEN-ACLOCAL-M4'    => $regen_aclocal_m4,
4147                       ACLOCAL_M4_DEPS       => "@aclocal_m4_deps");
4148
4149     if ($relative_dir eq '.')
4150     {
4151         &push_dist_common ('acconfig.h')
4152             if -f 'acconfig.h';
4153     }
4154
4155     # If we have a configure header, require it.
4156     my $hdr_index = 0;
4157     my @distclean_config;
4158     foreach my $spec (@config_headers)
4159       {
4160         $hdr_index += 1;
4161         # $CONFIG_H_PATH: config.h from top level.
4162         my ($config_h_path, @ins) = split_config_file_spec ($spec);
4163         my $config_h_dir = dirname ($config_h_path);
4164
4165         # If the header is in the current directory we want to build
4166         # the header here.  Otherwise, if we're at the topmost
4167         # directory and the header's directory doesn't have a
4168         # Makefile, then we also want to build the header.
4169         if ($relative_dir eq $config_h_dir
4170             || ($relative_dir eq '.' && ! &is_make_dir ($config_h_dir)))
4171         {
4172             my ($cn_sans_dir, $stamp_dir);
4173             if ($relative_dir eq $config_h_dir)
4174             {
4175                 $cn_sans_dir = basename ($config_h_path);
4176                 $stamp_dir = '';
4177             }
4178             else
4179             {
4180                 $cn_sans_dir = $config_h_path;
4181                 if ($config_h_dir eq '.')
4182                 {
4183                     $stamp_dir = '';
4184                 }
4185                 else
4186                 {
4187                     $stamp_dir = $config_h_dir . '/';
4188                 }
4189             }
4190
4191             # Compute relative path from directory holding output
4192             # header to directory holding input header.  FIXME:
4193             # doesn't handle case where we have multiple inputs.
4194             my $in0_sans_dir;
4195             if (dirname ($ins[0]) eq $relative_dir)
4196             {
4197                 $in0_sans_dir = basename ($ins[0]);
4198             }
4199             else
4200             {
4201                 $in0_sans_dir = backname ($relative_dir) . '/' . $ins[0];
4202             }
4203
4204             require_file ($config_header_location, FOREIGN, $in0_sans_dir);
4205
4206             # Header defined and in this directory.
4207             my @files;
4208             if (-f $config_h_path . '.top')
4209             {
4210                 push (@files, "$cn_sans_dir.top");
4211             }
4212             if (-f $config_h_path . '.bot')
4213             {
4214                 push (@files, "$cn_sans_dir.bot");
4215             }
4216
4217             push_dist_common (@files);
4218
4219             # For now, acconfig.h can only appear in the top srcdir.
4220             if (-f 'acconfig.h')
4221             {
4222                 push (@files, '$(top_srcdir)/acconfig.h');
4223             }
4224
4225             my $stamp = "${stamp_dir}stamp-h${hdr_index}";
4226             $output_rules .=
4227               file_contents ('remake-hdr',
4228                              new Automake::Location,
4229                              FILES         => "@files",
4230                              CONFIG_H      => $cn_sans_dir,
4231                              CONFIG_HIN    => $in0_sans_dir,
4232                              CONFIG_H_PATH => $config_h_path,
4233                              STAMP         => "$stamp");
4234
4235             push @distclean_config, $cn_sans_dir, $stamp;
4236         }
4237     }
4238
4239     $output_rules .= file_contents ('clean-hdr',
4240                                     new Automake::Location,
4241                                     FILES => "@distclean_config")
4242       if @distclean_config;
4243
4244     # Set location of mkinstalldirs.
4245     define_variable ('mkinstalldirs',
4246                      '$(SHELL) ' . $config_aux_dir . '/mkinstalldirs',
4247                      INTERNAL);
4248
4249     reject_var ('CONFIG_HEADER',
4250                 "`CONFIG_HEADER' is an anachronism; now determined "
4251                 . "automatically\nfrom `$configure_ac'");
4252
4253     my @config_h;
4254     foreach my $spec (@config_headers)
4255       {
4256         my ($out, @ins) = split_config_file_spec ($spec);
4257         # Generate CONFIG_HEADER define.
4258         if ($relative_dir eq dirname ($out))
4259         {
4260             push @config_h, basename ($out);
4261         }
4262         else
4263         {
4264             push @config_h, "\$(top_builddir)/$out";
4265         }
4266     }
4267     define_variable ("CONFIG_HEADER", "@config_h", INTERNAL)
4268       if @config_h;
4269
4270     # Now look for other files in this directory which must be remade
4271     # by config.status, and generate rules for them.
4272     my @actual_other_files = ();
4273     foreach my $lfile (@other_input_files)
4274     {
4275         my $file;
4276         my @inputs;
4277         if ($lfile =~ /^([^:]*):(.*)$/)
4278         {
4279             # This is the ":" syntax of AC_OUTPUT.
4280             $file = $1;
4281             @inputs = split (':', $2);
4282         }
4283         else
4284         {
4285             # Normal usage.
4286             $file = $lfile;
4287             @inputs = $file . '.in';
4288         }
4289
4290         # Automake files should not be stored in here, but in %MAKE_LIST.
4291         prog_error "$lfile in \@other_input_files"
4292           if -f $file . '.am';
4293
4294         my $local = basename ($file);
4295
4296         # Make sure the dist directory for each input file is created.
4297         # We only have to do this at the topmost level though.  This
4298         # is a bit ugly but it easier than spreading out the logic,
4299         # especially in cases like AC_OUTPUT(foo/out:bar/in), where
4300         # there is no Makefile in bar/.
4301         if ($relative_dir eq '.')
4302         {
4303             foreach (@inputs)
4304             {
4305                 $dist_dirs{dirname ($_)} = 1;
4306             }
4307         }
4308
4309         # We skip files that aren't in this directory.  However, if
4310         # the file's directory does not have a Makefile, and we are
4311         # currently doing `.', then we create a rule to rebuild the
4312         # file in the subdir.
4313         my $fd = dirname ($file);
4314         if ($fd ne $relative_dir)
4315         {
4316             if ($relative_dir eq '.' && ! &is_make_dir ($fd))
4317             {
4318                 $local = $file;
4319             }
4320             else
4321             {
4322                 next;
4323             }
4324         }
4325
4326         my @rewritten_inputs = rewrite_inputs_into_dependencies (1, @inputs);
4327         $output_rules .= ($local . ': '
4328                           . '$(top_builddir)/config.status '
4329                           . "@rewritten_inputs\n"
4330                           . "\t"
4331                           . 'cd $(top_builddir) && '
4332                           . '$(SHELL) ./config.status '
4333                           . ($relative_dir eq '.' ? '' : '$(subdir)/')
4334                           . '$@'
4335                           . "\n");
4336         push (@actual_other_files, $local);
4337
4338         # Require all input files.
4339         require_file ($ac_config_files_location, FOREIGN,
4340                       rewrite_inputs_into_dependencies (0, @inputs));
4341     }
4342
4343     # These files get removed by "make clean".
4344     define_pretty_variable ('CONFIG_CLEAN_FILES', TRUE, INTERNAL,
4345                             @actual_other_files);
4346 }
4347
4348 # Handle C headers.
4349 sub handle_headers
4350 {
4351     my @r = &am_install_var ('-defaultdist', 'header', 'HEADERS', 'include',
4352                              'oldinclude', 'pkginclude',
4353                              'noinst', 'check');
4354     foreach (@r)
4355     {
4356       next unless $_->[1] =~ /\..*$/;
4357       &saw_extension ($&);
4358     }
4359 }
4360
4361 sub handle_gettext
4362 {
4363   return if ! $seen_gettext || $relative_dir ne '.';
4364
4365   if (! variable_defined ('SUBDIRS'))
4366     {
4367       err_ac "AM_GNU_GETTEXT used but SUBDIRS not defined";
4368       return;
4369     }
4370
4371   # Perform some sanity checks to help users get the right setup.
4372   # We disable these tests when po/ doesn't exist in order not to disallow
4373   # unusual gettext setups.
4374   #
4375   # Bruno Haible:
4376   # | The idea is:
4377   # |
4378   # |  1) If a package doesn't have a directory po/ at top level, it
4379   # |     will likely have multiple po/ directories in subpackages.
4380   # |
4381   # |  2) It is useful to warn for the absence of intl/ if AM_GNU_GETTEXT
4382   # |     is used without 'external'. It is also useful to warn for the
4383   # |     presence of intl/ if AM_GNU_GETTEXT([external]) is used. Both
4384   # |     warnings apply only to the usual layout of packages, therefore
4385   # |     they should both be disabled if no po/ directory is found at
4386   # |     top level.
4387
4388   if (-d 'po')
4389     {
4390       my @subdirs = &variable_value_as_list_recursive ('SUBDIRS', 'all');
4391
4392       msg_var ('syntax', 'SUBDIRS',
4393                "AM_GNU_GETTEXT used but `po' not in SUBDIRS")
4394         if ! grep ($_ eq 'po', @subdirs);
4395
4396       # intl/ is not required when AM_GNU_GETTEXT is called with
4397       # the `external' option.
4398       msg_var ('syntax', 'SUBDIRS',
4399                "AM_GNU_GETTEXT used but `intl' not in SUBDIRS")
4400         if (! $seen_gettext_external
4401             && ! grep ($_ eq 'intl', @subdirs));
4402
4403       # intl/ should not be used with AM_GNU_GETTEXT([external])
4404       msg_var ('syntax', 'SUBDIRS',
4405                "`intl' should not be in SUBDIRS when "
4406                . "AM_GNU_GETTEXT([external]) is used")
4407         if ($seen_gettext_external && grep ($_ eq 'intl', @subdirs));
4408     }
4409
4410   require_file ($ac_gettext_location, GNU, 'ABOUT-NLS');
4411 }
4412
4413 # Handle footer elements.
4414 sub handle_footer
4415 {
4416     # NOTE don't use define_pretty_variable here, because
4417     # $contents{...} is already defined.
4418     $output_vars .= 'SOURCES = ' . variable_value ('SOURCES') . "\n\n"
4419       if variable_value ('SOURCES');
4420
4421     reject_target ('.SUFFIXES',
4422                    "use variable `SUFFIXES', not target `.SUFFIXES'");
4423
4424     # Note: AIX 4.1 /bin/make will fail if any suffix rule appears
4425     # before .SUFFIXES.  So we make sure that .SUFFIXES appears before
4426     # anything else, by sticking it right after the default: target.
4427     $output_header .= ".SUFFIXES:\n";
4428     if (@suffixes || variable_defined ('SUFFIXES'))
4429     {
4430         # Make sure suffixes has unique elements.  Sort them to ensure
4431         # the output remains consistent.  However, $(SUFFIXES) is
4432         # always at the start of the list, unsorted.  This is done
4433         # because make will choose rules depending on the ordering of
4434         # suffixes, and this lets the user have some control.  Push
4435         # actual suffixes, and not $(SUFFIXES).  Some versions of make
4436         # do not like variable substitutions on the .SUFFIXES line.
4437         my @user_suffixes = (variable_defined ('SUFFIXES')
4438                              ? &variable_value_as_list_recursive ('SUFFIXES',
4439                                                                   'all')
4440                              : ());
4441
4442         my %suffixes = map { $_ => 1 } @suffixes;
4443         delete @suffixes{@user_suffixes};
4444
4445         $output_header .= (".SUFFIXES: "
4446                            . join (' ', @user_suffixes, sort keys %suffixes)
4447                            . "\n");
4448     }
4449
4450     $output_trailer .= file_contents ('footer', new Automake::Location);
4451 }
4452
4453
4454 # Generate `make install' rules.
4455 sub handle_install ()
4456 {
4457   $output_rules .= &file_contents
4458     ('install',
4459      new Automake::Location,
4460      maybe_BUILT_SOURCES => (variable_defined ('BUILT_SOURCES')
4461                              ? (" \$(BUILT_SOURCES)\n"
4462                                 . "\t\$(MAKE) \$(AM_MAKEFLAGS)")
4463                              : ''),
4464      'installdirs-local' => (target_defined ('installdirs-local')
4465                              ? ' installdirs-local' : ''),
4466      am__installdirs => variable_value ('am__installdirs') || '');
4467 }
4468
4469
4470 # Deal with all and all-am.
4471 sub handle_all ($)
4472 {
4473     my ($makefile) = @_;
4474
4475     # Output `all-am'.
4476
4477     # Put this at the beginning for the sake of non-GNU makes.  This
4478     # is still wrong if these makes can run parallel jobs.  But it is
4479     # right enough.
4480     unshift (@all, basename ($makefile));
4481
4482     foreach my $spec (@config_headers)
4483       {
4484         my ($out, @ins) = split_config_file_spec ($spec);
4485         push (@all, basename ($out))
4486           if dirname ($out) eq $relative_dir;
4487       }
4488
4489     # Install `all' hooks.
4490     if (&target_defined ("all-local"))
4491     {
4492       push (@all, "all-local");
4493       &depend ('.PHONY', "all-local");
4494     }
4495
4496     &pretty_print_rule ("all-am:", "\t\t", @all);
4497     &depend ('.PHONY', 'all-am', 'all');
4498
4499
4500     # Output `all'.
4501
4502     my @local_headers = ();
4503     push @local_headers, '$(BUILT_SOURCES)'
4504       if variable_defined ('BUILT_SOURCES');
4505     foreach my $spec (@config_headers)
4506       {
4507         my ($out, @ins) = split_config_file_spec ($spec);
4508         push @local_headers, basename ($out)
4509           if dirname ($out) eq $relative_dir;
4510       }
4511
4512     if (@local_headers)
4513       {
4514         # We need to make sure config.h is built before we recurse.
4515         # We also want to make sure that built sources are built
4516         # before any ordinary `all' targets are run.  We can't do this
4517         # by changing the order of dependencies to the "all" because
4518         # that breaks when using parallel makes.  Instead we handle
4519         # things explicitly.
4520         $output_all .= ("all: @local_headers"
4521                         . "\n\t"
4522                         . '$(MAKE) $(AM_MAKEFLAGS) '
4523                         . (variable_defined ('SUBDIRS')
4524                            ? 'all-recursive' : 'all-am')
4525                         . "\n\n");
4526       }
4527     else
4528       {
4529         $output_all .= "all: " . (variable_defined ('SUBDIRS')
4530                                   ? 'all-recursive' : 'all-am') . "\n\n";
4531       }
4532 }
4533
4534
4535 # Handle check merge target specially.
4536 sub do_check_merge_target
4537 {
4538     if (&target_defined ('check-local'))
4539     {
4540         # User defined local form of target.  So include it.
4541         push (@check_tests, 'check-local');
4542         &depend ('.PHONY', 'check-local');
4543     }
4544
4545     # In --cygnus mode, check doesn't depend on all.
4546     if ($cygnus_mode)
4547     {
4548         # Just run the local check rules.
4549         &pretty_print_rule ('check-am:', "\t\t", @check);
4550     }
4551     else
4552     {
4553         # The check target must depend on the local equivalent of
4554         # `all', to ensure all the primary targets are built.  Then it
4555         # must build the local check rules.
4556         $output_rules .= "check-am: all-am\n";
4557         &pretty_print_rule ("\t\$(MAKE) \$(AM_MAKEFLAGS)", "\t  ",
4558                             @check)
4559             if @check;
4560     }
4561     &pretty_print_rule ("\t\$(MAKE) \$(AM_MAKEFLAGS)", "\t  ",
4562                         @check_tests)
4563         if @check_tests;
4564
4565     &depend ('.PHONY', 'check', 'check-am');
4566     # Handle recursion.  We have to honor BUILT_SOURCES like for `all:'.
4567     $output_rules .= ("check: "
4568                       . (variable_defined ('BUILT_SOURCES')
4569                          ? "\$(BUILT_SOURCES)\n\t\$(MAKE) \$(AM_MAKEFLAGS) "
4570                          : '')
4571                       . (variable_defined ('SUBDIRS')
4572                          ? 'check-recursive' : 'check-am')
4573                       . "\n");
4574 }
4575
4576 # Handle all 'clean' targets.
4577 sub handle_clean
4578 {
4579   # Clean the files listed in user variables if they exist.
4580   $clean_files{'$(MOSTLYCLEANFILES)'} = MOSTLY_CLEAN
4581     if variable_defined ('MOSTLYCLEANFILES');
4582   $clean_files{'$(CLEANFILES)'} = CLEAN
4583     if variable_defined ('CLEANFILES');
4584   $clean_files{'$(DISTCLEANFILES)'} = DIST_CLEAN
4585     if variable_defined ('DISTCLEANFILES');
4586   $clean_files{'$(MAINTAINERCLEANFILES)'} = MAINTAINER_CLEAN
4587     if variable_defined ('MAINTAINERCLEANFILES');
4588
4589   # Built sources are automatically removed by maintainer-clean.
4590   $clean_files{'$(BUILT_SOURCES)'} = MAINTAINER_CLEAN
4591     if variable_defined ('BUILT_SOURCES');
4592
4593   # Compute a list of "rm"s to run for each target.
4594   my %rms = (MOSTLY_CLEAN, [],
4595              CLEAN, [],
4596              DIST_CLEAN, [],
4597              MAINTAINER_CLEAN, []);
4598
4599   foreach my $file (keys %clean_files)
4600     {
4601       my $when = $clean_files{$file};
4602       prog_error 'invalid entry in %clean_files'
4603         unless exists $rms{$when};
4604
4605       my $rm = "rm -f $file";
4606       # If file is a variable, make sure when don't call `rm -f' without args.
4607       $rm ="test -z \"$file\" || $rm"
4608         if ($file =~ /^\s*\$(\(.*\)|\{.*\})\s*$/);
4609
4610       push @{$rms{$when}}, "\t-$rm\n";
4611     }
4612
4613   $output_rules .= &file_contents
4614     ('clean',
4615      new Automake::Location,
4616      MOSTLYCLEAN_RMS      => join ('', @{$rms{&MOSTLY_CLEAN}}),
4617      CLEAN_RMS            => join ('', @{$rms{&CLEAN}}),
4618      DISTCLEAN_RMS        => join ('', @{$rms{&DIST_CLEAN}}),
4619      MAINTAINER_CLEAN_RMS => join ('', @{$rms{&MAINTAINER_CLEAN}}));
4620 }
4621
4622
4623 # &depend ($CATEGORY, @DEPENDENDEES)
4624 # ----------------------------------
4625 # The target $CATEGORY depends on @DEPENDENDEES.
4626 sub depend
4627 {
4628     my ($category, @dependendees) = @_;
4629     {
4630       push (@{$dependencies{$category}}, @dependendees);
4631     }
4632 }
4633
4634
4635 # &target_cmp ($A, $B)
4636 # --------------------
4637 # Subroutine for &handle_factored_dependencies to let `.PHONY' be last.
4638 sub target_cmp
4639 {
4640     return 0
4641         if $a eq $b;
4642     return -1
4643         if $b eq '.PHONY';
4644     return 1
4645         if $a eq '.PHONY';
4646     return $a cmp $b;
4647 }
4648
4649
4650 # &handle_factored_dependencies ()
4651 # --------------------------------
4652 # Handle everything related to gathered targets.
4653 sub handle_factored_dependencies
4654 {
4655   # Reject bad hooks.
4656   foreach my $utarg ('uninstall-data-local', 'uninstall-data-hook',
4657                      'uninstall-exec-local', 'uninstall-exec-hook')
4658     {
4659       my $x = $utarg;
4660       $x =~ s/(data|exec)-//;
4661       reject_target ($utarg, "use `$x', not `$utarg'");
4662     }
4663
4664   reject_target ('install-local',
4665                  "use `install-data-local' or `install-exec-local', "
4666                  . "not `install-local'");
4667
4668   reject_target ('install-info-local',
4669                  "`install-info-local' target defined but "
4670                  . "`no-installinfo' option not in use")
4671     unless defined $options{'no-installinfo'};
4672
4673   # Install the -local hooks.
4674   foreach (keys %dependencies)
4675     {
4676       # Hooks are installed on the -am targets.
4677       s/-am$// or next;
4678       if (&target_defined ("$_-local"))
4679         {
4680           depend ("$_-am", "$_-local");
4681           &depend ('.PHONY', "$_-local");
4682         }
4683     }
4684
4685   # Install the -hook hooks.
4686   # FIXME: Why not be as liberal as we are with -local hooks?
4687   foreach ('install-exec', 'install-data', 'uninstall')
4688     {
4689       if (&target_defined ("$_-hook"))
4690         {
4691           $actions{"$_-am"} .=
4692             ("\t\@\$(NORMAL_INSTALL)\n"
4693              . "\t" . '$(MAKE) $(AM_MAKEFLAGS) ' . "$_-hook\n");
4694         }
4695     }
4696
4697   # All the required targets are phony.
4698   depend ('.PHONY', keys %required_targets);
4699
4700   # Actually output gathered targets.
4701   foreach (sort target_cmp keys %dependencies)
4702     {
4703       # If there is nothing about this guy, skip it.
4704       next
4705         unless (@{$dependencies{$_}}
4706                 || $actions{$_}
4707                 || $required_targets{$_});
4708
4709       # Define gathered targets in undefined conditions.
4710       # FIXME: Right now we must handle .PHONY as an exception,
4711       # because people write things like
4712       #    .PHONY: myphonytarget
4713       # to append dependencies.  This would not work if Automake
4714       # refrained from defining its own .PHONY target as it does
4715       # with other overridden targets.
4716       my @undefined_conds = (TRUE,);
4717       if ($_ ne '.PHONY')
4718         {
4719           @undefined_conds =
4720             rule_define ($_, 'internal', TARGET_AUTOMAKE, TRUE, INTERNAL);
4721         }
4722       my @uniq_deps = uniq (sort @{$dependencies{$_}});
4723       foreach my $cond (@undefined_conds)
4724         {
4725           my $condstr = $cond->subst_string;
4726           &pretty_print_rule ("$condstr$_:", "$condstr\t", @uniq_deps);
4727           $output_rules .= $actions{$_} if defined $actions{$_};
4728           $output_rules .= "\n";
4729         }
4730     }
4731 }
4732
4733
4734 # &handle_tests_dejagnu ()
4735 # ------------------------
4736 sub handle_tests_dejagnu
4737 {
4738     push (@check_tests, 'check-DEJAGNU');
4739     $output_rules .= file_contents ('dejagnu', new Automake::Location);
4740 }
4741
4742
4743 # Handle TESTS variable and other checks.
4744 sub handle_tests
4745 {
4746   if (defined $options{'dejagnu'})
4747     {
4748       &handle_tests_dejagnu;
4749     }
4750   else
4751     {
4752       foreach my $c ('DEJATOOL', 'RUNTEST', 'RUNTESTFLAGS')
4753         {
4754           reject_var ($c, "`$c' defined but `dejagnu' not in "
4755                       . "`AUTOMAKE_OPTIONS'");
4756         }
4757     }
4758
4759   if (variable_defined ('TESTS'))
4760     {
4761       push (@check_tests, 'check-TESTS');
4762       $output_rules .= &file_contents ('check', new Automake::Location);
4763     }
4764 }
4765
4766 # Handle Emacs Lisp.
4767 sub handle_emacs_lisp
4768 {
4769   my @elfiles = &am_install_var ('-candist', 'lisp', 'LISP',
4770                                  'lisp', 'noinst');
4771
4772   return if ! @elfiles;
4773
4774   # Generate .elc files.
4775   my @elcfiles = map { $_->[1] . 'c' } @elfiles;
4776
4777   define_pretty_variable ('ELCFILES', TRUE, INTERNAL, @elcfiles);
4778   define_pretty_variable ('am__ELFILES', TRUE, INTERNAL,
4779                           map { $_->[1] } @elfiles);
4780
4781   # Do not depend on the build rules if ELCFILES is empty.
4782   # This is necessary because overriding ELCFILES= is a documented
4783   # idiom to disable byte-compilation.
4784   if (variable_value ('ELCFILES'))
4785     {
4786       # It's important that all depends on elc-stamp so that
4787       # all .elc files get recompiled whenever a .el changes.
4788       # It's important that all depends on $(ELCFILES) so that
4789       # we can recover if any of them is deleted.
4790       push (@all, 'elc-stamp', '$(ELCFILES)');
4791     }
4792
4793   require_variables ($elfiles[0][0], "Emacs Lisp sources seen", TRUE,
4794                      'EMACS', 'lispdir');
4795   require_conf_file ($elfiles[0][0], FOREIGN, 'elisp-comp');
4796   &define_variable ('elisp_comp', $config_aux_dir . '/elisp-comp', INTERNAL);
4797 }
4798
4799 # Handle Python
4800 sub handle_python
4801 {
4802   my @pyfiles = &am_install_var ('-defaultdist', 'python', 'PYTHON',
4803                                  'noinst');
4804   return if ! @pyfiles;
4805
4806   require_variables ($pyfiles[0][0], "Python sources seen", TRUE, 'PYTHON');
4807   require_conf_file ($pyfiles[0][0], FOREIGN, 'py-compile');
4808   &define_variable ('py_compile', $config_aux_dir . '/py-compile', INTERNAL);
4809 }
4810
4811 # Handle Java.
4812 sub handle_java
4813 {
4814     my @sourcelist = &am_install_var ('-candist',
4815                                       'java', 'JAVA',
4816                                       'java', 'noinst', 'check');
4817     return if ! @sourcelist;
4818
4819     my @prefix = am_primary_prefixes ('JAVA', 1,
4820                                       'java', 'noinst', 'check');
4821
4822     my $dir;
4823     foreach my $curs (@prefix)
4824       {
4825         next
4826           if $curs eq 'EXTRA';
4827
4828         err_var "${curs}_JAVA", "multiple _JAVA primaries in use"
4829           if defined $dir;
4830         $dir = $curs;
4831       }
4832
4833
4834     push (@all, 'class' . $dir . '.stamp');
4835 }
4836
4837
4838 # Handle some of the minor options.
4839 sub handle_minor_options
4840 {
4841   if (defined $options{'readme-alpha'})
4842     {
4843       if ($relative_dir eq '.')
4844         {
4845           if ($package_version !~ /^$GNITS_VERSION_PATTERN$/)
4846             {
4847               msg ('error-gnits', $package_version_location,
4848                    "version `$package_version' doesn't follow " .
4849                    "Gnits standards");
4850             }
4851           if (defined $1 && -f 'README-alpha')
4852             {
4853               # This means we have an alpha release.  See
4854               # GNITS_VERSION_PATTERN for details.
4855               require_file_with_macro (TRUE, 'AUTOMAKE_OPTIONS',
4856                                        FOREIGN, 'README-alpha');
4857             }
4858         }
4859     }
4860 }
4861
4862 ################################################################
4863
4864 # ($OUTPUT, @INPUTS)
4865 # &split_config_file_spec ($SPEC)
4866 # -------------------------------
4867 # Decode the Autoconf syntax for config files (files, headers, links
4868 # etc.).
4869 sub split_config_file_spec ($)
4870 {
4871   my ($spec) = @_;
4872   my ($output, @inputs) = split (/:/, $spec);
4873
4874   push @inputs, "$output.in"
4875     unless @inputs;
4876
4877   return ($output, @inputs);
4878 }
4879
4880
4881 my %make_list;
4882
4883 # &scan_autoconf_config_files ($CONFIG-FILES)
4884 # -------------------------------------------
4885 # Study $CONFIG-FILES which is the first argument to AC_CONFIG_FILES
4886 # (or AC_OUTPUT).
4887 sub scan_autoconf_config_files
4888 {
4889     my ($config_files) = @_;
4890     # Look at potential Makefile.am's.
4891     foreach (split ' ', $config_files)
4892     {
4893         # Must skip empty string for Perl 4.
4894         next if $_ eq "\\" || $_ eq '';
4895
4896         # Handle $local:$input syntax.  Note that we ignore
4897         # every input file past the first, though we keep
4898         # those around for later.
4899         my ($local, $input, @rest) = split (/:/);
4900         if (! $input)
4901         {
4902             $input = $local;
4903         }
4904         else
4905         {
4906             # FIXME: should be error if .in is missing.
4907             $input =~ s/\.in$//;
4908         }
4909
4910         if (-f $input . '.am')
4911         {
4912             # We have a file that automake should generate.
4913             $make_list{$input} = join (':', ($local, @rest));
4914         }
4915         else
4916         {
4917             # We have a file that automake should cause to be
4918             # rebuilt, but shouldn't generate itself.
4919             push (@other_input_files, $_);
4920         }
4921     }
4922 }
4923
4924
4925 # &scan_autoconf_traces ($FILENAME)
4926 # ---------------------------------
4927 sub scan_autoconf_traces ($)
4928 {
4929   my ($filename) = @_;
4930
4931   my @traced = qw(AC_CANONICAL_HOST
4932                   AC_CANONICAL_SYSTEM
4933                   AC_CONFIG_AUX_DIR
4934                   AC_CONFIG_FILES
4935                   AC_CONFIG_HEADERS
4936                   AC_INIT
4937                   AC_LIBSOURCE
4938                   AC_SUBST
4939                   AM_AUTOMAKE_VERSION
4940                   AM_CONDITIONAL
4941                   AM_GNU_GETTEXT
4942                   AM_INIT_AUTOMAKE
4943                   AM_MAINTAINER_MODE
4944                   AM_PROG_CC_C_O
4945                   m4_include
4946                   m4_sinclude);
4947
4948   my $traces = ($ENV{AUTOCONF} || 'autoconf') . " ";
4949
4950   # Use a separator unlikely to be used, not `:', the default, which
4951   # has a precise meaning for AC_CONFIG_FILES and so on.
4952   $traces .= join (' ',
4953                    map { "--trace=$_" . ':\$f:\$l::\$n::\${::}%' } @traced);
4954
4955   my $tracefh = new Automake::XFile ("$traces $filename |");
4956   verb "reading $traces";
4957
4958   while ($_ = $tracefh->getline)
4959     {
4960       chomp;
4961       my ($here, @args) = split /::/;
4962       my $where = new Automake::Location $here;
4963       my $macro = $args[0];
4964
4965       # Alphabetical ordering please.
4966       if ($macro eq 'AC_CANONICAL_HOST')
4967         {
4968           if (! $seen_canonical)
4969             {
4970               $seen_canonical = AC_CANONICAL_HOST;
4971               $canonical_location = $where;
4972             }
4973         }
4974       elsif ($macro eq 'AC_CANONICAL_SYSTEM')
4975         {
4976           $seen_canonical = AC_CANONICAL_SYSTEM;
4977           $canonical_location = $where;
4978         }
4979       elsif ($macro eq 'AC_CONFIG_AUX_DIR')
4980         {
4981           @config_aux_path = $args[1];
4982           $config_aux_dir_set_in_configure_in = 1;
4983         }
4984       elsif ($macro eq 'AC_CONFIG_FILES')
4985         {
4986           # Look at potential Makefile.am's.
4987           $ac_config_files_location = $where;
4988           &scan_autoconf_config_files ($args[1]);
4989         }
4990       elsif ($macro eq 'AC_CONFIG_HEADERS')
4991         {
4992           $config_header_location = $where;
4993           push @config_headers, split (' ', $args[1]);
4994         }
4995       elsif ($macro eq 'AC_INIT')
4996         {
4997           if (defined $args[2])
4998             {
4999               $package_version = $args[2];
5000               $package_version_location = $where;
5001             }
5002         }
5003       elsif ($macro eq 'AC_LIBSOURCE')
5004         {
5005           $libsources{$args[1]} = $here;
5006         }
5007       elsif ($macro eq 'AC_SUBST')
5008         {
5009           # Just check for alphanumeric in AC_SUBST.  If you do
5010           # AC_SUBST(5), then too bad.
5011           $configure_vars{$args[1]} = $where
5012             if $args[1] =~ /^\w+$/;
5013         }
5014       elsif ($macro eq 'AM_AUTOMAKE_VERSION')
5015         {
5016           error ($where,
5017                  "version mismatch.  This is Automake $VERSION,\n" .
5018                  "but the definition used by this AM_INIT_AUTOMAKE\n" .
5019                  "comes from Automake $args[1].  You should recreate\n" .
5020                  "aclocal.m4 with aclocal and run automake again.\n")
5021             if $VERSION ne $args[1];
5022
5023           $seen_automake_version = 1;
5024         }
5025       elsif ($macro eq 'AM_CONDITIONAL')
5026         {
5027           $configure_cond{$args[1]} = $where;
5028         }
5029       elsif ($macro eq 'AM_GNU_GETTEXT')
5030         {
5031           $seen_gettext = $where;
5032           $ac_gettext_location = $where;
5033           $seen_gettext_external = grep ($_ eq 'external', @args);
5034         }
5035       elsif ($macro eq 'AM_INIT_AUTOMAKE')
5036         {
5037           $seen_init_automake = $where;
5038           if (defined $args[2])
5039             {
5040               $package_version = $args[2];
5041               $package_version_location = $where;
5042             }
5043           elsif (defined $args[1])
5044             {
5045               $global_options = $args[1];
5046             }
5047         }
5048       elsif ($macro eq 'AM_MAINTAINER_MODE')
5049         {
5050           $seen_maint_mode = $where;
5051         }
5052       elsif ($macro eq 'AM_PROG_CC_C_O')
5053         {
5054           $seen_cc_c_o = $where;
5055         }
5056       elsif ($macro eq 'm4_include' || $macro eq 'm4_sinclude')
5057         {
5058           # Some modified versions of Autoconf don't use
5059           # forzen files.  Consequently it's possible that we see all
5060           # m4_include's performed during Autoconf's startup.
5061           # Obviously we don't want to distribute Autoconf's files
5062           # so we skip absolute filenames here.
5063           push @configure_deps, '$(top_srcdir)/' . $args[1]
5064             unless $here =~ m,^(?:\w:)?[\\/],;
5065         }
5066    }
5067 }
5068
5069
5070 # &scan_autoconf_files ()
5071 # -----------------------
5072 # Check whether we use `configure.ac' or `configure.in'.
5073 # Scan it (and possibly `aclocal.m4') for interesting things.
5074 # We must scan aclocal.m4 because there might be AC_SUBSTs and such there.
5075 sub scan_autoconf_files
5076 {
5077     # Reinitialize libsources here.  This isn't really necessary,
5078     # since we currently assume there is only one configure.ac.  But
5079     # that won't always be the case.
5080     %libsources = ();
5081
5082     scan_autoconf_traces (require_configure_ac);
5083
5084     # Set input and output files if not specified by user.
5085     if (! @input_files)
5086     {
5087         @input_files = sort keys %make_list;
5088         %output_files = %make_list;
5089     }
5090
5091     @configure_input_files = sort keys %make_list;
5092
5093     if (! $seen_init_automake)
5094       {
5095         err_ac ("no proper invocation of AM_INIT_AUTOMAKE was found.\nYou "
5096                 . "should verify that $configure_ac invokes AM_INIT_AUTOMAKE,"
5097                 . "\nthat aclocal.m4 is present in the top-level directory,\n"
5098                 . "and that aclocal.m4 was recently regenerated "
5099                 . "(using aclocal).");
5100       }
5101     else
5102       {
5103         if (! $seen_automake_version)
5104           {
5105             if (-f 'aclocal.m4')
5106               {
5107                 error ($seen_init_automake,
5108                        "your implementation of AM_INIT_AUTOMAKE comes from " .
5109                        "an\nold Automake version.  You should recreate " .
5110                        "aclocal.m4\nwith aclocal and run automake again.\n");
5111               }
5112             else
5113               {
5114                 error ($seen_init_automake,
5115                        "no proper implementation of AM_INIT_AUTOMAKE was " .
5116                        "found,\nprobably because aclocal.m4 is missing...\n" .
5117                        "You should run aclocal to create this file, then\n" .
5118                        "run automake again.\n");
5119               }
5120           }
5121       }
5122
5123     # Look for some files we need.  Always check for these.  This
5124     # check must be done for every run, even those where we are only
5125     # looking at a subdir Makefile.  We must set relative_dir so that
5126     # the file-finding machinery works.
5127     # FIXME: Is this broken because it needs dynamic scopes.
5128     # My tests seems to show it's not the case.
5129     $relative_dir = '.';
5130     require_conf_file ($configure_ac, FOREIGN,
5131                        'install-sh', 'mkinstalldirs', 'missing');
5132     err_am "`install.sh' is an anachronism; use `install-sh' instead"
5133       if -f $config_aux_path[0] . '/install.sh';
5134
5135     # Preserve dist_common for later.
5136     $configure_dist_common = variable_value ('DIST_COMMON') || '';
5137 }
5138
5139 ################################################################
5140
5141 # Set up for Cygnus mode.
5142 sub check_cygnus
5143 {
5144   return unless $cygnus_mode;
5145
5146   &set_strictness ('foreign');
5147   $options{'no-installinfo'} = 1;
5148   $options{'no-dependencies'} = 1;
5149   $use_dependencies = 0;
5150
5151   err_ac "`AM_MAINTAINER_MODE' required when --cygnus specified"
5152     if !$seen_maint_mode;
5153 }
5154
5155 # Do any extra checking for GNU standards.
5156 sub check_gnu_standards
5157 {
5158   if ($relative_dir eq '.')
5159     {
5160       # In top level (or only) directory.
5161
5162       # Accept one of these three licenses; default to COPYING.
5163       my $license = 'COPYING';
5164       foreach (qw /COPYING.LIB COPYING.LESSER/)
5165         {
5166           $license = $_ if -f $_;
5167         }
5168       require_file ("$am_file.am", GNU, $license,
5169                     qw/INSTALL NEWS README AUTHORS ChangeLog/);
5170     }
5171
5172   for my $opt ('no-installman', 'no-installinfo')
5173     {
5174       msg_var ('error-gnu', 'AUTOMAKE_OPTIONS',
5175                "option `$opt' disallowed by GNU standards")
5176         if (defined $options{$opt});
5177     }
5178 }
5179
5180 # Do any extra checking for GNITS standards.
5181 sub check_gnits_standards
5182 {
5183   if ($relative_dir eq '.')
5184     {
5185       # In top level (or only) directory.
5186       require_file ("$am_file.am", GNITS, 'THANKS');
5187     }
5188 }
5189
5190 ################################################################
5191 #
5192 # Functions to handle files of each language.
5193
5194 # Each `lang_X_rewrite($DIRECTORY, $BASE, $EXT)' function follows a
5195 # simple formula: Return value is LANG_SUBDIR if the resulting object
5196 # file should be in a subdir if the source file is, LANG_PROCESS if
5197 # file is to be dealt with, LANG_IGNORE otherwise.
5198
5199 # Much of the actual processing is handled in
5200 # handle_single_transform_list.  These functions exist so that
5201 # auxiliary information can be recorded for a later cleanup pass.
5202 # Note that the calls to these functions are computed, so don't bother
5203 # searching for their precise names in the source.
5204
5205 # This is just a convenience function that can be used to determine
5206 # when a subdir object should be used.
5207 sub lang_sub_obj
5208 {
5209     return defined $options{'subdir-objects'} ? LANG_SUBDIR : LANG_PROCESS;
5210 }
5211
5212 # Rewrite a single C source file.
5213 sub lang_c_rewrite
5214 {
5215   my ($directory, $base, $ext) = @_;
5216
5217   if (defined $options{'ansi2knr'} && $base =~ /_$/)
5218     {
5219       # FIXME: include line number in error.
5220       err_am "C source file `$base.c' would be deleted by ansi2knr rules";
5221     }
5222
5223   my $r = LANG_PROCESS;
5224   if (defined $options{'subdir-objects'})
5225     {
5226       $r = LANG_SUBDIR;
5227       $base = $directory . '/' . $base
5228         unless $directory eq '.' || $directory eq '';
5229
5230       err_am ("C objects in subdir but `AM_PROG_CC_C_O' "
5231               . "not in `$configure_ac'",
5232               uniq_scope => US_GLOBAL)
5233         unless $seen_cc_c_o;
5234
5235       require_conf_file ("$am_file.am", FOREIGN, 'compile');
5236
5237       # In this case we already have the directory information, so
5238       # don't add it again.
5239       $de_ansi_files{$base} = '';
5240     }
5241   else
5242     {
5243       $de_ansi_files{$base} = (($directory eq '.' || $directory eq '')
5244                                ? ''
5245                                : "$directory/");
5246     }
5247
5248     return $r;
5249 }
5250
5251 # Rewrite a single C++ source file.
5252 sub lang_cxx_rewrite
5253 {
5254     return &lang_sub_obj;
5255 }
5256
5257 # Rewrite a single header file.
5258 sub lang_header_rewrite
5259 {
5260     # Header files are simply ignored.
5261     return LANG_IGNORE;
5262 }
5263
5264 # Rewrite a single yacc file.
5265 sub lang_yacc_rewrite
5266 {
5267     my ($directory, $base, $ext) = @_;
5268
5269     my $r = &lang_sub_obj;
5270     (my $newext = $ext) =~ tr/y/c/;
5271     return ($r, $newext);
5272 }
5273
5274 # Rewrite a single yacc++ file.
5275 sub lang_yaccxx_rewrite
5276 {
5277     my ($directory, $base, $ext) = @_;
5278
5279     my $r = &lang_sub_obj;
5280     (my $newext = $ext) =~ tr/y/c/;
5281     return ($r, $newext);
5282 }
5283
5284 # Rewrite a single lex file.
5285 sub lang_lex_rewrite
5286 {
5287     my ($directory, $base, $ext) = @_;
5288
5289     my $r = &lang_sub_obj;
5290     (my $newext = $ext) =~ tr/l/c/;
5291     return ($r, $newext);
5292 }
5293
5294 # Rewrite a single lex++ file.
5295 sub lang_lexxx_rewrite
5296 {
5297     my ($directory, $base, $ext) = @_;
5298
5299     my $r = &lang_sub_obj;
5300     (my $newext = $ext) =~ tr/l/c/;
5301     return ($r, $newext);
5302 }
5303
5304 # Rewrite a single assembly file.
5305 sub lang_asm_rewrite
5306 {
5307     return &lang_sub_obj;
5308 }
5309
5310 # Rewrite a single Fortran 77 file.
5311 sub lang_f77_rewrite
5312 {
5313     return LANG_PROCESS;
5314 }
5315
5316 # Rewrite a single preprocessed Fortran 77 file.
5317 sub lang_ppf77_rewrite
5318 {
5319     return LANG_PROCESS;
5320 }
5321
5322 # Rewrite a single ratfor file.
5323 sub lang_ratfor_rewrite
5324 {
5325     return LANG_PROCESS;
5326 }
5327
5328 # Rewrite a single Objective C file.
5329 sub lang_objc_rewrite
5330 {
5331     return &lang_sub_obj;
5332 }
5333
5334 # Rewrite a single Java file.
5335 sub lang_java_rewrite
5336 {
5337     return LANG_SUBDIR;
5338 }
5339
5340 # The lang_X_finish functions are called after all source file
5341 # processing is done.  Each should handle defining rules for the
5342 # language, etc.  A finish function is only called if a source file of
5343 # the appropriate type has been seen.
5344
5345 sub lang_c_finish
5346 {
5347     # Push all libobjs files onto de_ansi_files.  We actually only
5348     # push files which exist in the current directory, and which are
5349     # genuine source files.
5350     foreach my $file (keys %libsources)
5351     {
5352         if ($file =~ /^(.*)\.[cly]$/ && -f "$relative_dir/$file")
5353         {
5354             $de_ansi_files{$1} = ''
5355         }
5356     }
5357
5358     if (defined $options{'ansi2knr'} && keys %de_ansi_files)
5359     {
5360         # Make all _.c files depend on their corresponding .c files.
5361         my @objects;
5362         foreach my $base (sort keys %de_ansi_files)
5363         {
5364             # Each _.c file must depend on ansi2knr; otherwise it
5365             # might be used in a parallel build before it is built.
5366             # We need to support files in the srcdir and in the build
5367             # dir (because these files might be auto-generated.  But
5368             # we can't use $< -- some makes only define $< during a
5369             # suffix rule.
5370             my $ansfile = $de_ansi_files{$base} . $base . '.c';
5371             $output_rules .= ($base . "_.c: $ansfile \$(ANSI2KNR)\n\t"
5372                               . '$(CPP) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) '
5373                               . '`if test -f $(srcdir)/' . $ansfile
5374                               . '; then echo $(srcdir)/' . $ansfile
5375                               . '; else echo ' . $ansfile . '; fi` '
5376                               . "| sed 's/^# \\([0-9]\\)/#line \\1/' "
5377                               . '| $(ANSI2KNR) > $@'
5378                               # If ansi2knr fails then we shouldn't
5379                               # create the _.c file
5380                               . " || rm -f \$\@\n");
5381             push (@objects, $base . '_.$(OBJEXT)');
5382             push (@objects, $base . '_.lo')
5383               if variable_defined ('LIBTOOL');
5384         }
5385
5386         # Make all _.o (and _.lo) files depend on ansi2knr.
5387         # Use a sneaky little hack to make it print nicely.
5388         &pretty_print_rule ('', '', @objects, ':', '$(ANSI2KNR)');
5389     }
5390 }
5391
5392 # This is a yacc helper which is called whenever we have decided to
5393 # compile a yacc file.
5394 sub lang_yacc_target_hook
5395 {
5396     my ($self, $aggregate, $output, $input) = @_;
5397
5398     my $flag = $aggregate . "_YFLAGS";
5399     if ((variable_defined ($flag)
5400          && &variable_value ($flag) =~ /$DASH_D_PATTERN/o)
5401         || (variable_defined ('YFLAGS')
5402             && &variable_value ('YFLAGS') =~ /$DASH_D_PATTERN/o))
5403     {
5404         (my $output_base = $output) =~ s/$KNOWN_EXTENSIONS_PATTERN$//;
5405         my $header = $output_base . '.h';
5406
5407         # Found a `-d' that applies to the compilation of this file.
5408         # Add a dependency for the generated header file, and arrange
5409         # for that file to be included in the distribution.
5410         # FIXME: this fails for `nodist_*_SOURCES'.
5411         $output_rules .= ("${header}: $output\n"
5412                           # Recover from removal of $header
5413                           . "\t\@if test ! -f \$@; then \\\n"
5414                           . "\t  rm -f $output; \\\n"
5415                           . "\t  \$(MAKE) $output; \\\n"
5416                           . "\telse :; fi\n");
5417         &push_dist_common ($header);
5418         # If the files are built in the build directory, then we want
5419         # to remove them with `make clean'.  If they are in srcdir
5420         # they shouldn't be touched.  However, we can't determine this
5421         # statically, and the GNU rules say that yacc/lex output files
5422         # should be removed by maintainer-clean.  So that's what we
5423         # do.
5424         $clean_files{$header} = MAINTAINER_CLEAN;
5425     }
5426     # Erase $OUTPUT on `make maintainer-clean' (by GNU standards).
5427     # See the comment above for $HEADER.
5428     $clean_files{$output} = MAINTAINER_CLEAN;
5429 }
5430
5431 # This is a lex helper which is called whenever we have decided to
5432 # compile a lex file.
5433 sub lang_lex_target_hook
5434 {
5435     my ($self, $aggregate, $output, $input) = @_;
5436     # If the files are built in the build directory, then we want to
5437     # remove them with `make clean'.  If they are in srcdir they
5438     # shouldn't be touched.  However, we can't determine this
5439     # statically, and the GNU rules say that yacc/lex output files
5440     # should be removed by maintainer-clean.  So that's what we do.
5441     $clean_files{$output} = MAINTAINER_CLEAN;
5442 }
5443
5444 # This is a helper for both lex and yacc.
5445 sub yacc_lex_finish_helper
5446 {
5447     return if defined $language_scratch{'lex-yacc-done'};
5448     $language_scratch{'lex-yacc-done'} = 1;
5449
5450     # If there is more than one distinct yacc (resp lex) source file
5451     # in a given directory, then the `ylwrap' program is required to
5452     # allow parallel builds to work correctly.  FIXME: for now, no
5453     # line number.
5454     require_conf_file ($configure_ac, FOREIGN, 'ylwrap');
5455     if ($config_aux_dir_set_in_configure_in)
5456     {
5457         &define_variable ('YLWRAP', $config_aux_dir . "/ylwrap", INTERNAL);
5458     }
5459     else
5460     {
5461         &define_variable ('YLWRAP', '$(top_srcdir)/ylwrap', INTERNAL);
5462     }
5463 }
5464
5465 sub lang_yacc_finish
5466 {
5467   return if defined $language_scratch{'yacc-done'};
5468   $language_scratch{'yacc-done'} = 1;
5469
5470   reject_var 'YACCFLAGS', "`YACCFLAGS' obsolete; use `YFLAGS' instead";
5471
5472   &yacc_lex_finish_helper
5473     if count_files_for_language ('yacc') > 1;
5474 }
5475
5476
5477 sub lang_lex_finish
5478 {
5479   return if defined $language_scratch{'lex-done'};
5480   $language_scratch{'lex-done'} = 1;
5481
5482   &yacc_lex_finish_helper
5483     if count_files_for_language ('lex') > 1;
5484 }
5485
5486
5487 # Given a hash table of linker names, pick the name that has the most
5488 # precedence.  This is lame, but something has to have global
5489 # knowledge in order to eliminate the conflict.  Add more linkers as
5490 # required.
5491 sub resolve_linker
5492 {
5493     my (%linkers) = @_;
5494
5495     foreach my $l (qw(GCJLINK CXXLINK F77LINK OBJCLINK))
5496     {
5497         return $l if defined $linkers{$l};
5498     }
5499     return 'LINK';
5500 }
5501
5502 # Called to indicate that an extension was used.
5503 sub saw_extension
5504 {
5505     my ($ext) = @_;
5506     if (! defined $extension_seen{$ext})
5507     {
5508         $extension_seen{$ext} = 1;
5509     }
5510     else
5511     {
5512         ++$extension_seen{$ext};
5513     }
5514 }
5515
5516 # Return the number of files seen for a given language.  Knows about
5517 # special cases we care about.  FIXME: this is hideous.  We need
5518 # something that involves real language objects.  For instance yacc
5519 # and yaccxx could both derive from a common yacc class which would
5520 # know about the strange ylwrap requirement.  (Or better yet we could
5521 # just not support legacy yacc!)
5522 sub count_files_for_language
5523 {
5524     my ($name) = @_;
5525
5526     my @names;
5527     if ($name eq 'yacc' || $name eq 'yaccxx')
5528     {
5529         @names = ('yacc', 'yaccxx');
5530     }
5531     elsif ($name eq 'lex' || $name eq 'lexxx')
5532     {
5533         @names = ('lex', 'lexxx');
5534     }
5535     else
5536     {
5537         @names = ($name);
5538     }
5539
5540     my $r = 0;
5541     foreach $name (@names)
5542     {
5543         my $lang = $languages{$name};
5544         foreach my $ext (@{$lang->extensions})
5545         {
5546             $r += $extension_seen{$ext}
5547                 if defined $extension_seen{$ext};
5548         }
5549     }
5550
5551     return $r
5552 }
5553
5554 # Called to ask whether source files have been seen . If HEADERS is 1,
5555 # headers can be included.
5556 sub saw_sources_p
5557 {
5558     my ($headers) = @_;
5559
5560     # count all the sources
5561     my $count = 0;
5562     foreach my $val (values %extension_seen)
5563     {
5564         $count += $val;
5565     }
5566
5567     if (!$headers)
5568     {
5569         $count -= count_files_for_language ('header');
5570     }
5571
5572     return $count > 0;
5573 }
5574
5575
5576 # register_language (%ATTRIBUTE)
5577 # ------------------------------
5578 # Register a single language.
5579 # Each %ATTRIBUTE is of the form ATTRIBUTE => VALUE.
5580 sub register_language (%)
5581 {
5582   my (%option) = @_;
5583
5584   # Set the defaults.
5585   $option{'ansi'} = 0
5586     unless defined $option{'ansi'};
5587   $option{'autodep'} = 'no'
5588     unless defined $option{'autodep'};
5589   $option{'linker'} = ''
5590     unless defined $option{'linker'};
5591   $option{'flags'} = []
5592     unless defined $option{'flags'};
5593   $option{'output_extensions'} = sub { return ( '.$(OBJEXT)', '.lo' ) }
5594     unless defined $option{'output_extensions'};
5595
5596   my $lang = new Language (%option);
5597
5598   # Fill indexes.
5599   grep ($extension_map{$_} = $lang->name, @{$lang->extensions});
5600   $languages{$lang->name} = $lang;
5601
5602   # Update the pattern of known extensions.
5603   accept_extensions (@{$lang->extensions});
5604
5605   # Upate the $suffix_rule map.
5606   foreach my $suffix (@{$lang->extensions})
5607     {
5608       foreach my $dest (&{$lang->output_extensions} ($suffix))
5609         {
5610           &register_suffix_rule ('internal', $suffix, $dest);
5611         }
5612     }
5613 }
5614
5615 # derive_suffix ($EXT, $OBJ)
5616 # --------------------------
5617 # This function is used to find a path from a user-specified suffix $EXT
5618 # to $OBJ or to some other suffix we recognize internally, e.g. `cc'.
5619 sub derive_suffix ($$)
5620 {
5621   my ($source_ext, $obj) = @_;
5622
5623   while (! $extension_map{$source_ext}
5624          && $source_ext ne $obj
5625          && exists $suffix_rules->{$source_ext}
5626          && exists $suffix_rules->{$source_ext}{$obj})
5627     {
5628       $source_ext = $suffix_rules->{$source_ext}{$obj}[0];
5629     }
5630
5631   return $source_ext;
5632 }
5633
5634
5635 ################################################################
5636
5637 # Pretty-print something and append to output_rules.
5638 sub pretty_print_rule
5639 {
5640     $output_rules .= &makefile_wrap (@_);
5641 }
5642
5643
5644 ################################################################
5645
5646
5647 ## -------------------------------- ##
5648 ## Handling the conditional stack.  ##
5649 ## -------------------------------- ##
5650
5651
5652 # $STRING
5653 # make_conditional_string ($NEGATE, $COND)
5654 # ----------------------------------------
5655 sub make_conditional_string ($$)
5656 {
5657   my ($negate, $cond) = @_;
5658   $cond = "${cond}_TRUE"
5659     unless $cond =~ /^TRUE|FALSE$/;
5660   $cond = Automake::Condition::conditional_negate ($cond)
5661     if $negate;
5662   return $cond;
5663 }
5664
5665
5666 # $COND
5667 # cond_stack_if ($NEGATE, $COND, $WHERE)
5668 # --------------------------------------
5669 sub cond_stack_if ($$$)
5670 {
5671   my ($negate, $cond, $where) = @_;
5672
5673   error $where, "$cond does not appear in AM_CONDITIONAL"
5674     if ! $configure_cond{$cond} && $cond !~ /^TRUE|FALSE$/;
5675
5676   push (@cond_stack, make_conditional_string ($negate, $cond));
5677
5678   return new Automake::Condition (@cond_stack);
5679 }
5680
5681
5682 # $COND
5683 # cond_stack_else ($NEGATE, $COND, $WHERE)
5684 # ----------------------------------------
5685 sub cond_stack_else ($$$)
5686 {
5687   my ($negate, $cond, $where) = @_;
5688
5689   if (! @cond_stack)
5690     {
5691       error $where, "else without if";
5692       return;
5693     }
5694
5695   $cond_stack[$#cond_stack] =
5696     Automake::Condition::conditional_negate ($cond_stack[$#cond_stack]);
5697
5698   # If $COND is given, check against it.
5699   if (defined $cond)
5700     {
5701       $cond = make_conditional_string ($negate, $cond);
5702
5703       error ($where, "else reminder ($negate$cond) incompatible with "
5704              . "current conditional: $cond_stack[$#cond_stack]")
5705         if $cond_stack[$#cond_stack] ne $cond;
5706     }
5707
5708   return new Automake::Condition (@cond_stack);
5709 }
5710
5711
5712 # $COND
5713 # cond_stack_endif ($NEGATE, $COND, $WHERE)
5714 # -----------------------------------------
5715 sub cond_stack_endif ($$$)
5716 {
5717   my ($negate, $cond, $where) = @_;
5718   my $old_cond;
5719
5720   if (! @cond_stack)
5721     {
5722       error $where, "endif without if: $negate$cond";
5723       return;
5724     }
5725
5726   # If $COND is given, check against it.
5727   if (defined $cond)
5728     {
5729       $cond = make_conditional_string ($negate, $cond);
5730
5731       error ($where, "endif reminder ($negate$cond) incompatible with "
5732              . "current conditional: $cond_stack[$#cond_stack]")
5733         if $cond_stack[$#cond_stack] ne $cond;
5734     }
5735
5736   pop @cond_stack;
5737
5738   return new Automake::Condition (@cond_stack);
5739 }
5740
5741
5742
5743
5744
5745 ## ------------------------ ##
5746 ## Handling the variables.  ##
5747 ## ------------------------ ##
5748
5749
5750 # @CONDS
5751 # target_conditions ($TARGET)
5752 # ---------------------------
5753 # Get the list of conditions that a target is defined with.
5754 sub target_conditions ($)
5755 {
5756     my ($target) = @_;
5757     my @conds = keys %{$targets{$target}};
5758     return new Automake::DisjConditions @conds;
5759 }
5760
5761 # $BOOLEAN
5762 # &variable_conditionally_defined ($VAR)
5763 # --------------------------------------
5764 sub variable_conditionally_defined ($)
5765 {
5766     my ($var) = @_;
5767
5768     # Traverse the variable recursively until we
5769     # find a variable defined conditionally.
5770     # Use `die' to abort the traversal, and pass it `$full_cond'
5771     # to we can find easily whether the `eval' block aborted
5772     # because we found a condition, or for some other error.
5773     eval
5774       {
5775         traverse_variable_recursively
5776           ($var,
5777            sub {
5778              my ($subvar, $val, $cond, $full_cond) = @_;
5779              die $full_cond if ! $full_cond->true;
5780              return ();
5781            },
5782            sub { return (); });
5783       };
5784     if ($@)
5785       {
5786         return 1 if ref($@) && $@->isa ("Automake::Condition");
5787         # Propagate other errors.
5788         die;
5789       }
5790     return 0;
5791 }
5792
5793
5794 # @VALUE
5795 # &variable_value_as_list_recursive_worker ($VAR, $COND, $LOC_WANTED)
5796 # -------------------------------------------------------------------
5797 # Return contents of VAR as a list, split on whitespace.  This will
5798 # recursively follow $(...) and ${...} inclusions.  It preserves @...@
5799 # substitutions.  If COND is 'all', then all values under all
5800 # conditions should be returned; if COND is a particular condition
5801 # then only the value for that condition should be returned;
5802 # otherwise, warn if VAR is conditionally defined.  If $LOC_WANTED is set,
5803 # return a list of [$location, $value] instead of a list of values.
5804 sub variable_value_as_list_recursive_worker ($$$)
5805 {
5806     my ($var, $cond_filter, $loc_wanted) = @_;
5807
5808     return traverse_variable_recursively
5809       ($var,
5810        # Construct [$location, $value] pairs if requested.
5811        sub {
5812          my ($var, $val, $cond, $full_cond) = @_;
5813          return [rvar ($var)->rdef ($cond)->location, $val] if $loc_wanted;
5814          return $val;
5815        },
5816        # Collect results.
5817        sub {
5818          my ($var, $parent_cond, @allresults) = @_;
5819          return map { my ($cond, @vals) = @$_; return @vals } @allresults;
5820        },
5821        $cond_filter);
5822 }
5823
5824
5825 # &variable_value_as_list_recursive ($VAR, $COND)
5826 # -----------------------------------------------
5827 # Return the list of values of $VAR in condition $COND.
5828 sub variable_value_as_list_recursive ($$)
5829 {
5830   return &variable_value_as_list_recursive_worker (@_, 0);
5831 }
5832
5833 # &variable_loc_and_value_as_list_recursive ($VAR, $COND)
5834 # ----------------------------------------------------------------
5835 # Return the values of $VAR in condition $COND as a list of
5836 # [$location, @values] pairs.
5837 sub variable_loc_and_value_as_list_recursive ($$)
5838 {
5839   return &variable_value_as_list_recursive_worker (@_, 1);
5840 }
5841
5842
5843 # &define_pretty_variable ($VAR, $COND, $WHERE, @VALUE)
5844 # -----------------------------------------------------
5845 # Like define_variable, but the value is a list, and the variable may
5846 # be defined conditionally.  The second argument is the Condition
5847 # under which the value should be defined; this should be the empty
5848 # string to define the variable unconditionally.  The third argument
5849 # is a list holding the values to use for the variable.  The value is
5850 # pretty printed in the output file.
5851 sub define_pretty_variable ($$$@)
5852 {
5853     my ($var, $cond, $where, @value) = @_;
5854
5855     if (! variable_defined ($var, $cond))
5856     {
5857         Automake::Variable::define ($var, VAR_AUTOMAKE, '', $cond, "@value",
5858                                     '', $where, VAR_PRETTY);
5859         rvar ($var)->rdef ($cond)->set_seen;
5860     }
5861 }
5862
5863
5864 # define_variable ($VAR, $VALUE, $WHERE)
5865 # --------------------------------------
5866 # Define a new user variable VAR to VALUE, but only if not already defined.
5867 sub define_variable ($$$)
5868 {
5869     my ($var, $value, $where) = @_;
5870     define_pretty_variable ($var, TRUE, $where, $value);
5871 }
5872
5873
5874 # Like define_variable, but define a variable to be the configure
5875 # substitution by the same name.
5876 sub define_configure_variable ($)
5877 {
5878   my ($var) = @_;
5879   if (! variable_defined ($var, TRUE))
5880     {
5881       my $pretty = VAR_ASIS;
5882       my $owner = VAR_CONFIGURE;
5883
5884       # Do not output the ANSI2KNR configure variable -- we AC_SUBST
5885       # it in protos.m4, but later redefine it elsewhere.  This is
5886       # pretty hacky.  We also don't output AMDEPBACKSLASH: it might
5887       # be subst'd by `\', which certainly would not be appreciated by
5888       # Make.
5889       if ($var eq 'ANSI2KNR' || $var eq 'AMDEPBACKSLASH')
5890         {
5891           $pretty = VAR_SILENT;
5892           $owner = VAR_AUTOMAKE;
5893         }
5894
5895       Automake::Variable::define ($var, $owner, '', TRUE, subst $var,
5896                                   '', $configure_vars{$var}, $pretty);
5897     }
5898 }
5899
5900
5901 # define_compiler_variable ($LANG)
5902 # --------------------------------
5903 # Define a compiler variable.  We also handle defining the `LT'
5904 # version of the command when using libtool.
5905 sub define_compiler_variable ($)
5906 {
5907     my ($lang) = @_;
5908
5909     my ($var, $value) = ($lang->compiler, $lang->compile);
5910     &define_variable ($var, $value, INTERNAL);
5911     &define_variable ("LT$var", "\$(LIBTOOL) --mode=compile $value", INTERNAL)
5912       if variable_defined ('LIBTOOL');
5913 }
5914
5915
5916 # define_linker_variable ($LANG)
5917 # ------------------------------
5918 # Define linker variables.
5919 sub define_linker_variable ($)
5920 {
5921     my ($lang) = @_;
5922
5923     my ($var, $value) = ($lang->lder, $lang->ld);
5924     # CCLD = $(CC).
5925     &define_variable ($lang->lder, $lang->ld, INTERNAL);
5926     # CCLINK = $(CCLD) blah blah...
5927     &define_variable ($lang->linker,
5928                       ((variable_defined ('LIBTOOL')
5929                         ? '$(LIBTOOL) --mode=link ' : '')
5930                        . $lang->link),
5931                       INTERNAL);
5932 }
5933
5934 ################################################################
5935
5936 ## ---------------- ##
5937 ## Handling rules.  ##
5938 ## ---------------- ##
5939
5940 sub register_suffix_rule ($$$)
5941 {
5942   my ($where, $src, $dest) = @_;
5943
5944   verb "Sources ending in $src become $dest";
5945   push @suffixes, $src, $dest;
5946
5947   # When tranforming sources to objects, Automake uses the
5948   # %suffix_rules to move from each source extension to
5949   # `.$(OBJEXT)', not to `.o' or `.obj'.  However some people
5950   # define suffix rules for `.o' or `.obj', so internally we will
5951   # consider these extensions equivalent to `.$(OBJEXT)'.  We
5952   # CANNOT rewrite the target (i.e., automagically replace `.o'
5953   # and `.obj' by `.$(OBJEXT)' in the output), or warn the user
5954   # that (s)he'd better use `.$(OBJEXT)', because Automake itself
5955   # output suffix rules for `.o' or `.obj'...
5956   $dest = '.$(OBJEXT)' if ($dest eq '.o' || $dest eq '.obj');
5957
5958   # Reading the comments near the declaration of $suffix_rules might
5959   # help to understand the update of $suffix_rules that follows...
5960
5961   # Register $dest as a possible destination from $src.
5962   # We might have the create the \hash.
5963   if (exists $suffix_rules->{$src})
5964     {
5965       $suffix_rules->{$src}{$dest} = [ $dest, 1 ];
5966     }
5967   else
5968     {
5969       $suffix_rules->{$src} = { $dest => [ $dest, 1 ] };
5970     }
5971
5972   # If we know how to transform $dest in something else, then
5973   # we know how to transform $src in that "something else".
5974   if (exists $suffix_rules->{$dest})
5975     {
5976       for my $dest2 (keys %{$suffix_rules->{$dest}})
5977         {
5978           my $dist = $suffix_rules->{$dest}{$dest2}[1] + 1;
5979           # Overwrite an existing $src->$dest2 path only if
5980           # the path via $dest which is shorter.
5981           if (! exists $suffix_rules->{$src}{$dest2}
5982               || $suffix_rules->{$src}{$dest2}[1] > $dist)
5983             {
5984               $suffix_rules->{$src}{$dest2} = [ $dest, $dist ];
5985             }
5986         }
5987     }
5988
5989   # Similarly, any extension that can be derived into $src
5990   # can be derived into the same extenstions as $src can.
5991   my @dest2 = keys %{$suffix_rules->{$src}};
5992   for my $src2 (keys %$suffix_rules)
5993     {
5994       if (exists $suffix_rules->{$src2}{$src})
5995         {
5996           for my $dest2 (@dest2)
5997             {
5998               my $dist = $suffix_rules->{$src}{$dest2} + 1;
5999               # Overwrite an existing $src2->$dest2 path only if
6000               # the path via $src is shorter.
6001               if (! exists $suffix_rules->{$src2}{$dest2}
6002                   || $suffix_rules->{$src2}{$dest2}[1] > $dist)
6003                 {
6004                   $suffix_rules->{$src2}{$dest2} = [ $src, $dist ];
6005                 }
6006             }
6007         }
6008     }
6009 }
6010
6011 # @CONDS
6012 # rule_define ($TARGET, $SOURCE, $OWNER, $COND, $WHERE)
6013 # -----------------------------------------------------
6014 # Define a new rule.  $TARGET is the rule name.  $SOURCE
6015 # is the filename the rule comes from.  $OWNER is the
6016 # owner of the rule (TARGET_AUTOMAKE or TARGET_USER).
6017 # $COND is the Condition under which the rule is defined.
6018 # $WHERE is the Location where the rule is defined.
6019 # Returns a (possibly empty) list of Conditions where the rule
6020 # should be defined.
6021 sub rule_define ($$$$$)
6022 {
6023   my ($target, $source, $owner, $cond, $where) = @_;
6024
6025   prog_error "$where is not a reference"
6026     unless ref $where;
6027   prog_error "$cond is not a reference"
6028     unless ref $cond;
6029
6030   # Don't even think about defining a rule in condition FALSE.
6031   return () if $cond == FALSE;
6032
6033   # For now `foo:' will override `foo$(EXEEXT):'.  This is temporary,
6034   # though, so we emit a warning.
6035   (my $noexe = $target) =~ s,\$\(EXEEXT\)$,,;
6036   if ($noexe ne $target
6037       && exists $targets{$noexe}
6038       && exists $targets{$noexe}{$cond}
6039       && $target_name{$noexe}{$cond} ne $target)
6040     {
6041       # The no-exeext option enables this feature.
6042       if (! defined $options{'no-exeext'})
6043         {
6044           msg ('obsolete', $targets{$noexe}{$cond},
6045                "deprecated feature: target `$noexe' overrides "
6046                . "`$noexe\$(EXEEXT)'\n"
6047                . "change your target to read `$noexe\$(EXEEXT)'");
6048           msg ('obsolete', $where, "target `$target' was defined here");
6049         }
6050       # Don't `return ()' now, as this might hide target clashes
6051       # detected below.
6052     }
6053
6054   # For now on, strip off $(EXEEXT) from $target, so we can diagnose
6055   # a clash if `ctags$(EXEEXT):' is redefined after `ctags:'.
6056   my $realtarget = $target;
6057   $target = $noexe;
6058
6059   # A GNU make-style pattern rule has a single "%" in the target name.
6060   msg ('portability', $where,
6061        "`%'-style pattern rules are a GNU make extension")
6062     if $target =~ /^[^%]*%[^%]*$/;
6063
6064   # Diagnose target redefinitions.
6065   if (exists $target_source{$target}{$cond})
6066     {
6067       # Sanity checks.
6068       prog_error ("\$target_source{$target}{$cond} exists, but \$target_owner"
6069                   . " doesn't.")
6070         unless exists $target_owner{$target}{$cond};
6071       prog_error ("\$target_source{$target}{$cond} exists, but \$targets"
6072                   . " doesn't.")
6073         unless exists $targets{$target}{$cond};
6074       prog_error ("\$target_source{$target}{$cond} exists, but \$target_name"
6075                   . " doesn't.")
6076         unless exists $target_name{$target}{$cond};
6077
6078       my $oldowner  = $target_owner{$target}{$cond};
6079
6080       # Don't mention true conditions in diagnostics.
6081       my $condmsg =
6082         $cond == TRUE ? '' : " in condition `" . $cond->human . "'";
6083
6084       if ($owner == TARGET_USER)
6085         {
6086           if ($oldowner == TARGET_USER)
6087             {
6088               # Ignore `%'-style pattern rules.  We'd need the
6089               # dependencies to detect duplicates, and they are
6090               # already diagnosed as unportable by -Wportability.
6091               if ($target !~ /^[^%]*%[^%]*$/)
6092                 {
6093                   ## FIXME: Presently we can't diagnose duplcate user rules
6094                   ## because we doesn't distinguish rules with commands
6095                   ## from rules that only add dependencies.  E.g.,
6096                   ##   .PHONY: foo
6097                   ##   .PHONY: bar
6098                   ## is legitimate. (This is phony.test.)
6099
6100                   # msg ('syntax', $where,
6101                   #      "redefinition of `$target'$condmsg...", partial => 1);
6102                   # msg_cond_target ('syntax', $cond, $target,
6103                   #                "... `$target' previously defined here");
6104                 }
6105               # Return so we don't redefine the rule in our tables,
6106               # don't check for ambiguous condition, etc.  The rule
6107               # will be output anyway beauce &read_am_file ignore the
6108               # return code.
6109               return ();
6110             }
6111           else
6112             {
6113               # Since we parse the user Makefile.am before reading
6114               # the Automake fragments, this condition should never happen.
6115               prog_error ("user target `$target' seen after Automake's "
6116                           . "definition\nfrom `$targets{$target}$condmsg'");
6117             }
6118         }
6119       else # $owner == TARGET_AUTOMAKE
6120         {
6121           if ($oldowner == TARGET_USER)
6122             {
6123               # -am targets listed in %dependencies support a -local
6124               # variant.  If the user tries to override TARGET or
6125               # TARGET-am for which there exists a -local variant,
6126               # just tell the user to use it.
6127               my $hint = 0;
6128               my $noam = $target;
6129               $noam =~ s/-am$//;
6130               if (exists $dependencies{"$noam-am"})
6131                 {
6132                   $hint = "consider using $target-local instead of $target";
6133                 }
6134
6135               msg_cond_target ('override', $cond, $target,
6136                                "user target `$target' defined here"
6137                                . "$condmsg...", partial => 1);
6138               msg ('override', $where,
6139                    "... overrides Automake target `$target' defined here",
6140                    partial => $hint);
6141               msg_cond_target ('override', $cond, $target, $hint)
6142                 if $hint;
6143
6144               # Don't overwrite the user definition of TARGET.
6145               return ();
6146             }
6147           else # $oldowner == TARGET_AUTOMAKE
6148             {
6149               # Automake should ignore redefinitions of its own
6150               # rules if they came from the same file.  This makes
6151               # it easier to process a Makefile fragment several times.
6152               # Hower it's an error if the target is defined in many
6153               # files.  E.g., the user might be using bin_PROGRAMS = ctags
6154               # which clashes with our `ctags' rule.
6155               # (It would be more accurate if we had a way to compare
6156               # the *content* of both rules.  Then $targets_source would
6157               # be useless.)
6158               my $oldsource = $target_source{$target}{$cond};
6159               return () if $source eq $oldsource;
6160
6161               msg ('syntax', $where, "redefinition of `$target'$condmsg...",
6162                    partial => 1);
6163               msg_cond_target ('syntax', $cond, $target,
6164                                "... `$target' previously defined here");
6165               return ();
6166             }
6167         }
6168       # Never reached.
6169       prog_error ("Unreachable place reached.");
6170     }
6171
6172   # Conditions for which the rule should be defined.
6173   my @conds = $cond;
6174
6175   # Check ambiguous conditional definitions.
6176   my ($message, $ambig_cond) =
6177     condition_ambiguous_p ($target, $cond, target_conditions ($target));
6178   if ($message)                 # We have an ambiguty.
6179     {
6180       if ($owner == TARGET_USER)
6181         {
6182           # For user rules, just diagnose the ambiguity.
6183           msg 'syntax', $where, "$message ...", partial => 1;
6184           msg_cond_target ('syntax', $ambig_cond, $target,
6185                            "... `$target' previously defined here");
6186           return ();
6187         }
6188       else
6189         {
6190           # FIXME: for Automake rules, we can't diagnose ambiguities yet.
6191           # The point is that Automake doesn't propagate conditions
6192           # everywhere.  For instance &handle_PROGRAMS doesn't care if
6193           # bin_PROGRAMS was defined conditionally or not.
6194           # On the following input
6195           #   if COND1
6196           #   foo:
6197           #           ...
6198           #   else
6199           #   bin_PROGRAMS = foo
6200           #   endif
6201           # &handle_PROGRAMS will attempt to define a `foo:' rule
6202           # in condition TRUE (which conflicts with COND1).  Fixing
6203           # this in &handle_PROGRAMS and siblings seems hard: you'd
6204           # have to explain &file_contents what to do with a
6205           # condition.  So for now we do our best *here*.  If `foo:'
6206           # was already defined in condition COND1 and we want to define
6207           # it in condition TRUE, then define it only in condition !COND1.
6208           # (See cond14.test and cond15.test for some test cases.)
6209           my $defined_conds = target_conditions ($target);
6210           @conds = ();
6211           for my $undefined_cond ($defined_conds->invert->conds)
6212             {
6213               push @conds, $cond->merge ($undefined_cond);
6214             }
6215           # No conditions left to define the rule.
6216           # Warn, because our workaround is meaningless in this case.
6217           if (scalar @conds == 0)
6218             {
6219               msg 'syntax', $where, "$message ...", partial => 1;
6220               msg_cond_target ('syntax', $ambig_cond, $target,
6221                                "... `$target' previously defined here");
6222               return ();
6223             }
6224         }
6225     }
6226
6227   # Finally define this rule.
6228   for my $c (@conds)
6229     {
6230       $targets{$target}{$c} = $where->clone;
6231       $target_source{$target}{$c} = $source;
6232       $target_owner{$target}{$c} = $owner;
6233       $target_name{$target}{$c} = $realtarget;
6234     }
6235
6236   # We honor inference rules with multiple targets because many
6237   # make support this and people use it.  However this is disallowed
6238   # by POSIX.  We'll print a warning later.
6239   my $target_count = 0;
6240   my $inference_rule_count = 0;
6241   for my $t (split (' ', $target))
6242     {
6243       ++$target_count;
6244       # Check the rule for being a suffix rule. If so, store in a hash.
6245       # Either it's a rule for two known extensions...
6246       if ($t =~ /^($KNOWN_EXTENSIONS_PATTERN)($KNOWN_EXTENSIONS_PATTERN)$/
6247           # ...or it's a rule with unknown extensions (.i.e, the rule
6248           # looks like `.foo.bar:' but `.foo' or `.bar' are not
6249           # declared in SUFFIXES and are not known language
6250           # extensions).  Automake will complete SUFFIXES from
6251           # @suffixes automatically (see handle_footer).
6252           || ($t =~ /$SUFFIX_RULE_PATTERN/o && accept_extensions($1)))
6253         {
6254           ++$inference_rule_count;
6255           register_suffix_rule ($where, $1, $2);
6256         }
6257     }
6258
6259   # POSIX allow multiple targets befor the colon, but disallow
6260   # definitions of multiple Inference rules.  It's also
6261   # disallowed to mix plain targets with inference rules.
6262   msg ('portability', $where,
6263        "Inference rules can have only one target before the colon (POSIX).")
6264     if $inference_rule_count > 0 && $target_count > 1;
6265
6266   return @conds;
6267 }
6268
6269
6270 # See if a target exists.
6271 sub target_defined
6272 {
6273     my ($target) = @_;
6274     return exists $targets{$target};
6275 }
6276
6277
6278 ################################################################
6279
6280 # &check_trailing_slash ($WHERE, $LINE)
6281 # --------------------------------------
6282 # Return 1 iff $LINE ends with a slash.
6283 # Might modify $LINE.
6284 sub check_trailing_slash ($\$)
6285 {
6286   my ($where, $line) = @_;
6287
6288   # Ignore `##' lines.
6289   return 0 if $$line =~ /$IGNORE_PATTERN/o;
6290
6291   # Catch and fix a common error.
6292   msg "syntax", $where, "whitespace following trailing backslash"
6293     if $$line =~ s/\\\s+\n$/\\\n/;
6294
6295   return $$line =~ /\\$/;
6296 }
6297
6298
6299 # &read_am_file ($AMFILE, $WHERE)
6300 # -------------------------------
6301 # Read Makefile.am and set up %contents.  Simultaneously copy lines
6302 # from Makefile.am into $output_trailer, or define variables as
6303 # appropriate.  NOTE we put rules in the trailer section.  We want
6304 # user rules to come after our generated stuff.
6305 sub read_am_file ($$)
6306 {
6307     my ($amfile, $where) = @_;
6308
6309     my $am_file = new Automake::XFile ("< $amfile");
6310     verb "reading $amfile";
6311
6312     my $spacing = '';
6313     my $comment = '';
6314     my $blank = 0;
6315     my $saw_bk = 0;
6316
6317     use constant IN_VAR_DEF => 0;
6318     use constant IN_RULE_DEF => 1;
6319     use constant IN_COMMENT => 2;
6320     my $prev_state = IN_RULE_DEF;
6321
6322     while ($_ = $am_file->getline)
6323     {
6324         $where->set ("$amfile:$.");
6325         if (/$IGNORE_PATTERN/o)
6326         {
6327             # Merely delete comments beginning with two hashes.
6328         }
6329         elsif (/$WHITE_PATTERN/o)
6330         {
6331             error $where, "blank line following trailing backslash"
6332               if $saw_bk;
6333             # Stick a single white line before the incoming macro or rule.
6334             $spacing = "\n";
6335             $blank = 1;
6336             # Flush all comments seen so far.
6337             if ($comment ne '')
6338             {
6339                 $output_vars .= $comment;
6340                 $comment = '';
6341             }
6342         }
6343         elsif (/$COMMENT_PATTERN/o)
6344         {
6345             # Stick comments before the incoming macro or rule.  Make
6346             # sure a blank line preceeds first block of comments.
6347             $spacing = "\n" unless $blank;
6348             $blank = 1;
6349             $comment .= $spacing . $_;
6350             $spacing = '';
6351             $prev_state = IN_COMMENT;
6352         }
6353         else
6354         {
6355             last;
6356         }
6357         $saw_bk = check_trailing_slash ($where, $_);
6358     }
6359
6360     # We save the conditional stack on entry, and then check to make
6361     # sure it is the same on exit.  This lets us conditonally include
6362     # other files.
6363     my @saved_cond_stack = @cond_stack;
6364     my $cond = new Automake::Condition (@cond_stack);
6365
6366     my $last_var_name = '';
6367     my $last_var_type = '';
6368     my $last_var_value = '';
6369     my $last_where;
6370     # FIXME: shouldn't use $_ in this loop; it is too big.
6371     while ($_)
6372     {
6373         $where->set ("$amfile:$.");
6374
6375         # Make sure the line is \n-terminated.
6376         chomp;
6377         $_ .= "\n";
6378
6379         # Don't look at MAINTAINER_MODE_TRUE here.  That shouldn't be
6380         # used by users.  @MAINT@ is an anachronism now.
6381         $_ =~ s/\@MAINT\@//g
6382             unless $seen_maint_mode;
6383
6384         my $new_saw_bk = check_trailing_slash ($where, $_);
6385
6386         if (/$IGNORE_PATTERN/o)
6387         {
6388             # Merely delete comments beginning with two hashes.
6389         }
6390         elsif (/$WHITE_PATTERN/o)
6391         {
6392             # Stick a single white line before the incoming macro or rule.
6393             $spacing = "\n";
6394             error $where, "blank line following trailing backslash"
6395               if $saw_bk;
6396         }
6397         elsif (/$COMMENT_PATTERN/o)
6398         {
6399             # Stick comments before the incoming macro or rule.
6400             $comment .= $spacing . $_;
6401             $spacing = '';
6402             error $where, "comment following trailing backslash"
6403               if $saw_bk && $comment eq '';
6404             $prev_state = IN_COMMENT;
6405         }
6406         elsif ($saw_bk)
6407         {
6408             if ($prev_state == IN_RULE_DEF)
6409             {
6410               my $cond = new Automake::Condition @cond_stack;
6411               $output_trailer .= $cond->subst_string;
6412               $output_trailer .= $_;
6413             }
6414             elsif ($prev_state == IN_COMMENT)
6415             {
6416                 # If the line doesn't start with a `#', add it.
6417                 # We do this because a continuated comment like
6418                 #   # A = foo \
6419                 #         bar \
6420                 #         baz
6421                 # is not portable.  BSD make doesn't honor
6422                 # escaped newlines in comments.
6423                 s/^#?/#/;
6424                 $comment .= $spacing . $_;
6425             }
6426             else # $prev_state == IN_VAR_DEF
6427             {
6428               $last_var_value .= ' '
6429                 unless $last_var_value =~ /\s$/;
6430               $last_var_value .= $_;
6431
6432               if (!/\\$/)
6433                 {
6434                   Automake::Variable::define ($last_var_name, VAR_MAKEFILE,
6435                                               $last_var_type, $cond,
6436                                               $last_var_value, $comment,
6437                                               $last_where, VAR_ASIS)
6438                     if $cond != FALSE;
6439                   $comment = $spacing = '';
6440                 }
6441             }
6442         }
6443
6444         elsif (/$IF_PATTERN/o)
6445           {
6446             $cond = cond_stack_if ($1, $2, $where);
6447           }
6448         elsif (/$ELSE_PATTERN/o)
6449           {
6450             $cond = cond_stack_else ($1, $2, $where);
6451           }
6452         elsif (/$ENDIF_PATTERN/o)
6453           {
6454             $cond = cond_stack_endif ($1, $2, $where);
6455           }
6456
6457         elsif (/$RULE_PATTERN/o)
6458         {
6459             # Found a rule.
6460             $prev_state = IN_RULE_DEF;
6461
6462             # For now we have to output all definitions of user rules
6463             # and can't diagnose duplicates (see the comment in
6464             # rule_define). So we go on and ignore the return value.
6465             rule_define ($1, $amfile, TARGET_USER, $cond, $where);
6466
6467             check_variable_expansions ($_, $where);
6468
6469             $output_trailer .= $comment . $spacing;
6470             my $cond = new Automake::Condition @cond_stack;
6471             $output_trailer .= $cond->subst_string;
6472             $output_trailer .= $_;
6473             $comment = $spacing = '';
6474         }
6475         elsif (/$ASSIGNMENT_PATTERN/o)
6476         {
6477             # Found a macro definition.
6478             $prev_state = IN_VAR_DEF;
6479             $last_var_name = $1;
6480             $last_var_type = $2;
6481             $last_var_value = $3;
6482             $last_where = $where->clone;
6483             if ($3 ne '' && substr ($3, -1) eq "\\")
6484             {
6485                 # We preserve the `\' because otherwise the long lines
6486                 # that are generated will be truncated by broken
6487                 # `sed's.
6488                 $last_var_value = $3 . "\n";
6489             }
6490
6491             if (!/\\$/)
6492               {
6493                 Automake::Variable::define ($last_var_name, VAR_MAKEFILE,
6494                                             $last_var_type, $cond,
6495                                             $last_var_value, $comment,
6496                                             $last_where, VAR_ASIS)
6497                   if $cond != FALSE;
6498                 $comment = $spacing = '';
6499               }
6500         }
6501         elsif (/$INCLUDE_PATTERN/o)
6502         {
6503             my $path = $1;
6504
6505             if ($path =~ s/^\$\(top_srcdir\)\///)
6506               {
6507                 push (@include_stack, "\$\(top_srcdir\)/$path");
6508                 # Distribute any included file.
6509
6510                 # Always use the $(top_srcdir) prefix in DIST_COMMON,
6511                 # otherwise OSF make will implicitely copy the included
6512                 # file in the build tree during `make distdir' to satisfy
6513                 # the dependency.
6514                 # (subdircond2.test and subdircond3.test will fail.)
6515                 push_dist_common ("\$\(top_srcdir\)/$path");
6516               }
6517             else
6518               {
6519                 $path =~ s/\$\(srcdir\)\///;
6520                 push (@include_stack, "\$\(srcdir\)/$path");
6521                 # Always use the $(srcdir) prefix in DIST_COMMON,
6522                 # otherwise OSF make will implicitely copy the included
6523                 # file in the build tree during `make distdir' to satisfy
6524                 # the dependency.
6525                 # (subdircond2.test and subdircond3.test will fail.)
6526                 push_dist_common ("\$\(srcdir\)/$path");
6527                 $path = $relative_dir . "/" . $path if $relative_dir ne '.';
6528               }
6529             $where->push_context ("`$path' included from here");
6530             &read_am_file ($path, $where);
6531             $where->pop_context;
6532         }
6533         else
6534         {
6535             # This isn't an error; it is probably a continued rule.
6536             # In fact, this is what we assume.
6537             $prev_state = IN_RULE_DEF;
6538             check_variable_expansions ($_, $where);
6539             $output_trailer .= $comment . $spacing;
6540             my $cond = new Automake::Condition @cond_stack;
6541             $output_trailer .= $cond->subst_string;
6542             $output_trailer .= $_;
6543             $comment = $spacing = '';
6544             error $where, "`#' comment at start of rule is unportable"
6545               if $_ =~ /^\t\s*\#/;
6546         }
6547
6548         $saw_bk = $new_saw_bk;
6549         $_ = $am_file->getline;
6550     }
6551
6552     $output_trailer .= $comment;
6553
6554     error ($where, "trailing backslash on last line")
6555       if $saw_bk;
6556
6557     error ($where, (@cond_stack ? "unterminated conditionals: @cond_stack"
6558                     : "too many conditionals closed in include file"))
6559       if "@saved_cond_stack" ne "@cond_stack";
6560 }
6561
6562
6563 # define_standard_variables ()
6564 # ----------------------------
6565 # A helper for read_main_am_file which initializes configure variables
6566 # and variables from header-vars.am.
6567 sub define_standard_variables
6568 {
6569   my $saved_output_vars = $output_vars;
6570   my ($comments, undef, $rules) =
6571     file_contents_internal (1, "$libdir/am/header-vars.am",
6572                             new Automake::Location);
6573
6574   foreach my $var (sort keys %configure_vars)
6575     {
6576       &define_configure_variable ($var);
6577     }
6578
6579   $output_vars .= $comments . $rules;
6580 }
6581
6582 # Read main am file.
6583 sub read_main_am_file
6584 {
6585     my ($amfile) = @_;
6586
6587     # This supports the strange variable tricks we are about to play.
6588     prog_error (macros_dump () . "variable defined before read_main_am_file")
6589       if (scalar (variables) > 0);
6590
6591     # Generate copyright header for generated Makefile.in.
6592     # We do discard the output of predefined variables, handled below.
6593     $output_vars = ("# $in_file_name generated by automake "
6594                    . $VERSION . " from $am_file_name.\n");
6595     $output_vars .= '# ' . subst ('configure_input') . "\n";
6596     $output_vars .= $gen_copyright;
6597
6598     # We want to predefine as many variables as possible.  This lets
6599     # the user set them with `+=' in Makefile.am.
6600     &define_standard_variables;
6601
6602     # Read user file, which might override some of our values.
6603     &read_am_file ($amfile, new Automake::Location);
6604 }
6605
6606
6607
6608 ################################################################
6609
6610 # $FLATTENED
6611 # &flatten ($STRING)
6612 # ------------------
6613 # Flatten the $STRING and return the result.
6614 sub flatten
6615 {
6616   $_ = shift;
6617
6618   s/\\\n//somg;
6619   s/\s+/ /g;
6620   s/^ //;
6621   s/ $//;
6622
6623   return $_;
6624 }
6625
6626
6627 # @PARAGRAPHS
6628 # &make_paragraphs ($MAKEFILE, [%TRANSFORM])
6629 # ------------------------------------------
6630 # Load a $MAKEFILE, apply the %TRANSFORM, and return it as a list of
6631 # paragraphs.
6632 sub make_paragraphs ($%)
6633 {
6634     my ($file, %transform) = @_;
6635
6636     # Complete %transform with global options and make it a Perl
6637     # $command.
6638     my $command =
6639       "s/$IGNORE_PATTERN//gm;"
6640         . transform (%transform,
6641
6642                      'CYGNUS'          => $cygnus_mode,
6643                      'MAINTAINER-MODE'
6644                      => $seen_maint_mode ? subst ('MAINTAINER_MODE_TRUE') : '',
6645
6646                      'SHAR'        => $options{'dist-shar'} || 0,
6647                      'BZIP2'       => $options{'dist-bzip2'} || 0,
6648                      'ZIP'         => $options{'dist-zip'} || 0,
6649                      'COMPRESS'    => $options{'dist-tarZ'} || 0,
6650
6651                      'INSTALL-INFO' => !$options{'no-installinfo'},
6652                      'INSTALL-MAN'  => !$options{'no-installman'},
6653                      'CK-NEWS'      => $options{'check-news'} || 0,
6654
6655                      'SUBDIRS'      => variable_defined ('SUBDIRS'),
6656                      'TOPDIR'       => backname ($relative_dir),
6657                      'TOPDIR_P'     => $relative_dir eq '.',
6658                      'CONFIGURE-AC' => $configure_ac,
6659
6660                      'BUILD'    => $seen_canonical == AC_CANONICAL_SYSTEM,
6661                      'HOST'     => $seen_canonical,
6662                      'TARGET'   => $seen_canonical == AC_CANONICAL_SYSTEM,
6663
6664                      'LIBTOOL'      => variable_defined ('LIBTOOL'))
6665           # We don't need more than two consecutive new-lines.
6666           . 's/\n{3,}/\n\n/g';
6667
6668     # Swallow the file and apply the COMMAND.
6669     my $fc_file = new Automake::XFile "< $file";
6670     # Looks stupid?
6671     verb "reading $file";
6672     my $saved_dollar_slash = $/;
6673     undef $/;
6674     $_ = $fc_file->getline;
6675     $/ = $saved_dollar_slash;
6676     eval $command;
6677     $fc_file->close;
6678     my $content = $_;
6679
6680     # Split at unescaped new lines.
6681     my @lines = split (/(?<!\\)\n/, $content);
6682     my @res;
6683
6684     while (defined ($_ = shift @lines))
6685       {
6686         my $paragraph = "$_";
6687         # If we are a rule, eat as long as we start with a tab.
6688         if (/$RULE_PATTERN/smo)
6689           {
6690             while (defined ($_ = shift @lines) && $_ =~ /^\t/)
6691               {
6692                 $paragraph .= "\n$_";
6693               }
6694             unshift (@lines, $_);
6695           }
6696
6697         # If we are a comments, eat as much comments as you can.
6698         elsif (/$COMMENT_PATTERN/smo)
6699           {
6700             while (defined ($_ = shift @lines)
6701                    && $_ =~ /$COMMENT_PATTERN/smo)
6702               {
6703                 $paragraph .= "\n$_";
6704               }
6705             unshift (@lines, $_);
6706           }
6707
6708         push @res, $paragraph;
6709         $paragraph = '';
6710       }
6711
6712     return @res;
6713 }
6714
6715
6716
6717 # ($COMMENT, $VARIABLES, $RULES)
6718 # &file_contents_internal ($IS_AM, $FILE, $WHERE, [%TRANSFORM])
6719 # -------------------------------------------------------------
6720 # Return contents of a file from $libdir/am, automatically skipping
6721 # macros or rules which are already known. $IS_AM iff the caller is
6722 # reading an Automake file (as opposed to the user's Makefile.am).
6723 sub file_contents_internal ($$$%)
6724 {
6725     my ($is_am, $file, $where, %transform) = @_;
6726
6727     $where->set ($file);
6728
6729     my $result_vars = '';
6730     my $result_rules = '';
6731     my $comment = '';
6732     my $spacing = '';
6733
6734     # The following flags are used to track rules spanning across
6735     # multiple paragraphs.
6736     my $is_rule = 0;            # 1 if we are processing a rule.
6737     my $discard_rule = 0;       # 1 if the current rule should not be output.
6738
6739     # We save the conditional stack on entry, and then check to make
6740     # sure it is the same on exit.  This lets us conditonally include
6741     # other files.
6742     my @saved_cond_stack = @cond_stack;
6743     my $cond = new Automake::Condition (@cond_stack);
6744
6745     foreach (make_paragraphs ($file, %transform))
6746     {
6747         # FIXME: no line number available.
6748         $where->set ($file);
6749
6750         # Sanity checks.
6751         error $where, "blank line following trailing backslash:\n$_"
6752           if /\\$/;
6753         error $where, "comment following trailing backslash:\n$_"
6754           if /\\#/;
6755
6756         if (/^$/)
6757         {
6758             $is_rule = 0;
6759             # Stick empty line before the incoming macro or rule.
6760             $spacing = "\n";
6761         }
6762         elsif (/$COMMENT_PATTERN/mso)
6763         {
6764             $is_rule = 0;
6765             # Stick comments before the incoming macro or rule.
6766             $comment = "$_\n";
6767         }
6768
6769         # Handle inclusion of other files.
6770         elsif (/$INCLUDE_PATTERN/o)
6771         {
6772             if ($cond != FALSE)
6773               {
6774                 my $file = ($is_am ? "$libdir/am/" : '') . $1;
6775                 $where->push_context ("`$file' included from here");
6776                 # N-ary `.=' fails.
6777                 my ($com, $vars, $rules)
6778                   = file_contents_internal ($is_am, $file, $where, %transform);
6779                 $where->pop_context;
6780                 $comment .= $com;
6781                 $result_vars .= $vars;
6782                 $result_rules .= $rules;
6783               }
6784         }
6785
6786         # Handling the conditionals.
6787         elsif (/$IF_PATTERN/o)
6788           {
6789             $cond = cond_stack_if ($1, $2, $file);
6790           }
6791         elsif (/$ELSE_PATTERN/o)
6792           {
6793             $cond = cond_stack_else ($1, $2, $file);
6794           }
6795         elsif (/$ENDIF_PATTERN/o)
6796           {
6797             $cond = cond_stack_endif ($1, $2, $file);
6798           }
6799
6800         # Handling rules.
6801         elsif (/$RULE_PATTERN/mso)
6802         {
6803           $is_rule = 1;
6804           $discard_rule = 0;
6805           # Separate relationship from optional actions: the first
6806           # `new-line tab" not preceded by backslash (continuation
6807           # line).
6808           my $paragraph = $_;
6809           /^(.*?)(?:(?<!\\)\n(\t.*))?$/s;
6810           my ($relationship, $actions) = ($1, $2 || '');
6811
6812           # Separate targets from dependencies: the first colon.
6813           $relationship =~ /^([^:]+\S+) *: *(.*)$/som;
6814           my ($targets, $dependencies) = ($1, $2);
6815           # Remove the escaped new lines.
6816           # I don't know why, but I have to use a tmp $flat_deps.
6817           my $flat_deps = &flatten ($dependencies);
6818           my @deps = split (' ', $flat_deps);
6819
6820           foreach (split (' ' , $targets))
6821             {
6822               # FIXME: 1. We are not robust to people defining several targets
6823               # at once, only some of them being in %dependencies.  The
6824               # actions from the targets in %dependencies are usually generated
6825               # from the content of %actions, but if some targets in $targets
6826               # are not in %dependencies the ELSE branch will output
6827               # a rule for all $targets (i.e. the targets which are both
6828               # in %dependencies and $targets will have two rules).
6829
6830               # FIXME: 2. The logic here is not able to output a
6831               # multi-paragraph rule several time (e.g. for each condition
6832               # it is defined for) because it only knows the first paragraph.
6833
6834               # FIXME: 3. We are not robust to people defining a subset
6835               # of a previously defined "multiple-target" rule.  E.g.
6836               # `foo:' after `foo bar:'.
6837
6838               # Output only if not in FALSE.
6839               if (defined $dependencies{$_} && $cond != FALSE)
6840                 {
6841                   &depend ($_, @deps);
6842                   $actions{$_} .= $actions;
6843                 }
6844               else
6845                 {
6846                   # Free-lance dependency.  Output the rule for all the
6847                   # targets instead of one by one.
6848                   my @undefined_conds =
6849                     rule_define ($targets, $file,
6850                                  $is_am ? TARGET_AUTOMAKE : TARGET_USER,
6851                                  $cond, $where);
6852                   for my $undefined_cond (@undefined_conds)
6853                     {
6854                       my $condparagraph = $paragraph;
6855                       $condparagraph =~ s/^/$undefined_cond->subst_string/gme;
6856                       $result_rules .= "$spacing$comment$condparagraph\n";
6857                     }
6858                   if (scalar @undefined_conds == 0)
6859                     {
6860                       # Remember to discard next paragraphs
6861                       # if they belong to this rule.
6862                       # (but see also FIXME: #2 above.)
6863                       $discard_rule = 1;
6864                     }
6865                   $comment = $spacing = '';
6866                   last;
6867                 }
6868             }
6869         }
6870
6871         elsif (/$ASSIGNMENT_PATTERN/mso)
6872         {
6873             my ($var, $type, $val) = ($1, $2, $3);
6874             error $where, "variable `$var' with trailing backslash"
6875               if /\\$/;
6876
6877             $is_rule = 0;
6878
6879             Automake::Variable::define ($var,
6880                                         $is_am ? VAR_AUTOMAKE : VAR_MAKEFILE,
6881                                         $type, $cond, $val, $comment, $where,
6882                                         VAR_ASIS)
6883               if $cond != FALSE;
6884
6885             $comment = $spacing = '';
6886         }
6887         else
6888         {
6889             # This isn't an error; it is probably some tokens which
6890             # configure is supposed to replace, such as `@SET-MAKE@',
6891             # or some part of a rule cut by an if/endif.
6892             if (! $cond->false && ! ($is_rule && $discard_rule))
6893               {
6894                 s/^/$cond->subst_string/gme;
6895                 $result_rules .= "$spacing$comment$_\n";
6896               }
6897             $comment = $spacing = '';
6898         }
6899     }
6900
6901     error ($where, @cond_stack ?
6902            "unterminated conditionals: @cond_stack" :
6903            "too many conditionals closed in include file")
6904       if "@saved_cond_stack" ne "@cond_stack";
6905
6906     return ($comment, $result_vars, $result_rules);
6907 }
6908
6909
6910 # $CONTENTS
6911 # &file_contents ($BASENAME, $WHERE, [%TRANSFORM])
6912 # ------------------------------------------------
6913 # Return contents of a file from $libdir/am, automatically skipping
6914 # macros or rules which are already known.
6915 sub file_contents ($$%)
6916 {
6917     my ($basename, $where, %transform) = @_;
6918     my ($comments, $variables, $rules) =
6919       file_contents_internal (1, "$libdir/am/$basename.am", $where,
6920                               %transform);
6921     return "$comments$variables$rules";
6922 }
6923
6924
6925 # $REGEXP
6926 # &transform (%PAIRS)
6927 # -------------------
6928 # For each ($TOKEN, $VAL) in %PAIRS produce a replacement expression
6929 # suitable for file_contents which:
6930 #   - replaces %$TOKEN% with $VAL,
6931 #   - enables/disables ?$TOKEN? and ?!$TOKEN?,
6932 #   - replaces %?$TOKEN% with TRUE or FALSE.
6933 sub transform (%)
6934 {
6935     my (%pairs) = @_;
6936     my $result = '';
6937
6938     while (my ($token, $val) = each %pairs)
6939     {
6940         $result .= "s/\Q%$token%\E/\Q$val\E/gm;";
6941         if ($val)
6942         {
6943             $result .= "s/\Q?$token?\E//gm;s/^.*\Q?!$token?\E.*\\n//gm;";
6944             $result .= "s/\Q%?$token%\E/TRUE/gm;";
6945         }
6946         else
6947         {
6948             $result .= "s/\Q?!$token?\E//gm;s/^.*\Q?$token?\E.*\\n//gm;";
6949             $result .= "s/\Q%?$token%\E/FALSE/gm;";
6950         }
6951     }
6952
6953     return $result;
6954 }
6955
6956
6957 # &append_exeext ($MACRO)
6958 # -----------------------
6959 # Macro is an Automake magic macro which primary is PROGRAMS, e.g.
6960 # bin_PROGRAMS.  Make sure these programs have $(EXEEXT) appended.
6961 sub append_exeext ($)
6962 {
6963   my ($macro) = @_;
6964
6965   prog_error "append_exeext ($macro)"
6966     unless $macro =~ /_PROGRAMS$/;
6967
6968   transform_variable_recursively
6969     ($macro, $macro, 'am__EXEEXT', 0, INTERNAL,
6970      sub {
6971        my ($subvar, $val, $cond, $full_cond) = @_;
6972        # Append $(EXEEXT) unless the user did it already.
6973        $val .= '$(EXEEXT)' unless $val =~ /\$\(EXEEXT\)$/;
6974        return $val;
6975      });
6976 }
6977
6978
6979 # @PREFIX
6980 # &am_primary_prefixes ($PRIMARY, $CAN_DIST, @PREFIXES)
6981 # -----------------------------------------------------
6982 # Find all variable prefixes that are used for install directories.  A
6983 # prefix `zar' qualifies iff:
6984 #
6985 # * `zardir' is a variable.
6986 # * `zar_PRIMARY' is a variable.
6987 #
6988 # As a side effect, it looks for misspellings.  It is an error to have
6989 # a variable ending in a "reserved" suffix whose prefix is unknown, e.g.
6990 # "bin_PROGRAMS".  However, unusual prefixes are allowed if a variable
6991 # of the same name (with "dir" appended) exists.  For instance, if the
6992 # variable "zardir" is defined, then "zar_PROGRAMS" becomes valid.
6993 # This is to provide a little extra flexibility in those cases which
6994 # need it.
6995 sub am_primary_prefixes ($$@)
6996 {
6997   my ($primary, $can_dist, @prefixes) = @_;
6998
6999   local $_;
7000   my %valid = map { $_ => 0 } @prefixes;
7001   $valid{'EXTRA'} = 0;
7002   foreach my $varname (variables)
7003     {
7004       my $var = var $varname;
7005       # Automake is allowed to define variables that look like primaries
7006       # but which aren't.  E.g. INSTALL_sh_DATA.
7007       # Autoconf can also define variables like INSTALL_DATA, so
7008       # ignore all configure variables (at least those which are not
7009       # redefined in Makefile.am).
7010       # FIXME: We should make sure that these variables are not
7011       # conditionally defined (or else adjust the condition below).
7012       if ($var)
7013         {
7014           my $def = $var->def (TRUE);
7015           next if $def && $def->owner != VAR_MAKEFILE;
7016         }
7017
7018       if ($varname =~ /^(nobase_)?(dist_|nodist_)?(.*)_$primary$/)
7019         {
7020           my ($base, $dist, $X) = ($1 || '', $2 || '', $3 || '');
7021           if ($dist ne '' && ! $can_dist)
7022             {
7023               err_var ($var,
7024                        "invalid variable `$varname': `dist' is forbidden");
7025             }
7026           # Standard directories must be explicitely allowed.
7027           elsif (! defined $valid{$X} && exists $standard_prefix{$X})
7028             {
7029               err_var ($var,
7030                        "`${X}dir' is not a legitimate directory " .
7031                        "for `$primary'");
7032             }
7033           # A not explicitely valid directory is allowed if Xdir is defined.
7034           elsif (! defined $valid{$X} &&
7035                  require_variables_for_variable ($varname,
7036                                                  "`$varname' is used",
7037                                                  "${X}dir"))
7038             {
7039               # Nothing to do.  Any error message has been output
7040               # by require_variables_for_variable.
7041             }
7042           else
7043             {
7044               # Ensure all extended prefixes are actually used.
7045               $valid{"$base$dist$X"} = 1;
7046             }
7047         }
7048     }
7049
7050   # Return only those which are actually defined.
7051   return sort grep { variable_defined ($_ . '_' . $primary) } keys %valid;
7052 }
7053
7054
7055 # Handle `where_HOW' variable magic.  Does all lookups, generates
7056 # install code, and possibly generates code to define the primary
7057 # variable.  The first argument is the name of the .am file to munge,
7058 # the second argument is the primary variable (e.g. HEADERS), and all
7059 # subsequent arguments are possible installation locations.
7060 #
7061 # Returns list of [$location, $value] pairs, where
7062 # $value's are the values in all where_HOW variable, and $location
7063 # there associated location (the place here their parent variables were
7064 # defined).
7065 #
7066 # FIXME: this should be rewritten to be cleaner.  It should be broken
7067 # up into multiple functions.
7068 #
7069 # Usage is: am_install_var (OPTION..., file, HOW, where...)
7070 sub am_install_var
7071 {
7072   my (@args) = @_;
7073
7074   my $do_require = 1;
7075   my $can_dist = 0;
7076   my $default_dist = 0;
7077   while (@args)
7078     {
7079       if ($args[0] eq '-noextra')
7080         {
7081           $do_require = 0;
7082         }
7083       elsif ($args[0] eq '-candist')
7084         {
7085           $can_dist = 1;
7086         }
7087       elsif ($args[0] eq '-defaultdist')
7088         {
7089           $default_dist = 1;
7090           $can_dist = 1;
7091         }
7092       elsif ($args[0] !~ /^-/)
7093         {
7094           last;
7095         }
7096       shift (@args);
7097     }
7098
7099   my ($file, $primary, @prefix) = @args;
7100
7101   # Now that configure substitutions are allowed in where_HOW
7102   # variables, it is an error to actually define the primary.  We
7103   # allow `JAVA', as it is customarily used to mean the Java
7104   # interpreter.  This is but one of several Java hacks.  Similarly,
7105   # `PYTHON' is customarily used to mean the Python interpreter.
7106   reject_var $primary, "`$primary' is an anachronism"
7107     unless $primary eq 'JAVA' || $primary eq 'PYTHON';
7108
7109   # Get the prefixes which are valid and actually used.
7110   @prefix = am_primary_prefixes ($primary, $can_dist, @prefix);
7111
7112   # If a primary includes a configure substitution, then the EXTRA_
7113   # form is required.  Otherwise we can't properly do our job.
7114   my $require_extra;
7115
7116   my @used = ();
7117   my @result = ();
7118
7119   # True if the iteration is the first one.  Used for instance to
7120   # output parts of the associated file only once.
7121   my $first = 1;
7122   foreach my $X (@prefix)
7123     {
7124       my $nodir_name = $X;
7125       my $one_name = $X . '_' . $primary;
7126       my $one_var = var $one_name;
7127
7128       my $strip_subdir = 1;
7129       # If subdir prefix should be preserved, do so.
7130       if ($nodir_name =~ /^nobase_/)
7131         {
7132           $strip_subdir = 0;
7133           $nodir_name =~ s/^nobase_//;
7134         }
7135
7136       # If files should be distributed, do so.
7137       my $dist_p = 0;
7138       if ($can_dist)
7139         {
7140           $dist_p = (($default_dist && $nodir_name !~ /^nodist_/)
7141                      || (! $default_dist && $nodir_name =~ /^dist_/));
7142           $nodir_name =~ s/^(dist|nodist)_//;
7143         }
7144
7145
7146       # Use the location of the currently processed variable.
7147       # We are not processing a particular condition, so pick the first
7148       # available.
7149       my $tmpcond = $one_var->conditions->one_cond;
7150       my $where = $one_var->rdef ($tmpcond)->location->clone;
7151
7152       # Append actual contents of where_PRIMARY variable to
7153       # @result, skipping @substitutions@.
7154       foreach my $locvals (&variable_loc_and_value_as_list_recursive
7155                            ($one_name, 'all'))
7156         {
7157           my ($loc, $value) = @$locvals;
7158           # Skip configure substitutions.
7159           if ($value =~ /^\@.*\@$/)
7160             {
7161               if ($nodir_name eq 'EXTRA')
7162                 {
7163                   error ($where,
7164                          "`$one_name' contains configure substitution, "
7165                          . "but shouldn't");
7166                 }
7167               # Check here to make sure variables defined in
7168               # configure.ac do not imply that EXTRA_PRIMARY
7169               # must be defined.
7170               elsif (! defined $configure_vars{$one_name})
7171                 {
7172                   $require_extra = $one_name
7173                     if $do_require;
7174                 }
7175             }
7176           else
7177             {
7178               push (@result, $locvals);
7179             }
7180         }
7181       # A blatant hack: we rewrite each _PROGRAMS primary to include
7182       # EXEEXT.
7183       append_exeext ($one_name)
7184         if $primary eq 'PROGRAMS';
7185       # "EXTRA" shouldn't be used when generating clean targets,
7186       # all, or install targets.  We used to warn if EXTRA_FOO was
7187       # defined uselessly, but this was annoying.
7188       next
7189         if $nodir_name eq 'EXTRA';
7190
7191       if ($nodir_name eq 'check')
7192         {
7193           push (@check, '$(' . $one_name . ')');
7194         }
7195       else
7196         {
7197           push (@used, '$(' . $one_name . ')');
7198         }
7199
7200       # Is this to be installed?
7201       my $install_p = $nodir_name ne 'noinst' && $nodir_name ne 'check';
7202
7203       # If so, with install-exec? (or install-data?).
7204       my $exec_p = ($nodir_name =~ /$EXEC_DIR_PATTERN/o);
7205
7206       my $check_options_p = $install_p
7207         && defined $options{'std-options'};
7208
7209       # Use the location of the currently processed variable as context.
7210       $where->push_context ("while processing `$one_name'");
7211
7212       # Singular form of $PRIMARY.
7213       (my $one_primary = $primary) =~ s/S$//;
7214       $output_rules .= &file_contents ($file, $where,
7215                                          FIRST => $first,
7216
7217                                          PRIMARY     => $primary,
7218                                          ONE_PRIMARY => $one_primary,
7219                                          DIR         => $X,
7220                                          NDIR        => $nodir_name,
7221                                          BASE        => $strip_subdir,
7222
7223                                          EXEC      => $exec_p,
7224                                          INSTALL   => $install_p,
7225                                          DIST      => $dist_p,
7226                                          'CK-OPTS' => $check_options_p);
7227
7228       $first = 0;
7229     }
7230
7231   # The JAVA variable is used as the name of the Java interpreter.
7232   # The PYTHON variable is used as the name of the Python interpreter.
7233   if (@used && $primary ne 'JAVA' && $primary ne 'PYTHON')
7234     {
7235       # Define it.
7236       define_pretty_variable ($primary, TRUE, INTERNAL, @used);
7237       $output_vars .= "\n";
7238     }
7239
7240   err_var ($require_extra,
7241            "`$require_extra' contains configure substitution,\n"
7242            . "but `EXTRA_$primary' not defined")
7243     if ($require_extra && ! variable_defined ('EXTRA_' . $primary));
7244
7245   # Push here because PRIMARY might be configure time determined.
7246   push (@all, '$(' . $primary . ')')
7247     if @used && $primary ne 'JAVA' && $primary ne 'PYTHON';
7248
7249   # Make the result unique.  This lets the user use conditionals in
7250   # a natural way, but still lets us program lazily -- we don't have
7251   # to worry about handling a particular object more than once.
7252   # We will keep only one location per object.
7253   my %result = ();
7254   for my $pair (@result)
7255     {
7256       my ($loc, $val) = @$pair;
7257       $result{$val} = $loc;
7258     }
7259   my @l = sort keys %result;
7260   return map { [$result{$_}->clone, $_] } @l;
7261 }
7262
7263
7264 ################################################################
7265
7266 # Each key in this hash is the name of a directory holding a
7267 # Makefile.in.  These variables are local to `is_make_dir'.
7268 my %make_dirs = ();
7269 my $make_dirs_set = 0;
7270
7271 sub is_make_dir
7272 {
7273     my ($dir) = @_;
7274     if (! $make_dirs_set)
7275     {
7276         foreach my $iter (@configure_input_files)
7277         {
7278             $make_dirs{dirname ($iter)} = 1;
7279         }
7280         # We also want to notice Makefile.in's.
7281         foreach my $iter (@other_input_files)
7282         {
7283             if ($iter =~ /Makefile\.in$/)
7284             {
7285                 $make_dirs{dirname ($iter)} = 1;
7286             }
7287         }
7288         $make_dirs_set = 1;
7289     }
7290     return defined $make_dirs{$dir};
7291 }
7292
7293 ################################################################
7294
7295 # This variable is local to the "require file" set of functions.
7296 my @require_file_paths = ();
7297
7298
7299 # &maybe_push_required_file ($DIR, $FILE, $FULLFILE)
7300 # --------------------------------------------------
7301 # See if we want to push this file onto dist_common.  This function
7302 # encodes the rules for deciding when to do so.
7303 sub maybe_push_required_file
7304 {
7305     my ($dir, $file, $fullfile) = @_;
7306
7307     if ($dir eq $relative_dir)
7308     {
7309         push_dist_common ($file);
7310         return 1;
7311     }
7312     elsif ($relative_dir eq '.' && ! &is_make_dir ($dir))
7313     {
7314         # If we are doing the topmost directory, and the file is in a
7315         # subdir which does not have a Makefile, then we distribute it
7316         # here.
7317         push_dist_common ($fullfile);
7318         return 1;
7319     }
7320     return 0;
7321 }
7322
7323
7324 # &require_file_internal ($WHERE, $MYSTRICT, @FILES)
7325 # --------------------------------------------------
7326 # Verify that the file must exist in the current directory.
7327 # $MYSTRICT is the strictness level at which this file becomes required.
7328 #
7329 # Must set require_file_paths before calling this function.
7330 # require_file_paths is set to hold a single directory (the one in
7331 # which the first file was found) before return.
7332 sub require_file_internal ($$@)
7333 {
7334     my ($where, $mystrict, @files) = @_;
7335
7336     foreach my $file (@files)
7337     {
7338         my $fullfile;
7339         my $errdir;
7340         my $errfile;
7341         my $save_dir;
7342
7343         my $found_it = 0;
7344         my $dangling_sym = 0;
7345         foreach my $dir (@require_file_paths)
7346         {
7347             $fullfile = $dir . "/" . $file;
7348             $errdir = $dir unless $errdir;
7349
7350             # Use different name for "error filename".  Otherwise on
7351             # an error the bad file will be reported as e.g.
7352             # `../../install-sh' when using the default
7353             # config_aux_path.
7354             $errfile = $errdir . '/' . $file;
7355
7356             if (-l $fullfile && ! -f $fullfile)
7357             {
7358                 $dangling_sym = 1;
7359                 last;
7360             }
7361             elsif (-f $fullfile)
7362             {
7363                 $found_it = 1;
7364                 maybe_push_required_file ($dir, $file, $fullfile);
7365                 $save_dir = $dir;
7366                 last;
7367             }
7368         }
7369
7370         # `--force-missing' only has an effect if `--add-missing' is
7371         # specified.
7372         if ($found_it && (! $add_missing || ! $force_missing))
7373         {
7374             # Prune the path list.
7375             @require_file_paths = $save_dir;
7376         }
7377         else
7378         {
7379             # If we've already looked for it, we're done.  You might
7380             # wonder why we don't do this before searching for the
7381             # file.  If we do that, then something like
7382             # AC_OUTPUT(subdir/foo foo) will fail to put foo.in into
7383             # DIST_COMMON.
7384             if (! $found_it)
7385             {
7386                 next if defined $require_file_found{$fullfile};
7387                 $require_file_found{$fullfile} = 1;
7388             }
7389
7390             if ($strictness >= $mystrict)
7391             {
7392                 if ($dangling_sym && $add_missing)
7393                 {
7394                     unlink ($fullfile);
7395                 }
7396
7397                 my $trailer = '';
7398                 my $suppress = 0;
7399
7400                 # Only install missing files according to our desired
7401                 # strictness level.
7402                 my $message = "required file `$errfile' not found";
7403                 if ($add_missing)
7404                 {
7405                     if (-f ("$libdir/$file"))
7406                     {
7407                         $suppress = 1;
7408
7409                         # Install the missing file.  Symlink if we
7410                         # can, copy if we must.  Note: delete the file
7411                         # first, in case it is a dangling symlink.
7412                         $message = "installing `$errfile'";
7413                         # Windows Perl will hang if we try to delete a
7414                         # file that doesn't exist.
7415                         unlink ($errfile) if -f $errfile;
7416                         if ($symlink_exists && ! $copy_missing)
7417                         {
7418                             if (! symlink ("$libdir/$file", $errfile))
7419                             {
7420                                 $suppress = 0;
7421                                 $trailer = "; error while making link: $!";
7422                             }
7423                         }
7424                         elsif (system ('cp', "$libdir/$file", $errfile))
7425                         {
7426                             $suppress = 0;
7427                             $trailer = "\n    error while copying";
7428                         }
7429                     }
7430
7431                     if (! maybe_push_required_file (dirname ($errfile),
7432                                                     $file, $errfile))
7433                     {
7434                         if (! $found_it)
7435                         {
7436                             # We have added the file but could not push it
7437                             # into DIST_COMMON (probably because this is
7438                             # an auxiliary file and we are not processing
7439                             # the top level Makefile). This is unfortunate,
7440                             # since it means we are using a file which is not
7441                             # distributed!
7442
7443                             # Get Automake to be run again: on the second
7444                             # run the file will be found, and pushed into
7445                             # the toplevel DIST_COMMON automatically.
7446                             $automake_needs_to_reprocess_all_files = 1;
7447                         }
7448                     }
7449
7450                     # Prune the path list.
7451                     @require_file_paths = &dirname ($errfile);
7452                 }
7453
7454                 # If --force-missing was specified, and we have
7455                 # actually found the file, then do nothing.
7456                 next
7457                     if $found_it && $force_missing;
7458
7459                 # If we couldn' install the file, but it is a target in
7460                 # the Makefile, don't print anything.  This allows files
7461                 # like README, AUTHORS, or THANKS to be generated.
7462                 next
7463                   if !$suppress && target_defined ($file);
7464
7465                 msg ($suppress ? 'note' : 'error', $where, "$message$trailer");
7466             }
7467         }
7468     }
7469 }
7470
7471 # &require_file ($WHERE, $MYSTRICT, @FILES)
7472 # -----------------------------------------
7473 sub require_file ($$@)
7474 {
7475     my ($where, $mystrict, @files) = @_;
7476     @require_file_paths = $relative_dir;
7477     require_file_internal ($where, $mystrict, @files);
7478 }
7479
7480 # &require_file_with_macro ($COND, $MACRO, $MYSTRICT, @FILES)
7481 # -----------------------------------------------------------
7482 sub require_file_with_macro ($$$@)
7483 {
7484     my ($cond, $macro, $mystrict, @files) = @_;
7485     require_file (rvar ($macro)->rdef ($cond)->location, $mystrict, @files);
7486 }
7487
7488
7489 # &require_conf_file ($WHERE, $MYSTRICT, @FILES)
7490 # ----------------------------------------------
7491 # Looks in configuration path, as specified by AC_CONFIG_AUX_DIR.
7492 sub require_conf_file ($$@)
7493 {
7494     my ($where, $mystrict, @files) = @_;
7495     @require_file_paths = @config_aux_path;
7496     require_file_internal ($where, $mystrict, @files);
7497     my $dir = $require_file_paths[0];
7498     @config_aux_path = @require_file_paths;
7499      # Avoid unsightly '/.'s.
7500     $config_aux_dir = '$(top_srcdir)' . ($dir eq '.' ? "" : "/$dir");
7501 }
7502
7503
7504 # &require_conf_file_with_macro ($COND, $MACRO, $MYSTRICT, @FILES)
7505 # ----------------------------------------------------------------
7506 sub require_conf_file_with_macro ($$$@)
7507 {
7508     my ($cond, $macro, $mystrict, @files) = @_;
7509     require_conf_file (rvar ($macro)->rdef ($cond)->location,
7510                        $mystrict, @files);
7511 }
7512
7513 ################################################################
7514
7515 # &require_build_directory ($DIRECTORY)
7516 # ------------------------------------
7517 # Emit rules to create $DIRECTORY if needed, and return
7518 # the file that any target requiring this directory should be made
7519 # dependent upon.
7520 sub require_build_directory ($)
7521 {
7522   my $directory = shift;
7523   my $dirstamp = "$directory/\$(am__dirstamp)";
7524
7525   # Don't emit the rule twice.
7526   if (! defined $directory_map{$directory})
7527     {
7528       $directory_map{$directory} = 1;
7529
7530       # Set a variable for the dirstamp basename.
7531       define_pretty_variable ('am__dirstamp', TRUE, INTERNAL,
7532                               '$(am__leading_dot)dirstamp')
7533         unless variable_defined ('am__dirstamp');
7534
7535       # Directory must be removed by `make distclean'.
7536       $clean_files{$dirstamp} = DIST_CLEAN;
7537
7538       $output_rules .= ("$dirstamp:\n"
7539                         . "\t\@\$(mkinstalldirs) $directory\n"
7540                         . "\t\@: > $dirstamp\n");
7541     }
7542
7543   return $dirstamp;
7544 }
7545
7546 # &require_build_directory_maybe ($FILE)
7547 # --------------------------------------
7548 # If $FILE lies in a subdirectory, emit a rule to create this
7549 # directory and return the file that $FILE should be made
7550 # dependent upon.  Otherwise, just return the empty string.
7551 sub require_build_directory_maybe ($)
7552 {
7553     my $file = shift;
7554     my $directory = dirname ($file);
7555
7556     if ($directory ne '.')
7557     {
7558         return require_build_directory ($directory);
7559     }
7560     else
7561     {
7562         return '';
7563     }
7564 }
7565
7566 ################################################################
7567
7568 # Push a list of files onto dist_common.
7569 sub push_dist_common
7570 {
7571   prog_error "push_dist_common run after handle_dist"
7572     if $handle_dist_run;
7573   Automake::Variable::define ('DIST_COMMON', VAR_AUTOMAKE, '+', TRUE, "@_",
7574                               '', INTERNAL, VAR_PRETTY);
7575 }
7576
7577
7578 # Set strictness.
7579 sub set_strictness
7580 {
7581   $strictness_name = $_[0];
7582
7583   Automake::ChannelDefs::set_strictness ($strictness_name);
7584
7585   if ($strictness_name eq 'gnu')
7586     {
7587       $strictness = GNU;
7588     }
7589   elsif ($strictness_name eq 'gnits')
7590     {
7591       $strictness = GNITS;
7592     }
7593   elsif ($strictness_name eq 'foreign')
7594     {
7595       $strictness = FOREIGN;
7596     }
7597   else
7598     {
7599       prog_error "level `$strictness_name' not recognized\n";
7600     }
7601 }
7602
7603
7604 ################################################################
7605
7606 # Print usage information.
7607 sub usage ()
7608 {
7609     print "Usage: $0 [OPTION] ... [Makefile]...
7610
7611 Generate Makefile.in for configure from Makefile.am.
7612
7613 Operation modes:
7614       --help               print this help, then exit
7615       --version            print version number, then exit
7616   -v, --verbose            verbosely list files processed
7617       --no-force           only update Makefile.in's that are out of date
7618   -W, --warnings=CATEGORY  report the warnings falling in CATEGORY
7619
7620 Dependency tracking:
7621   -i, --ignore-deps      disable dependency tracking code
7622       --include-deps     enable dependency tracking code
7623
7624 Flavors:
7625       --cygnus           assume program is part of Cygnus-style tree
7626       --foreign          set strictness to foreign
7627       --gnits            set strictness to gnits
7628       --gnu              set strictness to gnu
7629
7630 Library files:
7631   -a, --add-missing      add missing standard files to package
7632       --libdir=DIR       directory storing library files
7633   -c, --copy             with -a, copy missing files (default is symlink)
7634   -f, --force-missing    force update of standard files
7635
7636 ";
7637     Automake::ChannelDefs::usage;
7638
7639     my ($last, @lcomm);
7640     $last = '';
7641     foreach my $iter (sort ((@common_files, @common_sometimes)))
7642     {
7643         push (@lcomm, $iter) unless $iter eq $last;
7644         $last = $iter;
7645     }
7646
7647     my @four;
7648     print "\nFiles which are automatically distributed, if found:\n";
7649     format USAGE_FORMAT =
7650   @<<<<<<<<<<<<<<<<   @<<<<<<<<<<<<<<<<   @<<<<<<<<<<<<<<<<   @<<<<<<<<<<<<<<<<
7651   $four[0],           $four[1],           $four[2],           $four[3]
7652 .
7653     $~ = "USAGE_FORMAT";
7654
7655     my $cols = 4;
7656     my $rows = int(@lcomm / $cols);
7657     my $rest = @lcomm % $cols;
7658
7659     if ($rest)
7660     {
7661         $rows++;
7662     }
7663     else
7664     {
7665         $rest = $cols;
7666     }
7667
7668     for (my $y = 0; $y < $rows; $y++)
7669     {
7670         @four = ("", "", "", "");
7671         for (my $x = 0; $x < $cols; $x++)
7672         {
7673             last if $y + 1 == $rows && $x == $rest;
7674
7675             my $idx = (($x > $rest)
7676                        ?  ($rows * $rest + ($rows - 1) * ($x - $rest))
7677                        : ($rows * $x));
7678
7679             $idx += $y;
7680             $four[$x] = $lcomm[$idx];
7681         }
7682         write;
7683     }
7684
7685     print "\nReport bugs to <bug-automake\@gnu.org>.\n";
7686
7687     # --help always returns 0 per GNU standards.
7688     exit 0;
7689 }
7690
7691
7692 # &version ()
7693 # -----------
7694 # Print version information
7695 sub version ()
7696 {
7697   print <<EOF;
7698 automake (GNU $PACKAGE) $VERSION
7699 Written by Tom Tromey <tromey\@redhat.com>.
7700
7701 Copyright 2003 Free Software Foundation, Inc.
7702 This is free software; see the source for copying conditions.  There is NO
7703 warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
7704 EOF
7705   # --version always returns 0 per GNU standards.
7706   exit 0;
7707 }
7708
7709 ################################################################
7710
7711 # Parse command line.
7712 sub parse_arguments ()
7713 {
7714   # Start off as gnu.
7715   &set_strictness ('gnu');
7716
7717   my %options =
7718     (
7719      'libdir:s'         => \$libdir,
7720      'gnu'              => sub { &set_strictness ('gnu'); },
7721      'gnits'            => sub { &set_strictness ('gnits'); },
7722      'cygnus'           => \$cygnus_mode,
7723      'foreign'          => sub { &set_strictness ('foreign'); },
7724      'include-deps'     => sub { $cmdline_use_dependencies = 1; },
7725      'i|ignore-deps'    => sub { $cmdline_use_dependencies = 0; },
7726      'no-force'         => sub { $force_generation = 0; },
7727      'f|force-missing'  => \$force_missing,
7728      'o|output-dir:s'   => \$output_directory,
7729      'a|add-missing'    => \$add_missing,
7730      'c|copy'           => \$copy_missing,
7731      'v|verbose'        => sub { setup_channel 'verb', silent => 0; },
7732      'W|warnings:s'     => \&parse_warnings,
7733      # These long options (--Werror and --Wno-error) for backward
7734      # compatibility.  Use -Werror and -Wno-error today.
7735      'Werror'           => sub { parse_warnings 'W', 'error'; },
7736      'Wno-error'        => sub { parse_warnings 'W', 'no-error'; },
7737      );
7738   use Getopt::Long;
7739   Getopt::Long::config ("bundling", "pass_through");
7740
7741   # See if --version or --help is used.  We want to process these before
7742   # anything else because the GNU Coding Standards require us to
7743   # `exit 0' after processing these options, and we can't garanty this
7744   # if we treat other options first.  (Handling other options first
7745   # could produce error diagnostics, and in this condition it is
7746   # confusing if Automake `exit 0'.)
7747   my %options_1st_pass =
7748     (
7749      'version' => \&version,
7750      'help'    => \&usage,
7751      # Recognize all other options (and their arguments) but do nothing.
7752      map { $_ => sub {} } (keys %options)
7753      );
7754   my @ARGV_backup = @ARGV;
7755   Getopt::Long::GetOptions %options_1st_pass
7756     or exit 1;
7757   @ARGV = @ARGV_backup;
7758
7759   # Now *really* process the options.  This time we know
7760   # that --help and --version are not present.
7761   Getopt::Long::GetOptions %options
7762     or exit 1;
7763
7764   if (defined $output_directory)
7765     {
7766       msg 'obsolete', "`--output-dir' is deprecated\n";
7767     }
7768   else
7769     {
7770       # In the next release we'll remove this entirely.
7771       $output_directory = '.';
7772     }
7773
7774   foreach my $arg (@ARGV)
7775     {
7776       if ($arg =~ /^-./)
7777         {
7778           fatal ("unrecognized option `$arg'\n"
7779                  . "Try `$0 --help' for more information.");
7780         }
7781
7782       # Handle $local:$input syntax.  Note that we only examine the
7783       # first ":" file to see if it is automake input; the rest are
7784       # just taken verbatim.  We still keep all the files around for
7785       # dependency checking, however.
7786       my ($local, $input, @rest) = split (/:/, $arg);
7787       if (! $input)
7788         {
7789           $input = $local;
7790         }
7791       else
7792         {
7793           # Strip .in; later on .am is tacked on.  That is how the
7794           # automake input file is found.  Maybe not the best way, but
7795           # it is easy to explain.
7796           $input =~ s/\.in$//
7797             or fatal "invalid input file name `$arg'\n.";
7798         }
7799       push (@input_files, $input);
7800       $output_files{$input} = join (':', ($local, @rest));
7801     }
7802
7803   # Take global strictness from whatever we currently have set.
7804   $default_strictness = $strictness;
7805   $default_strictness_name = $strictness_name;
7806 }
7807
7808 ################################################################
7809
7810 # Parse the WARNINGS environment variable.
7811 parse_WARNINGS;
7812
7813 # Parse command line.
7814 parse_arguments;
7815
7816 # Do configure.ac scan only once.
7817 scan_autoconf_files;
7818
7819 fatal "no `Makefile.am' found or specified\n"
7820   if ! @input_files;
7821
7822 my $automake_has_run = 0;
7823
7824 do
7825 {
7826   if ($automake_has_run)
7827     {
7828       verb 'processing Makefiles another time to fix them up.';
7829       prog_error 'running more than two times should never be needed.'
7830         if $automake_has_run >= 2;
7831     }
7832   $automake_needs_to_reprocess_all_files = 0;
7833
7834   # Now do all the work on each file.
7835   foreach my $file (@input_files)
7836     {
7837       $am_file = $file;
7838       if (! -f ($am_file . '.am'))
7839         {
7840           error "`$am_file.am' does not exist";
7841         }
7842       else
7843         {
7844           generate_makefile ($output_files{$am_file}, $am_file);
7845         }
7846     }
7847   ++$automake_has_run;
7848 }
7849 while ($automake_needs_to_reprocess_all_files);
7850
7851 exit $exit_code;
7852
7853
7854 ### Setup "GNU" style for perl-mode and cperl-mode.
7855 ## Local Variables:
7856 ## perl-indent-level: 2
7857 ## perl-continued-statement-offset: 2
7858 ## perl-continued-brace-offset: 0
7859 ## perl-brace-offset: 0
7860 ## perl-brace-imaginary-offset: 0
7861 ## perl-label-offset: -2
7862 ## cperl-indent-level: 2
7863 ## cperl-brace-offset: 0
7864 ## cperl-continued-brace-offset: 0
7865 ## cperl-label-offset: -2
7866 ## cperl-extra-newline-before-brace: t
7867 ## cperl-merge-trailing-else: nil
7868 ## cperl-continued-statement-offset: 2
7869 ## End: