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