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