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