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