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