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