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