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