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