* automake.in (handle_languages, handle_single_transform_list,
[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_conf_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_conf_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         # AMDEPBACKSLASH might be subst'd by `\', which certainly would
4779         # not be appreciated by Make.
4780         if (/$AC_SUBST_PATTERN/o
4781             && $1 ne 'ANSI2KNR'
4782             && $1 ne 'INSTALL_SCRIPT'
4783             && $1 ne 'INSTALL_DATA'
4784             && $1 ne 'AMDEPBACKSLASH')
4785         {
4786             $configure_vars{$1} = $filename . ':' . $.;
4787         }
4788
4789         $seen_decl_yytext = 1 if /AC_DECL_YYTEXT/;
4790         if (/AM_MAINTAINER_MODE/)
4791         {
4792             $seen_maint_mode = 1;
4793             $configure_cond{'MAINTAINER_MODE'} = 1;
4794         }
4795
4796         $seen_lispdir = 1 if /AM_PATH_LISPDIR/;
4797
4798         if (/AM_PATH_PYTHON/)
4799           {
4800             $seen_pythondir = 1;
4801             $configure_vars{'pythondir'} = $filename . ':' . $.;
4802             $configure_vars{'PYTHON'} = $filename . ':' . $.;
4803           }
4804
4805         if (/A(C|M)_PROG_LIBTOOL/)
4806         {
4807             # We're not ready for this yet.  People still use a
4808             # libtool with no AC_PROG_LIBTOOL.  Once that is the
4809             # dominant version we can reenable this code -- but next
4810             # time by mentioning the macro in %obsolete_macros, both
4811             # here and in aclocal.in.
4812
4813             # if (/AM_PROG_LIBTOOL/)
4814             # {
4815             #   &am_conf_line_warning ($filename, $., "`AM_PROG_LIBTOOL' is obsolete, use `AC_PROG_LIBTOOL' instead");
4816             # }
4817             $seen_libtool = 1;
4818             $libtool_line = $.;
4819             $configure_vars{'LIBTOOL'} = $filename . ':' . $.;
4820             $configure_vars{'RANLIB'} = $filename . ':' . $.;
4821             $configure_vars{'CC'} = $filename . ':' . $.;
4822             # AC_PROG_LIBTOOL runs AC_CANONICAL_HOST.  Make sure we
4823             # never downgrade (if we've seen AC_CANONICAL_SYSTEM).
4824             $seen_canonical = $AC_CANONICAL_HOST if ! $seen_canonical;
4825         }
4826
4827         $seen_multilib = 1 if (/AM_ENABLE_MULTILIB/);
4828
4829         if (/$AM_CONDITIONAL_PATTERN/o)
4830         {
4831             $configure_cond{$1} = 1;
4832         }
4833
4834         # Check for Fortran 77 intrinsic and run-time libraries.
4835         if (/AC_F77_LIBRARY_LDFLAGS/)
4836         {
4837             $configure_vars{'FLIBS'} = $filename . ':' . $.;
4838         }
4839     }
4840
4841     $configfh->close;
4842 }
4843
4844
4845 # &scan_autoconf_files ()
4846 # -----------------------
4847 # Check whether we use `configure.ac' or `configure.in'.
4848 # Scan it (and possibly `aclocal.m4') for interesting things.
4849 # We must scan aclocal.m4 because there might be AC_SUBSTs and such there.
4850 sub scan_autoconf_files
4851 {
4852     # Reinitialize libsources here.  This isn't really necessary,
4853     # since we currently assume there is only one configure.ac.  But
4854     # that won't always be the case.
4855     %libsources = ();
4856
4857     $configure_ac = find_configure_ac;
4858     die "$me: `configure.ac' or `configure.in' is required\n"
4859         if !$configure_ac;
4860
4861     &scan_one_autoconf_file ($configure_ac);
4862     &scan_one_autoconf_file ('aclocal.m4')
4863         if -f 'aclocal.m4';
4864
4865     if (defined $ENV{'amtraces'})
4866     {
4867         warn '$me: Autoconf traces is an experimental feature';
4868         warn '$me: use at your own risks';
4869
4870         &scan_autoconf_traces ($configure_ac);
4871     }
4872
4873     # Set input and output files if not specified by user.
4874     if (! @input_files)
4875     {
4876         @input_files = sort keys %make_list;
4877         %output_files = %make_list;
4878     }
4879
4880     @configure_input_files = sort keys %make_list;
4881
4882     &am_conf_error ("`AM_INIT_AUTOMAKE' must be used")
4883         if ! $seen_init_automake;
4884
4885     # Look for some files we need.  Always check for these.  This
4886     # check must be done for every run, even those where we are only
4887     # looking at a subdir Makefile.  We must set relative_dir so that
4888     # the file-finding machinery works.
4889     # FIXME: Is this broken because it needs dynamic scopes.
4890     # My tests seems to show it's not the case.
4891     $relative_dir = '.';
4892     &require_config_file ($FOREIGN, 'install-sh', 'mkinstalldirs', 'missing');
4893     &am_error ("`install.sh' is an anachronism; use `install-sh' instead")
4894         if -f $config_aux_path[0] . '/install.sh';
4895
4896     &require_config_file ($FOREIGN, 'py-compile')
4897         if $seen_pythondir;
4898
4899     # Preserve dist_common for later.
4900     $configure_dist_common = variable_value ('DIST_COMMON', 'TRUE') || '';
4901 }
4902
4903 ################################################################
4904
4905 # Set up for Cygnus mode.
4906 sub check_cygnus
4907 {
4908     return unless $cygnus_mode;
4909
4910     &set_strictness ('foreign');
4911     $options{'no-installinfo'} = 1;
4912     $options{'no-dependencies'} = 1;
4913     $use_dependencies = 0;
4914
4915     if (! $seen_maint_mode)
4916     {
4917         &am_conf_error ("`AM_MAINTAINER_MODE' required when --cygnus specified");
4918     }
4919 }
4920
4921 # Do any extra checking for GNU standards.
4922 sub check_gnu_standards
4923 {
4924     if ($relative_dir eq '.')
4925     {
4926         # In top level (or only) directory.
4927         &require_file ($GNU, 'INSTALL', 'NEWS', 'README', 'COPYING',
4928                        'AUTHORS', 'ChangeLog');
4929     }
4930
4931     if ($strictness >= $GNU
4932         && defined $options{'no-installman'})
4933     {
4934         &am_line_error ('AUTOMAKE_OPTIONS',
4935                         "option `no-installman' disallowed by GNU standards");
4936     }
4937
4938     if ($strictness >= $GNU
4939         && defined $options{'no-installinfo'})
4940     {
4941         &am_line_error ('AUTOMAKE_OPTIONS',
4942                         "option `no-installinfo' disallowed by GNU standards");
4943     }
4944 }
4945
4946 # Do any extra checking for GNITS standards.
4947 sub check_gnits_standards
4948 {
4949     if ($relative_dir eq '.')
4950     {
4951         # In top level (or only) directory.
4952         &require_file ($GNITS, 'THANKS');
4953     }
4954 }
4955
4956 ################################################################
4957 #
4958 # Functions to handle files of each language.
4959
4960 # Each `lang_X_rewrite($DIRECTORY, $BASE, $EXT)' function follows a
4961 # simple formula: Return value is $LANG_SUBDIR if the resulting object
4962 # file should be in a subdir if the source file is, $LANG_PROCESS if
4963 # file is to be dealt with, $LANG_IGNORE otherwise.
4964
4965 # Much of the actual processing is handled in
4966 # handle_single_transform_list.  These functions exist so that
4967 # auxiliary information can be recorded for a later cleanup pass.
4968 # Note that the calls to these functions are computed, so don't bother
4969 # searching for their precise names in the source.
4970
4971 # This is just a convenience function that can be used to determine
4972 # when a subdir object should be used.
4973 sub lang_sub_obj
4974 {
4975     return defined $options{'subdir-objects'} ? $LANG_SUBDIR : $LANG_PROCESS;
4976 }
4977
4978 # Rewrite a single C source file.
4979 sub lang_c_rewrite
4980 {
4981     my ($directory, $base, $ext) = @_;
4982
4983     if (defined $options{'ansi2knr'} && $base =~ /_$/)
4984     {
4985         # FIXME: include line number in error.
4986         &am_error ("C source file `$base.c' would be deleted by ansi2knr rules");
4987     }
4988
4989     my $r = $LANG_PROCESS;
4990     if (defined $options{'subdir-objects'})
4991     {
4992         $r = $LANG_SUBDIR;
4993         $base = $directory . '/' . $base;
4994
4995         if (! $seen_cc_c_o)
4996         {
4997             # Only give error once.
4998             $seen_cc_c_o = 1;
4999             # FIXME: line number.
5000             &am_error ("C objects in subdir but `AM_PROG_CC_C_O' not in `$configure_ac'");
5001         }
5002
5003         &require_conf_file ($FOREIGN, 'compile');
5004     }
5005
5006     $de_ansi_files{$base} = 1;
5007     return $r;
5008 }
5009
5010 # Rewrite a single C++ source file.
5011 sub lang_cxx_rewrite
5012 {
5013     return &lang_sub_obj;
5014 }
5015
5016 # Rewrite a single header file.
5017 sub lang_header_rewrite
5018 {
5019     # Header files are simply ignored.
5020     return $LANG_IGNORE;
5021 }
5022
5023 # Rewrite a single yacc file.
5024 sub lang_yacc_rewrite
5025 {
5026     my ($directory, $base, $ext) = @_;
5027
5028     my $r = &lang_sub_obj;
5029     (my $newext = $ext) =~ tr/y/c/;
5030     return ($r, $newext);
5031 }
5032
5033 # Rewrite a single yacc++ file.
5034 sub lang_yaccxx_rewrite
5035 {
5036     my ($directory, $base, $ext) = @_;
5037
5038     my $r = &lang_sub_obj;
5039     (my $newext = $ext) =~ tr/y/c/;
5040     return ($r, $newext);
5041 }
5042
5043 # Rewrite a single lex file.
5044 sub lang_lex_rewrite
5045 {
5046     my ($directory, $base, $ext) = @_;
5047
5048     my $r = &lang_sub_obj;
5049     (my $newext = $ext) =~ tr/l/c/;
5050     return ($r, $newext);
5051 }
5052
5053 # Rewrite a single lex++ file.
5054 sub lang_lexxx_rewrite
5055 {
5056     my ($directory, $base, $ext) = @_;
5057
5058     my $r = &lang_sub_obj;
5059     (my $newext = $ext) =~ tr/l/c/;
5060     return ($r, $newext);
5061 }
5062
5063 # Rewrite a single assembly file.
5064 sub lang_asm_rewrite
5065 {
5066     return &lang_sub_obj;
5067 }
5068
5069 # Rewrite a single Fortran 77 file.
5070 sub lang_f77_rewrite
5071 {
5072     return $LANG_PROCESS;
5073 }
5074
5075 # Rewrite a single preprocessed Fortran 77 file.
5076 sub lang_ppf77_rewrite
5077 {
5078     return $LANG_PROCESS;
5079 }
5080
5081 # Rewrite a single ratfor file.
5082 sub lang_ratfor_rewrite
5083 {
5084     return $LANG_PROCESS;
5085 }
5086
5087 # Rewrite a single Objective C file.
5088 sub lang_objc_rewrite
5089 {
5090     return &lang_sub_obj;
5091 }
5092
5093 # Rewrite a single Java file.
5094 sub lang_java_rewrite
5095 {
5096     return $LANG_SUBDIR;
5097 }
5098
5099 # The lang_X_finish functions are called after all source file
5100 # processing is done.  Each should handle defining rules for the
5101 # language, etc.  A finish function is only called if a source file of
5102 # the appropriate type has been seen.
5103
5104 sub lang_c_finish
5105 {
5106     # Push all libobjs files onto de_ansi_files.  We actually only
5107     # push files which exist in the current directory, and which are
5108     # genuine source files.
5109     foreach my $file (keys %libsources)
5110     {
5111         if ($file =~ /^(.*)\.[cly]$/ && -f "$relative_dir/$file")
5112         {
5113             $de_ansi_files{$1} = 1;
5114         }
5115     }
5116
5117     if (defined $options{'ansi2knr'} && keys %de_ansi_files)
5118     {
5119         # Make all _.c files depend on their corresponding .c files.
5120         my @objects;
5121         foreach my $base (sort keys %de_ansi_files)
5122         {
5123             # Each _.c file must depend on ansi2knr; otherwise it
5124             # might be used in a parallel build before it is built.
5125             # We need to support files in the srcdir and in the build
5126             # dir (because these files might be auto-generated.  But
5127             # we can't use $< -- some makes only define $< during a
5128             # suffix rule.
5129             $output_rules .= ($base . "_.c: $base.c \$(ANSI2KNR)\n\t"
5130                               . '$(CPP) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) '
5131                               . '`if test -f $(srcdir)/' . $base . '.c'
5132                               . '; then echo $(srcdir)/' . $base . '.c'
5133                               . '; else echo ' . $base . '.c; fi` '
5134                               . "| sed 's/^# \\([0-9]\\)/#line \\1/' "
5135                               . '| $(ANSI2KNR) > ' . $base . "_.c"
5136                               # If ansi2knr fails then we shouldn't
5137                               # create the _.c file
5138                               . " || rm -f ${base}_.c\n");
5139             push (@objects, $base . '_.$(OBJEXT)');
5140             push (@objects, $base . '_.lo')
5141               if $seen_libtool;
5142         }
5143
5144         # Make all _.o (and _.lo) files depend on ansi2knr.
5145         # Use a sneaky little hack to make it print nicely.
5146         &pretty_print_rule ('', '', @objects, ':', '$(ANSI2KNR)');
5147     }
5148 }
5149
5150 # This is a yacc helper which is called whenever we have decided to
5151 # compile a yacc file.
5152 sub lang_yacc_target_hook
5153 {
5154     my ($self, $aggregate, $output, $input) = @_;
5155
5156     my $flag = $aggregate . "_YFLAGS";
5157     if ((&variable_defined ($flag)
5158          && &variable_value ($flag) =~ /$DASH_D_PATTERN/o)
5159         || (&variable_defined ('YFLAGS')
5160             && &variable_value ('YFLAGS') =~ /$DASH_D_PATTERN/o))
5161     {
5162         (my $output_base = $output) =~ s/\..*$//;
5163         my $header = $output_base . '.h';
5164
5165         # Found a `-d' that applies to the compilation of this file.
5166         # Add a dependency for the generated header file, and arrange
5167         # for that file to be included in the distribution.
5168         # FIXME: this fails for `nodist_*_SOURCES'.
5169         $output_rules .= "${header}: $output\n";
5170         &push_dist_common ($header);
5171         # If the files are built in the build directory, then we want
5172         # to remove them with `make clean'.  If they are in srcdir
5173         # they shouldn't be touched.  However, we can't determine this
5174         # statically, and the GNU rules say that yacc/lex output files
5175         # should be removed by maintainer-clean.  So that's what we
5176         # do.
5177         push (@maintainer_clean_files, $header);
5178     }
5179 }
5180
5181 # This is a helper for both lex and yacc.
5182 sub yacc_lex_finish_helper
5183 {
5184     return if defined $language_scratch{'lex-yacc-done'};
5185     $language_scratch{'lex-yacc-done'} = 1;
5186
5187     # If there is more than one distinct yacc (resp lex) source file
5188     # in a given directory, then the `ylwrap' program is required to
5189     # allow parallel builds to work correctly.  FIXME: for now, no
5190     # line number.
5191     &require_config_file ($FOREIGN, 'ylwrap');
5192     if ($config_aux_dir_set_in_configure_in)
5193     {
5194         &define_variable ('YLWRAP', $config_aux_dir . "/ylwrap");
5195     }
5196     else
5197     {
5198         &define_variable ('YLWRAP', '$(top_srcdir)/ylwrap');
5199     }
5200 }
5201
5202 sub lang_yacc_finish
5203 {
5204     return if defined $language_scratch{'yacc-done'};
5205     $language_scratch{'yacc-done'} = 1;
5206
5207     if (&variable_defined ('YACCFLAGS'))
5208     {
5209         &am_line_error ('YACCFLAGS',
5210                         "`YACCFLAGS' obsolete; use `YFLAGS' instead");
5211     }
5212
5213     if (count_files_for_language ('yacc') > 1)
5214     {
5215         &yacc_lex_finish_helper;
5216     }
5217 }
5218
5219
5220 sub lang_lex_finish
5221 {
5222     return if defined $language_scratch{'lex-done'};
5223     $language_scratch{'lex-done'} = 1;
5224
5225     if (! $seen_decl_yytext)
5226     {
5227         &am_error ("lex source seen but `AC_DECL_YYTEXT' not in `$configure_ac'");
5228     }
5229
5230     if (count_files_for_language ('lex') > 1)
5231     {
5232         &yacc_lex_finish_helper;
5233     }
5234 }
5235
5236
5237 # Given a hash table of linker names, pick the name that has the most
5238 # precedence.  This is lame, but something has to have global
5239 # knowledge in order to eliminate the conflict.  Add more linkers as
5240 # required.
5241 sub resolve_linker
5242 {
5243     my (%linkers) = @_;
5244
5245     return 'GCJLINK'
5246         if defined $linkers{'GCJLINK'};
5247     return 'CXXLINK'
5248         if defined $linkers{'CXXLINK'};
5249     return 'F77LINK'
5250         if defined $linkers{'F77LINK'};
5251     return 'OBJCLINK'
5252         if defined $linkers{'OBJCLINK'};
5253     return 'LINK';
5254 }
5255
5256 # Called to indicate that an extension was used.
5257 sub saw_extension
5258 {
5259     my ($ext) = @_;
5260     if (! defined $extension_seen{$ext})
5261     {
5262         $extension_seen{$ext} = 1;
5263     }
5264     else
5265     {
5266         ++$extension_seen{$ext};
5267     }
5268 }
5269
5270 # Return the number of files seen for a given language.  Knows about
5271 # special cases we care about.  FIXME: this is hideous.  We need
5272 # something that involves real language objects.  For instance yacc
5273 # and yaccxx could both derive from a common yacc class which would
5274 # know about the strange ylwrap requirement.  (Or better yet we could
5275 # just not support legacy yacc!)
5276 sub count_files_for_language
5277 {
5278     my ($name) = @_;
5279
5280     my @names;
5281     if ($name eq 'yacc' || $name eq 'yaccxx')
5282     {
5283         @names = ('yacc', 'yaccxx');
5284     }
5285     elsif ($name eq 'lex' || $name eq 'lexxx')
5286     {
5287         @names = ('lex', 'lexxx');
5288     }
5289     else
5290     {
5291         @names = ($name);
5292     }
5293
5294     my $r = 0;
5295     foreach $name (@names)
5296     {
5297         my $lang = $languages{$name};
5298         foreach my $ext (@{$lang->extensions})
5299         {
5300             $r += $extension_seen{$ext}
5301                 if defined $extension_seen{$ext};
5302         }
5303     }
5304
5305     return $r
5306 }
5307
5308 # Called to ask whether source files have been seen . If HEADERS is 1,
5309 # headers can be included.
5310 sub saw_sources_p
5311 {
5312     my ($headers) = @_;
5313
5314     # count all the sources
5315     my $count = 0;
5316     foreach my $val (values %extension_seen)
5317     {
5318         $count += $val;
5319     }
5320
5321     if (!$headers)
5322     {
5323         $count -= count_files_for_language ('header');
5324     }
5325
5326     return $count > 0;
5327 }
5328
5329
5330 # register_language (%ATTRIBUTE)
5331 # ------------------------------
5332 # Register a single language.
5333 # Each %ATTRIBUTE is of the form ATTRIBUTE => VALUE.
5334 sub register_language (%)
5335 {
5336     my (%option) = @_;
5337
5338     # Set the defaults.
5339     $option{'ansi'} = 0
5340       unless defined $option{'ansi'};
5341     $option{'autodep'} = 'no'
5342       unless defined $option{'autodep'};
5343     $option{'linker'} = ''
5344       unless defined $option{'linker'};
5345     $option{'define_flag'} = 1
5346       unless defined $option{'define_flag'};
5347
5348     my $lang = new Language (%option);
5349
5350     # Fill indexes.
5351     grep ($extension_map{$_} = $lang->name, @{$lang->extensions});
5352     $languages{$lang->name} = $lang;
5353 }
5354
5355 # This function is used to find a path from a user-specified suffix to
5356 # `o' or to some other suffix we recognize internally, eg `cc'.
5357 sub derive_suffix
5358 {
5359     my ($source_ext) = @_;
5360
5361     # FIXME: hard-coding `o' is a mistake.  Doing something
5362     # intelligent is harder.
5363     while (! $extension_map{$source_ext}
5364            && $source_ext ne 'o'
5365            && defined $suffix_rules{$source_ext})
5366     {
5367         $source_ext = $suffix_rules{$source_ext};
5368     }
5369
5370     return $source_ext;
5371 }
5372
5373
5374 ################################################################
5375
5376 # Pretty-print something.  HEAD is what should be printed at the
5377 # beginning of the first line, FILL is what should be printed at the
5378 # beginning of every subsequent line.
5379 sub pretty_print_internal
5380 {
5381     my ($head, $fill, @values) = @_;
5382
5383     my $column = length ($head);
5384     my $result = $head;
5385
5386     # Fill length is number of characters.  However, each Tab
5387     # character counts for eight.  So we count the number of Tabs and
5388     # multiply by 7.
5389     my $fill_length = length ($fill);
5390     $fill_length += 7 * ($fill =~ tr/\t/\t/d);
5391
5392     foreach (@values)
5393     {
5394         # "71" because we also print a space.
5395         if ($column + length ($_) > 71)
5396         {
5397             $result .= " \\\n" . $fill;
5398             $column = $fill_length;
5399         }
5400         $result .= ' ' if $result =~ /\S\z/;
5401         $result .= $_;
5402         $column += length ($_) + 1;
5403     }
5404
5405     $result .= "\n";
5406     return $result;
5407 }
5408
5409 # Pretty-print something and append to output_vars.
5410 sub pretty_print
5411 {
5412     $output_vars .= &pretty_print_internal (@_);
5413 }
5414
5415 # Pretty-print something and append to output_rules.
5416 sub pretty_print_rule
5417 {
5418     $output_rules .= &pretty_print_internal (@_);
5419 }
5420
5421
5422 ################################################################
5423
5424
5425 # $STRING
5426 # &conditional_string(@COND-STACK)
5427 # --------------------------------
5428 # Build a string which denotes the conditional in @COND-STACK.  Some
5429 # simplifications are done: `TRUE' entries are elided, and any `FALSE'
5430 # entry results in a return of `FALSE'.
5431 sub conditional_string
5432 {
5433   my (@stack) = @_;
5434
5435   if (grep (/^FALSE$/, @stack))
5436     {
5437       return 'FALSE';
5438     }
5439   else
5440     {
5441       return join (' ', uniq sort grep (!/^TRUE$/, @stack));
5442     }
5443 }
5444
5445
5446 # $BOOLEAN
5447 # &conditional_true_when ($COND, $WHEN)
5448 # -------------------------------------
5449 # See if a conditional is true.  Both arguments are conditional
5450 # strings.  This returns true if the first conditional is true when
5451 # the second conditional is true.
5452 # For instance with $COND = `BAR FOO', and $WHEN = `BAR BAZ FOO',
5453 # obviously return 1, and 0 when, for instance, $WHEN = `FOO'.
5454 sub conditional_true_when ($$)
5455 {
5456     my ($cond, $when) = @_;
5457
5458     # Make a hash holding all the values from $WHEN.
5459     my %cond_vals = map { $_ => 1 } split (' ', $when);
5460
5461     # Check each component of $cond, which looks `COND1 COND2'.
5462     foreach my $comp (split (' ', $cond))
5463     {
5464         # TRUE is always true.
5465         next if $comp eq 'TRUE';
5466         return 0 if ! defined $cond_vals{$comp};
5467     }
5468
5469     return 1;
5470 }
5471
5472
5473 # $BOOLEAN
5474 # &conditional_is_redundant ($COND, @WHENS)
5475 # ----------------------------------------
5476 # Determine whether $COND is redundant with respect to @WHENS.
5477 #
5478 # Returns true if $COND is true for any of the conditions in @WHENS.
5479 #
5480 # If there are no @WHENS, then behave as if @WHENS contained a single empty
5481 # condition.
5482 sub conditional_is_redundant ($@)
5483 {
5484     my ($cond, @whens) = @_;
5485
5486     if (@whens == 0)
5487     {
5488         return 1 if conditional_true_when ($cond, "");
5489     }
5490     else
5491     {
5492         foreach my $when (@whens)
5493         {
5494             return 1 if conditional_true_when ($cond, $when);
5495         }
5496     }
5497
5498     return 0;
5499 }
5500
5501
5502 # $NEGATION
5503 # condition_negate ($COND)
5504 # ------------------------
5505 sub condition_negate ($)
5506 {
5507     my ($cond) = @_;
5508
5509     $cond =~ s/TRUE$/TRUEO/;
5510     $cond =~ s/FALSE$/TRUE/;
5511     $cond =~ s/TRUEO$/FALSE/;
5512
5513     return $cond;
5514 }
5515
5516
5517 # Compare condition names.
5518 # Issue them in alphabetical order, foo_TRUE before foo_FALSE.
5519 sub by_condition
5520 {
5521     # Be careful we might be comparing `' or `#'.
5522     $a =~ /^(.*)_(TRUE|FALSE)$/;
5523     my ($aname, $abool) = ($1 || '', $2 || '');
5524     $b =~ /^(.*)_(TRUE|FALSE)$/;
5525     my ($bname, $bbool) = ($1 || '', $2 || '');
5526     return ($aname cmp $bname
5527             # Don't bother with IFs, given that TRUE is after FALSE
5528             # just cmp in the reverse order.
5529             || $bbool cmp $abool
5530             # Just in case...
5531             || $a cmp $b);
5532 }
5533
5534
5535 # &make_condition (@CONDITIONS)
5536 # -----------------------------
5537 # Transform a list of conditions (themselves can be an internal list
5538 # of conditions, e.g., @CONDITIONS = ('cond1 cond2', 'cond3')) into a
5539 # Make conditional (a pattern for AC_SUBST).
5540 # Correctly returns the empty string when there are no conditions.
5541 sub make_condition
5542 {
5543     my $res = conditional_string (@_);
5544
5545     # There are no conditions.
5546     if ($res eq '')
5547       {
5548         # Nothing to do.
5549       }
5550     # It's impossible.
5551     elsif ($res eq 'FALSE')
5552       {
5553         $res = '#';
5554       }
5555     # Build it.
5556     else
5557       {
5558         $res = '@' . $res . '@';
5559         $res =~ s/ /@@/g;
5560       }
5561
5562     return $res;
5563 }
5564
5565
5566
5567 ## ------------------------------ ##
5568 ## Handling the condition stack.  ##
5569 ## ------------------------------ ##
5570
5571
5572 # $COND_STRING
5573 # cond_stack_if ($NEGATE, $COND, $WHERE)
5574 # --------------------------------------
5575 sub cond_stack_if ($$$)
5576 {
5577   my ($negate, $cond, $where) = @_;
5578
5579   &am_file_error ($where, "$cond does not appear in AM_CONDITIONAL")
5580     if ! $configure_cond{$cond} && $cond !~ /^TRUE|FALSE$/;
5581
5582   $cond = "${cond}_TRUE"
5583     unless $cond =~ /^TRUE|FALSE$/;
5584   $cond = condition_negate ($cond)
5585     if $negate;
5586
5587   push (@cond_stack, $cond);
5588
5589   return conditional_string (@cond_stack);
5590 }
5591
5592
5593 # $COND_STRING
5594 # cond_stack_else ($NEGATE, $COND, $WHERE)
5595 # ----------------------------------------
5596 sub cond_stack_else ($$$)
5597 {
5598   my ($negate, $cond, $where) = @_;
5599
5600   if (! @cond_stack)
5601     {
5602       &am_file_error ($where, "else without if");
5603       return;
5604     }
5605
5606   $cond_stack[$#cond_stack] = condition_negate ($cond_stack[$#cond_stack]);
5607
5608   # If $COND is given, check against it.
5609   if (defined $cond)
5610     {
5611       $cond = "${cond}_TRUE"
5612         unless $cond =~ /^TRUE|FALSE$/;
5613       $cond = condition_negate ($cond)
5614         if $negate;
5615
5616       &am_file_error ($where,
5617                       "else reminder ($negate$cond) incompatible with "
5618                       . "current conditional: $cond_stack[$#cond_stack]")
5619         if $cond_stack[$#cond_stack] ne $cond;
5620     }
5621
5622   return conditional_string (@cond_stack);
5623 }
5624
5625
5626 # $COND_STRING
5627 # cond_stack_endif ($NEGATE, $COND, $WHERE)
5628 # -----------------------------------------
5629 sub cond_stack_endif ($$$)
5630 {
5631   my ($negate, $cond, $where) = @_;
5632   my $old_cond;
5633
5634   if (! @cond_stack)
5635     {
5636       &am_file_error ($where, "endif without if: $negate$cond");
5637       return;
5638     }
5639
5640
5641   # If $COND is given, check against it.
5642   if (defined $cond)
5643     {
5644       $cond = "${cond}_TRUE"
5645         unless $cond =~ /^TRUE|FALSE$/;
5646       $cond = condition_negate ($cond)
5647         if $negate;
5648
5649       &am_file_error ($where,
5650                       "endif reminder ($negate$cond) incompatible with "
5651                       . "current conditional: $cond_stack[$#cond_stack]")
5652         if $cond_stack[$#cond_stack] ne $cond;
5653     }
5654
5655   pop @cond_stack;
5656
5657   return conditional_string (@cond_stack);
5658 }
5659
5660
5661
5662
5663
5664 ## ------------------------ ##
5665 ## Handling the variables.  ##
5666 ## ------------------------ ##
5667
5668
5669 # check_ambiguous_conditional ($VAR, $COND)
5670 # -----------------------------------------
5671 # Check for an ambiguous conditional.  This is called when a variable
5672 # is being defined conditionally.  If we already know about a
5673 # definition that is true under the same conditions, then we have an
5674 # ambiguity.
5675 sub check_ambiguous_conditional ($$)
5676 {
5677     my ($var, $cond) = @_;
5678     foreach my $vcond (keys %{$var_value{$var}})
5679     {
5680        my $message;
5681        if ($vcond eq $cond)
5682        {
5683            $message = "$var multiply defined in condition $cond";
5684        }
5685        elsif (&conditional_true_when ($vcond, $cond))
5686        {
5687          $message = ("$var was already defined in condition $vcond, "
5688                      . "which implies condition $cond");
5689        }
5690        elsif (&conditional_true_when ($cond, $vcond))
5691        {
5692            $message = ("$var was already defined in condition $vcond, "
5693                        . "which is implied by condition $cond");
5694        }
5695        if ($message)
5696        {
5697            &am_line_error ($var, $message);
5698            macro_dump ($var);
5699        }
5700    }
5701 }
5702
5703
5704 # &macro_define($VAR, $VAR_IS_AM, $TYPE, $COND, $VALUE, $WHERE)
5705 # -------------------------------------------------------------
5706 # The $VAR can go from Automake to user, but not the converse.
5707 sub macro_define ($$$$$$)
5708 {
5709   my ($var, $var_is_am, $type, $cond, $value, $where) = @_;
5710
5711   am_file_error ($where, "bad macro name `$var'")
5712     if $var !~ /$MACRO_PATTERN/o;
5713
5714   $cond ||= 'TRUE';
5715
5716   # An Automake variable must be consistently defined with the same
5717   # sign by Automake.  A user variable must be set by either `=' or
5718   # `:=', and later promoted to `+='.
5719   if ($var_is_am)
5720     {
5721       if (defined $var_type{$var} && $var_type{$var} ne $type)
5722         {
5723           am_line_error ($var,
5724                          ("$var was set with `$var_type{$var}=' "
5725                           . "and is now set with `$type='"));
5726         }
5727     }
5728   else
5729     {
5730       if (!defined $var_type{$var} && $type eq '+')
5731         {
5732           am_line_error ($var, "$var must be set with `=' before using `+='");
5733         }
5734     }
5735   $var_type{$var} = $type;
5736
5737   # When adding, since we rewrite, don't try to preserve the
5738   # Automake continuation backslashes.
5739   $value =~ s/\\$//mg
5740     if $type eq '+' && $var_is_am;
5741
5742   # Differentiate the first assignment (including with `+=').
5743   if ($type eq '+' && defined $var_value{$var}{$cond})
5744     {
5745       if (substr ($var_value{$var}{$cond}, -1) eq "\n")
5746         {
5747           # Insert a backslash before a trailing newline.
5748           $var_value{$var}{$cond} =
5749             substr ($var_value{$var}{$cond}, 0, -1) . "\\\n";
5750         }
5751       elsif ($var_value{$var}{$cond})
5752         {
5753           # Insert a separator.
5754           $var_value{$var}{$cond} .= ' ';
5755         }
5756        $var_value{$var}{$cond} .= $value;
5757     }
5758   else
5759     {
5760       # The first assignment to a macro sets the line number.  Ideally I
5761       # suppose we would associate line numbers with random bits of text.
5762       # FIXME: We sometimes redefine some variables, but we want to keep
5763       # the original location.  More subs are needed to handle
5764       # properly variables.  Once this done, remove this hack.
5765       $var_line{$var} = $where
5766         unless defined $var_line{$var};
5767
5768       # If Automake tries to override a value specified by the user,
5769       # just don't let it do.
5770       if (defined $var_value{$var}{$cond} && !$var_is_am{$var} && $var_is_am)
5771         {
5772           if ($verbose)
5773             {
5774               print STDERR "$me: refusing to override the user definition of:\n";
5775               macro_dump ($var);
5776               print STDERR "$me: with `$cond' => `$value'\n";
5777             }
5778         }
5779       else
5780         {
5781           # There must be no previous value unless the user is redefining
5782           # an Automake variable or an AC_SUBST variable.
5783           check_ambiguous_conditional ($var, $cond)
5784             unless ($var_is_am{$var} && !$var_is_am
5785                     || exists $configure_vars{$var});
5786
5787           $var_value{$var}{$cond} = $value;
5788         }
5789     }
5790
5791   # An Automake variable can be given to the user, but not the converse.
5792   if (! defined $var_is_am{$var} || !$var_is_am)
5793     {
5794       $var_is_am{$var} = $var_is_am;
5795     }
5796 }
5797
5798
5799 # &variable_delete ($VAR, [@CONDS])
5800 # ---------------------------------
5801 # Forget about $VAR under the conditions @CONDS, or completely if
5802 # @CONDS is empty.
5803 sub variable_delete ($@)
5804 {
5805   my ($var, @conds) = @_;
5806
5807   if (!@conds)
5808     {
5809       delete $var_value{$var};
5810       delete $var_line{$var};
5811       delete $var_is_am{$var};
5812       delete $var_comment{$var};
5813       delete $var_type{$var};
5814     }
5815   else
5816     {
5817       foreach my $cond (@conds)
5818         {
5819           delete $var_value{$var}{$cond};
5820         }
5821     }
5822 }
5823
5824
5825 # &macro_dump ($VAR)
5826 # ------------------
5827 sub macro_dump ($)
5828 {
5829   my ($var) = @_;
5830
5831   if (!exists $var_value{$var})
5832     {
5833       print STDERR "  $var does not exist\n";
5834     }
5835   else
5836     {
5837       my $var_is_am = $var_is_am{$var} ? "Automake" : "User";
5838       my $where = (defined $var_line{$var}
5839                    ? $var_line{$var} : "undefined");
5840       print STDERR "$var_comment{$var}"
5841         if defined $var_comment{$var};
5842       print STDERR "  $var ($var_is_am, where = $where) $var_type{$var}=\n";
5843       print STDERR "  {\n";
5844       foreach my $vcond (sort by_condition keys %{$var_value{$var}})
5845         {
5846           print STDERR "    $vcond => $var_value{$var}{$vcond}\n";
5847         }
5848       print STDERR "  }\n";
5849     }
5850 }
5851
5852
5853 # &macros_dump ()
5854 # ---------------
5855 sub macros_dump ()
5856 {
5857   my ($var) = @_;
5858
5859   print STDERR "%var_value =\n";
5860   print STDERR "{\n";
5861   foreach my $var (sort (keys %var_value))
5862     {
5863       macro_dump ($var);
5864     }
5865   print STDERR "}\n";
5866 }
5867
5868
5869 # $BOOLEAN
5870 # &variable_defined ($VAR, [$COND])
5871 # ---------------------------------
5872 # See if a variable exists.  $VAR is the variable name, and $COND is
5873 # the condition which we should check.  If no condition is given, we
5874 # currently return true if the variable is defined under any
5875 # condition.
5876 sub variable_defined ($$)
5877 {
5878     my ($var, $cond) = @_;
5879
5880     # Unfortunately we can't just check for $var_value{VAR}{COND}
5881     # as this would make perl create $condition{VAR}, which we
5882     # don't want.
5883     if (!exists $var_value{$var})
5884       {
5885         if (defined $targets{$var})
5886           {
5887             &am_line_error ($var, "`$var' is a target; expected a variable")
5888           }
5889         # The variable is not defined
5890         return 0;
5891       }
5892
5893     if ($cond && !exists $var_value{$var}{$cond})
5894       {
5895         # The variable is not defined for the given condition.
5896         return 0;
5897       }
5898
5899     # Even a var_value examination is good enough for us.  FIXME:
5900     # really should maintain examined status on a per-condition basis.
5901     $content_seen{$var} = 1;
5902     return 1;
5903 }
5904
5905 # Mark a variable as examined.
5906 sub examine_variable
5907 {
5908     my ($var) = @_;
5909     &variable_defined ($var);
5910 }
5911
5912 # Return the set of conditions for which a variable is defined.
5913
5914 # If the variable is not defined conditionally, and is not defined in
5915 # terms of any variables which are defined conditionally, then this
5916 # returns the empty list.
5917
5918 # If the variable is defined conditionally, but is not defined in
5919 # terms of any variables which are defined conditionally, then this
5920 # returns the list of conditions for which the variable is defined.
5921
5922 # If the variable is defined in terms of any variables which are
5923 # defined conditionally, then this returns a full set of permutations
5924 # of the subvariable conditions.  For example, if the variable is
5925 # defined in terms of a variable which is defined for COND_TRUE,
5926 # then this returns both COND_TRUE and COND_FALSE.  This is
5927 # because we will need to define the variable under both conditions.
5928
5929 sub variable_conditions_recursive ($)
5930 {
5931     my ($var) = @_;
5932
5933     %vars_scanned = ();
5934
5935     my @new_conds = variable_conditions_recursive_sub ($var, '');
5936     # Now we want to return all permutations of the subvariable
5937     # conditions.
5938     my %allconds = ();
5939     foreach my $item (@new_conds)
5940     {
5941         foreach (split (' ', $item))
5942         {
5943             s/^(.*)_(TRUE|FALSE)$/$1_TRUE/;
5944             $allconds{$_} = 1;
5945         }
5946     }
5947     @new_conds = variable_conditions_permutations (sort keys %allconds);
5948
5949     my %uniqify;
5950     foreach my $cond (@new_conds)
5951     {
5952         my $reduce = variable_conditions_reduce (split (' ', $cond));
5953         next
5954             if $reduce eq 'FALSE';
5955         $uniqify{$cond} = 1;
5956     }
5957
5958     # Note we cannot just do `return sort keys %uniqify', because this
5959     # function is sometimes used in a scalar context.
5960     my @uniq_list = sort by_condition keys %uniqify;
5961     return @uniq_list;
5962 }
5963
5964 # @CONDS
5965 # variable_conditions ($VAR)
5966 # --------------------------
5967 # Get the list of conditions that a variable is defined with, without
5968 # recursing through the conditions of any subvariables.
5969 # Argument is $VAR: the variable to get the conditions of.
5970 # Returns the list of conditions.
5971 sub variable_conditions ($)
5972 {
5973     my ($var) = @_;
5974     my @conds = keys %{$var_value{$var}};
5975     return sort by_condition @conds;
5976 }
5977
5978
5979 # $BOOLEAN
5980 # &variable_conditionally_defined ($VAR)
5981 # --------------------------------------
5982 sub variable_conditionally_defined ($)
5983 {
5984     my ($var) = @_;
5985     foreach my $cond (variable_conditions_recursive ($var))
5986       {
5987         return 1
5988           unless $cond =~ /^TRUE|FALSE$/;
5989       }
5990     return 0;
5991 }
5992
5993
5994
5995 # &variable_conditions_recursive_sub ($VAR, $PARENT)
5996 # -------------------------------------------------------
5997 # A subroutine of variable_conditions_recursive.  This returns all the
5998 # conditions of $VAR, including those of any sub-variables.
5999 sub variable_conditions_recursive_sub
6000 {
6001     my ($var, $parent) = @_;
6002     my @new_conds = ();
6003
6004     if (defined $vars_scanned{$var})
6005     {
6006         &am_line_error ($parent, "variable `$var' recursively defined");
6007         return ();
6008     }
6009     $vars_scanned{$var} = 1;
6010
6011     my @this_conds = ();
6012     # Examine every condition under which $VAR is defined.
6013     foreach my $vcond (keys %{$var_value{$var}})
6014     {
6015         push (@this_conds, $vcond);
6016
6017         # If $VAR references some other variable, then compute the
6018         # conditions for that subvariable.
6019         my @subvar_conds = ();
6020         foreach (split (' ', $var_value{$var}{$vcond}))
6021         {
6022             # If a comment seen, just leave.
6023             last if /^#/;
6024
6025             # Handle variable substitutions.
6026             if (/^\$\{(.*)\}$/ || /^\$\((.*)\)$/)
6027             {
6028                 my $varname = $1;
6029                 if ($varname =~ /$SUBST_REF_PATTERN/o)
6030                 {
6031                     $varname = $1;
6032                 }
6033
6034
6035                 # Here we compute all the conditions under which the
6036                 # subvariable is defined.  Then we go through and add
6037                 # $VCOND to each.
6038                 my @svc = variable_conditions_recursive_sub ($varname, $var);
6039                 foreach my $item (@svc)
6040                 {
6041                     my $val = conditional_string ($vcond, split (' ', $item));
6042                     $val ||= 'TRUE';
6043                     push (@subvar_conds, $val);
6044                 }
6045             }
6046         }
6047
6048         # If there are no conditional subvariables, then we want to
6049         # return this condition.  Otherwise, we want to return the
6050         # permutations of the subvariables, taking into account the
6051         # conditions of $VAR.
6052         if (! @subvar_conds)
6053         {
6054             push (@new_conds, $vcond);
6055         }
6056         else
6057         {
6058             push (@new_conds, variable_conditions_reduce (@subvar_conds));
6059         }
6060     }
6061
6062     # Unset our entry in vars_scanned.  We only care about recursive
6063     # definitions.
6064     delete $vars_scanned{$var};
6065
6066     # If we are being called on behalf of another variable, we need to
6067     # return all possible permutations of the conditions.  We have
6068     # already handled everything in @this_conds along with their
6069     # subvariables.  We now need to add any permutations that are not
6070     # in @this_conds.
6071     foreach my $this_cond (@this_conds)
6072     {
6073         my @perms =
6074             variable_conditions_permutations (split (' ', $this_cond));
6075         foreach my $perm (@perms)
6076         {
6077             my $ok = 1;
6078             foreach my $scan (@this_conds)
6079             {
6080                 if (&conditional_true_when ($perm, $scan)
6081                     || &conditional_true_when ($scan, $perm))
6082                 {
6083                     $ok = 0;
6084                     last;
6085                 }
6086             }
6087             next if ! $ok;
6088
6089             # This permutation was not already handled, and is valid
6090             # for the parents.
6091             push (@new_conds, $perm);
6092         }
6093     }
6094
6095     return @new_conds;
6096 }
6097
6098
6099 # Filter a list of conditionals so that only the exclusive ones are
6100 # retained.  For example, if both `COND1_TRUE COND2_TRUE' and
6101 # `COND1_TRUE' are in the list, discard the latter.
6102 # If the list is empty, return TRUE
6103 sub variable_conditions_reduce
6104 {
6105     my (@conds) = @_;
6106     my @ret = ();
6107     my $cond;
6108     while(@conds > 0)
6109     {
6110         $cond = shift(@conds);
6111
6112         # FALSE is absorbent.
6113         if ($cond eq 'FALSE')
6114           {
6115             return ('FALSE');
6116           }
6117         elsif (!conditional_is_redundant ($cond, @ret, @conds))
6118           {
6119             push (@ret, $cond);
6120           }
6121     }
6122
6123     return "TRUE" if @ret == 0;
6124     return @ret;
6125 }
6126
6127 # @CONDS
6128 # invert_conditions (@CONDS)
6129 # --------------------------
6130 # Invert a list of conditionals.  Returns a set of conditionals which
6131 # are never true for any of the input conditionals, and when taken
6132 # together with the input conditionals cover all possible cases.
6133 #
6134 # For example: invert_conditions("A_TRUE B_TRUE", "A_FALSE B_FALSE") will
6135 # return ("A_FALSE B_TRUE", "A_TRUE B_FALSE")
6136 sub invert_conditions
6137 {
6138     my (@conds) = @_;
6139
6140     my @notconds = ();
6141     foreach my $cond (@conds)
6142     {
6143         foreach my $perm (variable_conditions_permutations (split(' ', $cond)))
6144         {
6145             push @notconds, $perm
6146                     if ! conditional_is_redundant ($perm, @conds);
6147         }
6148     }
6149     return variable_conditions_reduce (@notconds);
6150 }
6151
6152 # Return a list of permutations of a conditional string.
6153 sub variable_conditions_permutations
6154 {
6155     my (@comps) = @_;
6156     return ()
6157         if ! @comps;
6158     my $comp = shift (@comps);
6159     return variable_conditions_permutations (@comps)
6160         if $comp eq '';
6161     my $neg = condition_negate ($comp);
6162
6163     my @ret;
6164     foreach my $sub (variable_conditions_permutations (@comps))
6165     {
6166         push (@ret, "$comp $sub");
6167         push (@ret, "$neg $sub");
6168     }
6169     if (! @ret)
6170     {
6171         push (@ret, $comp);
6172         push (@ret, $neg);
6173     }
6174     return @ret;
6175 }
6176
6177
6178 # $BOOL
6179 # &check_variable_defined_unconditionally($VAR, $PARENT)
6180 # ------------------------------------------------------
6181 # Warn if a variable is conditionally defined.  This is called if we
6182 # are using the value of a variable.
6183 sub check_variable_defined_unconditionally ($$)
6184 {
6185     my ($var, $parent) = @_;
6186     foreach my $cond (keys %{$var_value{$var}})
6187     {
6188         next
6189           if $cond =~ /^TRUE|FALSE$/;
6190
6191         if ($parent)
6192         {
6193             &am_line_error ($parent,
6194                             "warning: automake does not support conditional definition of $var in $parent");
6195         }
6196         else
6197         {
6198             &am_line_error ($parent,
6199                             "warning: automake does not support $var being defined conditionally");
6200         }
6201     }
6202 }
6203
6204
6205 # Get the TRUE value of a variable, warn if the variable is
6206 # conditionally defined.
6207 sub variable_value
6208 {
6209     my ($var) = @_;
6210     &check_variable_defined_unconditionally ($var);
6211     return $var_value{$var}{'TRUE'};
6212 }
6213
6214
6215 # @VALUES
6216 # &value_to_list ($VAR, $VAL, $COND)
6217 # ----------------------------------
6218 # Convert a variable value to a list, split as whitespace.  This will
6219 # recursively follow $(...) and ${...} inclusions.  It preserves @...@
6220 # substitutions.
6221 #
6222 # If COND is 'all', then all values under all conditions should be
6223 # returned; if COND is a particular condition (all conditions are
6224 # surrounded by @...@) then only the value for that condition should
6225 # be returned; otherwise, warn if VAR is conditionally defined.
6226 # SCANNED is a global hash listing whose keys are all the variables
6227 # already scanned; it is an error to rescan a variable.
6228 sub value_to_list
6229 {
6230     my ($var, $val, $cond) = @_;
6231     my @result;
6232
6233     # Strip backslashes
6234     $val =~ s/\\(\n|$)/ /g;
6235
6236     foreach (split (' ', $val))
6237     {
6238         # If a comment seen, just leave.
6239         last if /^#/;
6240
6241         # Handle variable substitutions.
6242         if (/^\$\{([^}]*)\}$/ || /^\$\(([^)]*)\)$/)
6243         {
6244             my $varname = $1;
6245
6246             # If the user uses a losing variable name, just ignore it.
6247             # This isn't ideal, but people have requested it.
6248             next if ($varname =~ /\@.*\@/);
6249
6250             my ($from, $to);
6251             my @temp_list;
6252             if ($varname =~ /$SUBST_REF_PATTERN/o)
6253             {
6254                 $varname = $1;
6255                 $to = $3;
6256                 ($from = $2) =~ s/(\W)/\\$1/g;
6257             }
6258
6259             # Find the value.
6260             @temp_list = &variable_value_as_list_recursive_worker ($1, $cond, $var);
6261
6262             # Now rewrite the value if appropriate.
6263             if (defined $from)
6264             {
6265                 grep (s/$from$/$to/, @temp_list);
6266             }
6267
6268             push (@result, @temp_list);
6269         }
6270         else
6271         {
6272             push (@result, $_);
6273         }
6274     }
6275
6276     return @result;
6277 }
6278
6279 # @VALUES
6280 # variable_value_as_list ($VAR, $COND, $PARENT)
6281 # ---------------------------------------------
6282 # Get the value of a variable given a specified condition. without
6283 # recursing through any subvariables.
6284 # Arguments are:
6285 #   $VAR    is the variable
6286 #   $COND   is the condition.  If this is not given, the value for the
6287 #           "TRUE" condition will be returned.
6288 #   $PARENT is the variable in which the variable is used: this is used
6289 #           only for error messages.
6290 # Returns the list of conditions.
6291 # For example, if A is defined as "foo $(B) bar", and B is defined as
6292 # "baz", this will return ("foo", "$(B)", "bar")
6293 sub variable_value_as_list
6294 {
6295     my ($var, $cond, $parent) = @_;
6296     my @result;
6297
6298     # Check defined
6299     if (! defined $var_value{$var})
6300     {
6301         if (defined $targets{$var})
6302           {
6303             &am_line_error ($var, "`$var' is a target; expected a variable");
6304           }
6305         else
6306           {
6307             &am_line_error ($parent, "variable `$var' not defined");
6308           }
6309     }
6310
6311     # Get value for given condition
6312     $cond ||= 'TRUE';
6313     my $onceflag;
6314     foreach my $vcond (keys %{$var_value{$var}})
6315     {
6316         my $val = $var_value{$var}{$vcond};
6317
6318         if (&conditional_true_when ($vcond, $cond))
6319         {
6320             # Unless variable is not defined conditionally, there should only
6321             # be one value of $vcond true when $cond.
6322             &check_variable_defined_unconditionally ($var, $parent)
6323                     if $onceflag;
6324             $onceflag = 1;
6325
6326             # Strip backslashes
6327             $val =~ s/\\(\n|$)/ /g;
6328
6329             foreach (split (' ', $val))
6330             {
6331                 # If a comment seen, just leave.
6332                 last if /^#/;
6333
6334                 push (@result, $_);
6335             }
6336         }
6337     }
6338
6339     return @result;
6340 }
6341
6342 # Return contents of variable as list, split as whitespace.  This will
6343 # recursively follow $(...) and ${...} inclusions.  It preserves @...@
6344 # substitutions.  If COND is 'all', then all values under all
6345 # conditions should be returned; if COND is a particular condition
6346 # (all conditions are surrounded by @...@) then only the value for
6347 # that condition should be returned; otherwise, warn if VAR is
6348 # conditionally defined.  If PARENT is specified, it is the name of
6349 # the including variable; this is only used for error reports.
6350 sub variable_value_as_list_recursive_worker
6351 {
6352     my ($var, $cond, $parent) = @_;
6353     my @result = ();
6354
6355     if (! defined $var_value{$var})
6356     {
6357         if (defined $targets{$var})
6358           {
6359             &am_line_error ($var, "`$var' is a target; expected a variable");
6360           }
6361         else
6362           {
6363             &am_line_error ($parent, "variable `$var' not defined");
6364           }
6365     }
6366     elsif (defined $vars_scanned{$var})
6367     {
6368         # `vars_scanned' is a global we use to keep track of which
6369         # variables we've already examined.
6370         &am_line_error ($parent, "variable `$var' recursively defined");
6371     }
6372     elsif ($cond eq 'all')
6373     {
6374         $vars_scanned{$var} = 1;
6375         foreach my $vcond (keys %{$var_value{$var}})
6376         {
6377             my $val = $var_value{$var}{$vcond};
6378             push (@result, &value_to_list ($var, $val, $cond));
6379         }
6380     }
6381     else
6382     {
6383         $cond ||= 'TRUE';
6384         $vars_scanned{$var} = 1;
6385         my $onceflag;
6386         foreach my $vcond (keys %{$var_value{$var}})
6387         {
6388             my $val = $var_value{$var}{$vcond};
6389             if (&conditional_true_when ($vcond, $cond))
6390             {
6391                 # Warn if we have an ambiguity.  It's hard to know how
6392                 # to handle this case correctly.
6393                 &check_variable_defined_unconditionally ($var, $parent)
6394                     if $onceflag;
6395                 $onceflag = 1;
6396                 push (@result, &value_to_list ($var, $val, $cond));
6397             }
6398         }
6399     }
6400
6401     # Unset our entry in vars_scanned.  We only care about recursive
6402     # definitions.
6403     delete $vars_scanned{$var};
6404
6405     return @result;
6406 }
6407
6408
6409 # &variable_output ($VAR, [@CONDS])
6410 # ---------------------------------
6411 # Output all the values of $VAR is @COND is not specified, else only
6412 # that corresponding to @COND.
6413 sub variable_output ($@)
6414 {
6415   my ($var, @conds) = @_;
6416
6417   @conds = keys %{$var_value{$var}}
6418     unless @conds;
6419
6420   $output_vars .= $var_comment{$var}
6421     if defined $var_comment{$var};
6422
6423   foreach my $cond (sort by_condition @conds)
6424     {
6425       my $val = $var_value{$var}{$cond};
6426       my $equals = $var_type{$var} eq ':' ? ':=' : '=';
6427       my $output_var = "$var $equals $val";
6428       $output_var =~ s/^/make_condition ($cond)/meg;
6429       $output_vars .= $output_var . "\n";
6430     }
6431 }
6432
6433
6434 # &variable_pretty_output ($VAR, [@CONDS])
6435 # ----------------------------------------
6436 # Likewise, but pretty, i.e., we *split* the values at spaces.   Use only
6437 # with variables holding filenames.
6438 sub variable_pretty_output ($@)
6439 {
6440   my ($var, @conds) = @_;
6441
6442   @conds = keys %{$var_value{$var}}
6443     unless @conds;
6444
6445   $output_vars .= $var_comment{$var}
6446     if defined $var_comment{$var};
6447
6448   foreach my $cond (sort by_condition @conds)
6449     {
6450       my $val = $var_value{$var}{$cond};
6451       my $equals = $var_type{$var} eq ':' ? ':=' : '=';
6452       my $make_condition = make_condition ($cond);
6453       $output_vars .= pretty_print_internal ("$make_condition$var $equals",
6454                                              "$make_condition\t",
6455                                              split (' ' , $val));
6456     }
6457 }
6458
6459
6460 # This is just a wrapper for variable_value_as_list_recursive_worker that
6461 # initializes the global hash `vars_scanned'.  This hash is used to
6462 # avoid infinite recursion.
6463 sub variable_value_as_list_recursive
6464 {
6465     my ($var, $cond, $parent) = @_;
6466     %vars_scanned = ();
6467     return &variable_value_as_list_recursive_worker ($var, $cond, $parent);
6468 }
6469
6470
6471 # Like define_variable, but the value is a list, and the variable may
6472 # be defined conditionally.  The second argument is the conditional
6473 # under which the value should be defined; this should be the empty
6474 # string to define the variable unconditionally.  The third argument
6475 # is a list holding the values to use for the variable.  The value is
6476 # pretty printed in the output file.
6477 sub define_pretty_variable
6478 {
6479     my ($var, $cond, @value) = @_;
6480
6481     # Beware that an empty $cond has a different semantics for
6482     # macro_define and variable_pretty_output.
6483     $cond ||= 'TRUE';
6484
6485     if (! &variable_defined ($var, $cond))
6486     {
6487         macro_define ($var, 1, '', $cond, join (' ', @value), undef);
6488         variable_pretty_output ($var, $cond || 'TRUE');
6489         $content_seen{$var} = 1;
6490     }
6491 }
6492
6493
6494 # define_variable ($VAR, $VALUE)
6495 # ------------------------------
6496 # Define a new user variable VAR to VALUE, but only if not already defined.
6497 sub define_variable
6498 {
6499     my ($var, $value) = @_;
6500
6501     define_pretty_variable ($var, 'TRUE', $value);
6502 }
6503
6504
6505 # Like define_variable, but define a variable to be the configure
6506 # substitution by the same name.
6507 sub define_configure_variable
6508 {
6509     my ($var) = @_;
6510     my $value = '@' . $var . '@';
6511     &define_variable ($var, $value);
6512 }
6513
6514
6515 # define_compiler_variable ($LANG)
6516 # --------------------------------
6517 # Define a compiler variable.  We also handle defining the `LT'
6518 # version of the command when using libtool.
6519 sub define_compiler_variable ($)
6520 {
6521     my ($lang) = @_;
6522
6523     my ($var, $value) = ($lang->compiler, $lang->compile);
6524     &define_variable ($var, $value);
6525     &define_variable ("LT$var", "\$(LIBTOOL) --mode=compile $value")
6526       if $seen_libtool;
6527 }
6528
6529
6530 # define_linker_variable ($LANG)
6531 # ------------------------------
6532 # Define linker variables.
6533 sub define_linker_variable ($)
6534 {
6535     my ($lang) = @_;
6536
6537     my ($var, $value) = ($lang->lder, $lang->ld);
6538     # CCLD = $(CC).
6539     &define_variable ($lang->lder, $lang->ld);
6540     # CCLINK = $(CCLD) blah blah...
6541     &define_variable ($lang->linker,
6542                       (($seen_libtool ? '$(LIBTOOL) --mode=link ' : '')
6543                        . $lang->link));
6544 }
6545
6546 ################################################################
6547
6548 ## ---------------- ##
6549 ## Handling rules.  ##
6550 ## ---------------- ##
6551
6552 # $BOOL
6553 # rule_define ($TARGET, $IS_AM, $COND, $WHERE)
6554 # --------------------------------------------
6555 # Define a new rule.  $TARGET is the rule name.  $IS_AM is a boolean
6556 # which is true if the new rule is defined by the user.  $COND is the
6557 # condition under which the rule is defined.  $WHERE is where the rule
6558 # is defined (file name or line number).  Returns true if it is ok to
6559 # define the rule, false otherwise.
6560 sub rule_define ($$$$)
6561 {
6562   my ($target, $rule_is_am, $cond, $where) = @_;
6563
6564   # For now `foo:' will override `foo$(EXEEXT):'.  This is temporary,
6565   # though, so we emit a warning.
6566   (my $noexe = $target) =~ s,\$\(EXEEXT\)$,,;
6567   if ($noexe ne $target && defined $targets{$noexe})
6568   {
6569       # The no-exeext option enables this feature.
6570       if (! defined $options{'no-exeext'})
6571       {
6572           &am_line_error ($noexe,
6573                           "deprecated feature: `$noexe' overrides `$noexe\$(EXEEXT)'\nchange your target to read `$noexe\$(EXEEXT)'");
6574       }
6575       # Don't define.
6576       return 0;
6577   }
6578
6579   if (defined $targets{$target}
6580       && ($cond
6581           ? ! defined $target_conditional{$target}
6582           : defined $target_conditional{$target}))
6583   {
6584       &am_line_error ($target,
6585                       "$target defined both conditionally and unconditionally");
6586   }
6587
6588   # Value here doesn't matter; for targets we only note existence.
6589   $targets{$target} = $where;
6590   if ($cond)
6591   {
6592       if ($target_conditional{$target})
6593       {
6594           &check_ambiguous_conditional ($target, $cond);
6595       }
6596       $target_conditional{$target}{$cond} = $where;
6597   }
6598
6599
6600   # Check the rule for being a suffix rule. If so, store in a hash.
6601
6602   if ((my ($source_suffix, $object_suffix)) = ($target =~ $SUFFIX_RULE_PATTERN))
6603   {
6604       $suffix_rules{$source_suffix} = $object_suffix;
6605       print "Sources ending in .$source_suffix become .$object_suffix\n"
6606           if $verbose;
6607       # Set SUFFIXES from suffix_rules.
6608       push @suffixes, ".$source_suffix", ".$object_suffix";
6609   }
6610
6611   return 1;
6612 }
6613
6614
6615 # See if a target exists.
6616 sub target_defined
6617 {
6618     my ($target) = @_;
6619     return defined $targets{$target};
6620 }
6621
6622
6623 ################################################################
6624
6625 # Read Makefile.am and set up %contents.  Simultaneously copy lines
6626 # from Makefile.am into $output_trailer or $output_vars as
6627 # appropriate.  NOTE we put rules in the trailer section.  We want
6628 # user rules to come after our generated stuff.
6629 sub read_am_file
6630 {
6631     my ($amfile) = @_;
6632
6633     my $am_file = new Automake::XFile ("< $amfile");
6634     print "$me: reading $amfile\n" if $verbose;
6635
6636     my $spacing = '';
6637     my $comment = '';
6638     my $blank = 0;
6639
6640     while ($_ = $am_file->getline)
6641     {
6642         if (/$IGNORE_PATTERN/o)
6643         {
6644             # Merely delete comments beginning with two hashes.
6645         }
6646         elsif (/$WHITE_PATTERN/o)
6647         {
6648             # Stick a single white line before the incoming macro or rule.
6649             $spacing = "\n";
6650             $blank = 1;
6651         }
6652         elsif (/$COMMENT_PATTERN/o)
6653         {
6654             # Stick comments before the incoming macro or rule.  Make
6655             # sure a blank line preceeds first block of comments.
6656             $spacing = "\n" unless $blank;
6657             $blank = 1;
6658             $comment .= $spacing . $_;
6659             $spacing = '';
6660         }
6661         else
6662         {
6663             last;
6664         }
6665     }
6666
6667     $output_vars .= $comment . "\n";
6668     $comment = '';
6669     $spacing = "\n";
6670
6671     # We save the conditional stack on entry, and then check to make
6672     # sure it is the same on exit.  This lets us conditonally include
6673     # other files.
6674     my @saved_cond_stack = @cond_stack;
6675     my $cond = conditional_string (@cond_stack);
6676
6677     my $saw_bk = 0;
6678     my $was_rule = 0;
6679     my $last_var_name = '';
6680     my $last_var_type = '';
6681     my $last_var_value = '';
6682     # FIXME: shouldn't use $_ in this loop; it is too big.
6683     while ($_)
6684     {
6685         $_ .= "\n"
6686             unless substr ($_, -1, 1) eq "\n";
6687
6688         # Don't look at MAINTAINER_MODE_TRUE here.  That shouldn't be
6689         # used by users.  @MAINT@ is an anachronism now.
6690         $_ =~ s/\@MAINT\@//g
6691             unless $seen_maint_mode;
6692
6693         my $new_saw_bk = /\\$/ && ! /$COMMENT_PATTERN/o;
6694
6695         if (/$IGNORE_PATTERN/o)
6696         {
6697             # Merely delete comments beginning with two hashes.
6698         }
6699         elsif (/$WHITE_PATTERN/o)
6700         {
6701             # Stick a single white line before the incoming macro or rule.
6702             $spacing = "\n";
6703             &am_line_error ($., "blank line following trailing backslash")
6704                 if $saw_bk;
6705         }
6706         elsif (/$COMMENT_PATTERN/o)
6707         {
6708             # Stick comments before the incoming macro or rule.
6709             $comment .= $spacing . $_;
6710             $spacing = '';
6711             &am_line_error ($., "comment following trailing backslash")
6712                 if $saw_bk;
6713         }
6714         elsif ($saw_bk)
6715         {
6716             if ($was_rule)
6717             {
6718                 $output_trailer .= &make_condition (@cond_stack);
6719                 $output_trailer .= $_;
6720             }
6721             else
6722             {
6723               $last_var_value .= ' '
6724                 unless $last_var_value =~ /\s$/;
6725               $last_var_value .= $_;
6726
6727               if (!/\\$/)
6728                 {
6729                   $var_comment{$last_var_name} .= "$spacing"
6730                     if (!defined $var_comment{$last_var_name}
6731                         || substr ($var_comment{$last_var_name}, -1) ne "\n");
6732                   $var_comment{$last_var_name} .= "$comment";
6733                   $comment = $spacing = '';
6734                   macro_define ($last_var_name, 0,
6735                                 $last_var_type, $cond,
6736                                 $last_var_value, $.)
6737                     if $cond ne 'FALSE';
6738                   push (@var_list, $last_var_name);
6739                 }
6740             }
6741         }
6742
6743         elsif (/$IF_PATTERN/o)
6744           {
6745             $cond = cond_stack_if ($1, $2, "$amfile:$.");
6746           }
6747         elsif (/$ELSE_PATTERN/o)
6748           {
6749             $cond = cond_stack_else ($1, $2, "$amfile:$.");
6750           }
6751         elsif (/$ENDIF_PATTERN/o)
6752           {
6753             $cond = cond_stack_endif ($1, $2, "$amfile:$.");
6754           }
6755
6756         elsif (/$RULE_PATTERN/o)
6757         {
6758             # Found a rule.
6759             $was_rule = 1;
6760
6761             rule_define ($1, 0, $cond, $.);
6762
6763             $var_line{$1} = $.;
6764             $output_trailer .= $comment . $spacing;
6765             $output_trailer .= &make_condition (@cond_stack);
6766             $output_trailer .= $_;
6767             $comment = $spacing = '';
6768         }
6769         elsif (/$ASSIGNMENT_PATTERN/o)
6770         {
6771             # Found a macro definition.
6772             $was_rule = 0;
6773             $last_var_name = $1;
6774             $last_var_type = $2;
6775             $last_var_value = $3;
6776             if ($3 ne '' && substr ($3, -1) eq "\\")
6777             {
6778                 # We preserve the `\' because otherwise the long lines
6779                 # that are generated will be truncated by broken
6780                 # `sed's.
6781                 $last_var_value = $3 . "\n";
6782             }
6783
6784             if (!/\\$/)
6785               {
6786                 # FIXME: this doesn't always work correctly; it will
6787                 # group all comments for a given variable, no matter
6788                 # where defined.
6789                 # Accumulating variables must not be output.
6790                 $var_comment{$last_var_name} .= "$spacing"
6791                   if (!defined $var_comment{$last_var_name}
6792                       || substr ($var_comment{$last_var_name}, -1) ne "\n");
6793                 $var_comment{$last_var_name} .= "$comment";
6794                 $comment = $spacing = '';
6795
6796                 macro_define ($last_var_name, 0,
6797                               $last_var_type, $cond,
6798                               $last_var_value, $.)
6799                   if $cond ne 'FALSE';
6800                 push (@var_list, $last_var_name);
6801               }
6802         }
6803         elsif (/$INCLUDE_PATTERN/o)
6804         {
6805             my $path = $1;
6806
6807             if ($path =~ s/^\$\(top_srcdir\)\///)
6808             {
6809                 push (@include_stack, "\$\(top_srcdir\)/$path");
6810             }
6811             else
6812             {
6813                 $path =~ s/\$\(srcdir\)\///;
6814                 push (@include_stack, "\$\(srcdir\)/$path");
6815                 $path = $relative_dir . "/" . $path;
6816             }
6817             &read_am_file ($path);
6818         }
6819         else
6820         {
6821             # This isn't an error; it is probably a continued rule.
6822             # In fact, this is what we assume.
6823             $was_rule = 1;
6824             $output_trailer .= $comment . $spacing;
6825             $output_trailer .= &make_condition  (@cond_stack);
6826             $output_trailer .= $_;
6827             $comment = $spacing = '';
6828             &am_line_error ($., "`#' comment at start of rule is unportable")
6829                 if $_ =~ /^\t\s*\#/;
6830         }
6831
6832         $saw_bk = $new_saw_bk;
6833         $_ = $am_file->getline;
6834     }
6835
6836     $output_trailer .= $comment;
6837
6838     if (join (' ', @saved_cond_stack) ne join (' ', @cond_stack))
6839     {
6840         if (@cond_stack)
6841         {
6842             &am_error ("unterminated conditionals: @cond_stack");
6843         }
6844         else
6845         {
6846             # FIXME: better error message here.
6847             &am_error ("conditionals not nested in include file");
6848         }
6849     }
6850 }
6851
6852
6853 # define_standard_variables ()
6854 # ----------------------------
6855 # A helper for read_main_am_file which initializes configure variables
6856 # and variables from header-vars.am.  This is a subr so we can call it
6857 # twice.
6858 sub define_standard_variables
6859 {
6860     my $saved_output_vars = $output_vars;
6861     my ($comments, undef, $rules) =
6862       file_contents_internal (1, "$libdir/am/header-vars.am");
6863
6864     # This will output the definitions in $output_vars, which we don't
6865     # want...
6866     foreach my $var (sort keys %configure_vars)
6867     {
6868         &define_configure_variable ($var);
6869         push (@var_list, $var);
6870     }
6871
6872     # ... hence, we restore $output_vars.
6873     $output_vars = $saved_output_vars . $comments . $rules;
6874 }
6875
6876 # Read main am file.
6877 sub read_main_am_file
6878 {
6879     my ($amfile) = @_;
6880
6881     # This supports the strange variable tricks we are about to play.
6882     if (scalar keys %var_value > 0)
6883       {
6884         macros_dump ();
6885         &prog_error ("variable defined before read_main_am_file");
6886       }
6887
6888     # Generate copyright header for generated Makefile.in.
6889     # We do discard the output of predefined variables, handled below.
6890     $output_vars = ("# $in_file_name generated automatically by automake "
6891                    . $VERSION . " from $am_file_name.\n");
6892     $output_vars .= $gen_copyright;
6893
6894     # We want to predefine as many variables as possible.  This lets
6895     # the user set them with `+=' in Makefile.am.  However, we don't
6896     # want these initial definitions to end up in the output quite
6897     # yet.  So we just load them, but output them later.
6898     &define_standard_variables;
6899
6900     # Read user file, which might override some of our values.
6901     &read_am_file ($amfile);
6902
6903     # Ouput all the Automake variables.  If the user changed one, then
6904     # it is now marked as owned by the user.
6905     foreach my $var (uniq @var_list)
6906     {
6907         # Don't process user variables.
6908         variable_output ($var)
6909           unless !$var_is_am{$var};
6910     }
6911
6912     # Now dump the user variables that were defined.  We do it in the same
6913     # order in which they were defined (skipping duplicates).
6914     foreach my $var (uniq @var_list)
6915     {
6916         # Don't process Automake variables.
6917         variable_output ($var)
6918           unless $var_is_am{$var};
6919     }
6920 }
6921
6922 ################################################################
6923
6924 # $FLATTENED
6925 # &flatten ($STRING)
6926 # ------------------
6927 # Flatten the $STRING and return the result.
6928 sub flatten
6929 {
6930   $_ = shift;
6931
6932   s/\\\n//somg;
6933   s/\s+/ /g;
6934   s/^ //;
6935   s/ $//;
6936
6937   return $_;
6938 }
6939
6940
6941 # @PARAGRAPHS
6942 # &make_paragraphs ($MAKEFILE, [%TRANSFORM])
6943 # ------------------------------------------
6944 # Load a $MAKEFILE, apply the %TRANSFORM, and return it as a list of
6945 # paragraphs.
6946 sub make_paragraphs ($%)
6947 {
6948     my ($file, %transform) = @_;
6949
6950     # Complete %transform with global options and make it a Perl
6951     # $command.
6952     my $command =
6953       "s/$IGNORE_PATTERN//gm;"
6954         . transform (%transform,
6955
6956                      'CYGNUS'          => $cygnus_mode,
6957                      'MAINTAINER-MODE'
6958                      => $seen_maint_mode ? subst ('MAINTAINER_MODE_TRUE') : '',
6959
6960                      'SHAR'        => $options{'dist-shar'} || 0,
6961                      'BZIP2'       => $options{'dist-bzip2'} || 0,
6962                      'ZIP'         => $options{'dist-zip'} || 0,
6963                      'COMPRESS'    => $options{'dist-tarZ'} || 0,
6964
6965                      'INSTALL-INFO' => !$options{'no-installinfo'},
6966                      'INSTALL-MAN'  => !$options{'no-installman'},
6967                      'CK-NEWS'      => $options{'check-news'} || 0,
6968
6969                      'SUBDIRS'      => &variable_defined ('SUBDIRS'),
6970                      'TOPDIR'       => backname ($relative_dir),
6971                      'TOPDIR_P'     => $relative_dir eq '.',
6972                      'CONFIGURE-AC' => $configure_ac,
6973
6974                      'BUILD'    => $seen_canonical == $AC_CANONICAL_SYSTEM,
6975                      'HOST'     => $seen_canonical,
6976                      'TARGET'   => $seen_canonical == $AC_CANONICAL_SYSTEM,
6977
6978                      'LIBTOOL'      => defined $configure_vars{'LIBTOOL'})
6979           # We don't need more than two consecutive new-lines.
6980           . 's/\n{3,}/\n\n/g';
6981
6982     # Swallow the file and apply the COMMAND.
6983     my $fc_file = new Automake::XFile ("< $file");
6984     # Looks stupid?
6985     print "$me: reading $file\n"
6986       if $verbose;
6987     my $saved_dollar_slash = $/;
6988     undef $/;
6989     $_ = $fc_file->getline;
6990     $/ = $saved_dollar_slash;
6991     eval $command;
6992     $fc_file->close;
6993     my $content = $_;
6994
6995     # Split at unescaped new lines.
6996     my @lines = split (/(?<!\\)\n/, $content);
6997     my @res;
6998
6999     while (defined ($_ = shift @lines))
7000       {
7001         my $paragraph = "$_";
7002         # If we are a rule, eat as long as we start with a tab.
7003         if (/$RULE_PATTERN/smo)
7004           {
7005             while (defined ($_ = shift @lines) && $_ =~ /^\t/)
7006               {
7007                 $paragraph .= "\n$_";
7008               }
7009             unshift (@lines, $_);
7010           }
7011
7012         # If we are a comments, eat as much comments as you can.
7013         elsif (/$COMMENT_PATTERN/smo)
7014           {
7015             while (defined ($_ = shift @lines)
7016                    && $_ =~ /$COMMENT_PATTERN/smo)
7017               {
7018                 $paragraph .= "\n$_";
7019               }
7020             unshift (@lines, $_);
7021           }
7022
7023         push @res, $paragraph;
7024         $paragraph = '';
7025       }
7026
7027     return @res;
7028 }
7029
7030
7031
7032 # ($COMMENT, $VARIABLES, $RULES)
7033 # &file_contents_internal ($IS_AM, $FILE, [%TRANSFORM])
7034 # -----------------------------------------------------
7035 # Return contents of a file from $libdir/am, automatically skipping
7036 # macros or rules which are already known. $IS_AM iff the caller is
7037 # reading an Automake file (as opposed to the user's Makefile.am).
7038 sub file_contents_internal ($$%)
7039 {
7040     my ($is_am, $file, %transform) = @_;
7041
7042     my $result_vars = '';
7043     my $result_rules = '';
7044     my $comment = '';
7045     my $spacing = '';
7046
7047     # We save the conditional stack on entry, and then check to make
7048     # sure it is the same on exit.  This lets us conditonally include
7049     # other files.
7050     my @saved_cond_stack = @cond_stack;
7051     my $cond = conditional_string (@cond_stack);
7052
7053     foreach (make_paragraphs ($file, %transform))
7054     {
7055         # Sanity checks.
7056         &am_file_error ($file, "blank line following trailing backslash:\n$_")
7057           if /\\$/;
7058         &am_file_error ($file, "comment following trailing backslash:\n$_")
7059           if /\\#/;
7060
7061         if (/^$/)
7062         {
7063             # Stick empty line before the incoming macro or rule.
7064             $spacing = "\n";
7065         }
7066         elsif (/$COMMENT_PATTERN/mso)
7067         {
7068             # Stick comments before the incoming macro or rule.
7069             $comment = "$_\n";
7070         }
7071
7072         # Handle inclusion of other files.
7073         elsif (/$INCLUDE_PATTERN/o)
7074         {
7075             if ($cond ne 'FALSE')
7076               {
7077                 my $file = ($is_am ? "$libdir/am/" : '') . $1;
7078                 # N-ary `.=' fails.
7079                 my ($com, $vars, $rules)
7080                   = file_contents_internal ($is_am, $file, %transform);
7081                 $comment .= $com;
7082                 $result_vars .= $vars;
7083                 $result_rules .= $rules;
7084               }
7085         }
7086
7087         # Handling the conditionals.
7088         elsif (/$IF_PATTERN/o)
7089           {
7090             $cond = cond_stack_if ($1, $2, $file);
7091           }
7092         elsif (/$ELSE_PATTERN/o)
7093           {
7094             $cond = cond_stack_else ($1, $2, $file);
7095           }
7096         elsif (/$ENDIF_PATTERN/o)
7097           {
7098             $cond = cond_stack_endif ($1, $2, $file);
7099           }
7100
7101         # Handling rules.
7102         elsif (/$RULE_PATTERN/mso)
7103         {
7104           # Separate relationship from optional actions: the first
7105           # `new-line tab" not preceded by backslash (continuation
7106           # line).
7107           # I'm quite shoked!  It seems that (\\\n|[^\n]) is not the
7108           # same as `([^\n]|\\\n)!!!  Don't swap it, it breaks.
7109           my $paragraph = $_;
7110           /^((?:\\\n|[^\n])*)(?:\n(\t.*))?$/som;
7111           my ($relationship, $actions) = ($1, $2 || '');
7112
7113           # Separate targets from dependencies: the first colon.
7114           $relationship =~ /^([^:]+\S+) *: *(.*)$/som;
7115           my ($targets, $dependencies) = ($1, $2);
7116           # Remove the escaped new lines.
7117           # I don't know why, but I have to use a tmp $flat_deps.
7118           my $flat_deps = &flatten ($dependencies);
7119           my @deps = split (' ', $flat_deps);
7120
7121           foreach (split (' ' , $targets))
7122             {
7123               # FIXME: We are not robust to people defining several targets
7124               # at once, only some of them being in %dependencies.
7125
7126               # Output only if not in FALSE.
7127               if (defined $dependencies{$_}
7128                   && $cond ne 'FALSE')
7129                 {
7130                   &depend ($_, @deps);
7131                   $actions{$_} .= $actions;
7132                 }
7133               else
7134                 {
7135                   # Free-lance dependency.  Output the rule for all the
7136                   # targets instead of one by one.
7137
7138                   # Work out all the conditions for which the target hasn't
7139                   # been defined
7140                   my @undefined_conds;
7141                   if (defined $target_conditional{$targets})
7142                     {
7143                       my @defined_conds = keys %{$target_conditional{$targets}};
7144                       @undefined_conds = invert_conditions(@defined_conds);
7145                     }
7146                   else
7147                     {
7148                       if (defined $targets{$targets})
7149                         {
7150                           # No conditions for which target hasn't been defined
7151                           @undefined_conds = ();
7152                         }
7153                       else
7154                         {
7155                           # Target hasn't been defined for any conditions
7156                           @undefined_conds = ("");
7157                         }
7158                     }
7159
7160                   if ($cond ne 'FALSE')
7161                     {
7162                       my $undefined_cond;
7163                       for $undefined_cond (@undefined_conds)
7164                       {
7165                           my $condparagraph = $paragraph;
7166                           $condparagraph =~ s/^/make_condition (@cond_stack, $undefined_cond)/gme;
7167                           $result_rules .= "$spacing$comment$condparagraph\n"
7168                               if rule_define ($targets, $is_am,
7169                                               "$cond $undefined_cond", $file);
7170                       }
7171                     }
7172                   $comment = $spacing = '';
7173                   last;
7174                 }
7175             }
7176         }
7177
7178         elsif (/$ASSIGNMENT_PATTERN/mso)
7179         {
7180             my ($var, $type, $val) = ($1, $2, $3);
7181             &am_file_error ($file, "macro `$var' with trailing backslash")
7182               if /\\$/;
7183
7184             # Accumulating variables must not be output.
7185             $var_comment{$var} .= "$spacing"
7186               if (!defined $var_comment{$var}
7187                   || substr ($var_comment{$var}, -1) ne "\n");
7188             $var_comment{$var} .= "$comment";
7189             macro_define ($var, $is_am, $type, $cond, $val, $file)
7190               if $cond ne 'FALSE';
7191             push (@var_list, $var);
7192
7193             # If the user has set some variables we were in charge
7194             # of (which is detected by the first reading of
7195             # `header-vars.am'), we must not output them.
7196             $result_vars .= "$spacing$comment$_\n"
7197               if $type ne '+' && $var_is_am{$var} && $cond ne 'FALSE';
7198
7199             $comment = $spacing = '';
7200         }
7201         else
7202         {
7203             # This isn't an error; it is probably some tokens which
7204             # configure is supposed to replace, such as `@SET-MAKE@',
7205             # or some part of a rule cut by an if/endif.
7206             if ($cond ne 'FALSE')
7207               {
7208                 s/^/make_condition (@cond_stack)/gme;
7209                 $result_rules .= "$spacing$comment$_\n";
7210               }
7211             $comment = $spacing = '';
7212         }
7213     }
7214
7215     if (join (' ', @saved_cond_stack) ne join (' ', @cond_stack))
7216     {
7217         if (@cond_stack)
7218         {
7219             &am_error ("unterminated conditionals: @cond_stack");
7220         }
7221         else
7222         {
7223             # FIXME: better error message here.
7224             &am_error ("conditionals not nested in include file");
7225         }
7226     }
7227
7228     return ($comment, $result_vars, $result_rules);
7229 }
7230
7231
7232 # $CONTENTS
7233 # &file_contents ($BASENAME, [%TRANSFORM])
7234 # ----------------------------------------
7235 # Return contents of a file from $libdir/am, automatically skipping
7236 # macros or rules which are already known.
7237 sub file_contents ($%)
7238 {
7239     my ($basename, %transform) = @_;
7240     my ($comments, $variables, $rules) =
7241       file_contents_internal (1, "$libdir/am/$basename.am", %transform);
7242     return "$comments$variables$rules";
7243 }
7244
7245
7246 # $REGEXP
7247 # &transform (%PAIRS)
7248 # -------------------
7249 # Foreach ($TOKEN, $VAL) in %PAIRS produce a replacement expression suitable
7250 # for file_contents which:
7251 #   - replaces @$TOKEN@ with $VALUE,
7252 #   - enables/disables ?$TOKEN?.
7253 sub transform (%)
7254 {
7255     my (%pairs) = @_;
7256     my $result = '';
7257
7258     while (my ($token, $val) = each %pairs)
7259     {
7260         $result .= "s/\Q%$token%\E/\Q$val\E/gm;";
7261         if ($val)
7262         {
7263             $result .= "s/\Q?$token?\E//gm;s/^.*\Q?!$token?\E.*\\n//gm;";
7264             $result .= "s/\Q%?$token%\E/TRUE/gm;";
7265         }
7266         else
7267         {
7268             $result .= "s/\Q?!$token?\E//gm;s/^.*\Q?$token?\E.*\\n//gm;";
7269             $result .= "s/\Q%?$token%\E/FALSE/gm;";
7270         }
7271     }
7272
7273     return $result;
7274 }
7275
7276
7277 # Find all variable prefixes that are used for install directories.  A
7278 # prefix `zar' qualifies iff:
7279 # * `zardir' is a variable.
7280 # * `zar_PRIMARY' is a variable.
7281 sub am_primary_prefixes
7282 {
7283     my ($primary, $can_dist, @prefixes) = @_;
7284
7285     my %valid = map { $_ => 0 } @prefixes;
7286     $valid{'EXTRA'} = 0;
7287     foreach my $varname (keys %var_value)
7288     {
7289         # Automake is allowed to define variables that look like they
7290         # are magic variables, such as INSTALL_DATA.
7291         next
7292           if $var_is_am{$varname};
7293
7294         if ($varname =~ /^(nobase_)?(dist_|nodist_)?(.*)_$primary$/)
7295         {
7296             my ($base, $dist, $X) = ($1 || '', $2 || '', $3 || '');
7297             if ($dist ne '' && ! $can_dist)
7298             {
7299                 # Note that a configure variable is always legitimate.
7300                 # It is natural to name such variables after the
7301                 # primary, so we explicitly allow it.
7302                 if (! defined $configure_vars{$varname})
7303                 {
7304                     &am_line_error ($varname,
7305                                     "invalid variable `$varname': `dist' is forbidden");
7306                 }
7307             }
7308             elsif (! defined $valid{$X} && ! &variable_defined ("${X}dir"))
7309             {
7310                 # Note that a configure variable is always legitimate.
7311                 # It is natural to name such variables after the
7312                 # primary, so we explicitly allow it.
7313                 if (! defined $configure_vars{$varname})
7314                 {
7315                     &am_line_error ($varname,
7316                                     "invalid variable `$varname'");
7317                 }
7318             }
7319             else
7320             {
7321                 # Ensure all extended prefixes are actually used.
7322                 $valid{"$base$dist$X"} = 1;
7323             }
7324         }
7325     }
7326
7327     return %valid;
7328 }
7329
7330 # Handle `where_HOW' variable magic.  Does all lookups, generates
7331 # install code, and possibly generates code to define the primary
7332 # variable.  The first argument is the name of the .am file to munge,
7333 # the second argument is the primary variable (eg HEADERS), and all
7334 # subsequent arguments are possible installation locations.  Returns
7335 # list of all values of all _HOW targets.
7336 #
7337 # FIXME: this should be rewritten to be cleaner.  It should be broken
7338 # up into multiple functions.
7339 #
7340 # Usage is: am_install_var (OPTION..., file, HOW, where...)
7341 sub am_install_var
7342 {
7343     my (@args) = @_;
7344
7345     my $do_require = 1;
7346     my $can_dist = 0;
7347     my $default_dist = 0;
7348     while (@args)
7349     {
7350         if ($args[0] eq '-noextra')
7351         {
7352             $do_require = 0;
7353         }
7354         elsif ($args[0] eq '-candist')
7355         {
7356             $can_dist = 1;
7357         }
7358         elsif ($args[0] eq '-defaultdist')
7359         {
7360             $default_dist = 1;
7361             $can_dist = 1;
7362         }
7363         elsif ($args[0] !~ /^-/)
7364         {
7365             last;
7366         }
7367         shift (@args);
7368     }
7369
7370     my ($file, $primary, @prefixes) = @args;
7371
7372     # Now that configure substitutions are allowed in where_HOW
7373     # variables, it is an error to actually define the primary.  We
7374     # allow `JAVA', as it is customarily used to mean the Java
7375     # interpreter.  This is but one of several Java hacks.  Similarly,
7376     # `PYTHON' is customarily used to mean the Python interpreter.
7377     &am_line_error ($primary, "`$primary' is an anachronism")
7378         if &variable_defined ($primary)
7379             && ($primary ne 'JAVA' && $primary ne 'PYTHON');
7380
7381
7382     # Look for misspellings.  It is an error to have a variable ending
7383     # in a "reserved" suffix whose prefix is unknown, eg
7384     # "bni_PROGRAMS".  However, unusual prefixes are allowed if a
7385     # variable of the same name (with "dir" appended) exists.  For
7386     # instance, if the variable "zardir" is defined, then
7387     # "zar_PROGRAMS" becomes valid.  This is to provide a little extra
7388     # flexibility in those cases which need it.
7389     my %valid = &am_primary_prefixes ($primary, $can_dist, @prefixes);
7390
7391     # If a primary includes a configure substitution, then the EXTRA_
7392     # form is required.  Otherwise we can't properly do our job.
7393     my $require_extra;
7394     my $warned_about_extra = 0;
7395
7396     my @used = ();
7397     my @result = ();
7398
7399     # True if the iteration is the first one.  Used for instance to
7400     # output parts of the associated file only once.
7401     my $first = 1;
7402     foreach my $X (sort keys %valid)
7403     {
7404         my $one_name = $X . '_' . $primary;
7405         next
7406           unless (&variable_defined ($one_name));
7407
7408         my $strip_subdir = 1;
7409         # If subdir prefix should be preserved, do so.
7410         if ($X =~ /^nobase_/)
7411           {
7412             $strip_subdir = 0;
7413             $X =~ s/^nobase_//;
7414           }
7415
7416         my $nodir_name = $X;
7417         # If files should be distributed, do so.
7418         my $dist_p = 0;
7419         if ($can_dist)
7420           {
7421             $dist_p = (($default_dist && $one_name !~ /^nodist_/)
7422                        || (! $default_dist && $one_name =~ /^dist_/));
7423             $nodir_name =~ s/^(dist|nodist)_//;
7424           }
7425
7426         # Append actual contents of where_PRIMARY variable to
7427         # result.
7428         foreach my $rcurs (&variable_value_as_list_recursive ($one_name, 'all'))
7429           {
7430             # Skip configure substitutions.  Possibly bogus.
7431             if ($rcurs =~ /^\@.*\@$/)
7432               {
7433                 if ($X eq 'EXTRA')
7434                   {
7435                     if (! $warned_about_extra)
7436                       {
7437                         $warned_about_extra = 1;
7438                         &am_line_error ($one_name,
7439                                         "`$one_name' contains configure substitution, but shouldn't");
7440                       }
7441                   }
7442                 # Check here to make sure variables defined in
7443                 # configure.ac do not imply that EXTRA_PRIMARY
7444                 # must be defined.
7445                 elsif (! defined $configure_vars{$one_name})
7446                   {
7447                     $require_extra = $one_name
7448                       if $do_require;
7449                   }
7450
7451                 next;
7452               }
7453
7454             push (@result, $rcurs);
7455           }
7456
7457         # A blatant hack: we rewrite each _PROGRAMS primary to include
7458         # EXEEXT.
7459         if ($primary eq 'PROGRAMS')
7460         {
7461             my @conds = variable_conditions_recursive ($one_name);
7462
7463             my @condvals;
7464             foreach my $cond (@conds)
7465             {
7466                 my @one_binlist = ();
7467                 my @condval = &variable_value_as_list_recursive ($one_name,
7468                                                        $cond);
7469                 foreach my $rcurs (@condval)
7470                 {
7471                     # Skip autoconf substs.  Also skip if the user
7472                     # already applied $(EXEEXT).
7473                     if ($rcurs =~ /^\@.*\@$/ || $rcurs =~ /\$\(EXEEXT\)$/)
7474                     {
7475                         push (@one_binlist, $rcurs);
7476                     }
7477                     else
7478                     {
7479                         push (@one_binlist, $rcurs . '$(EXEEXT)');
7480                     }
7481                 }
7482
7483                 push (@condvals, $cond);
7484                 push (@condvals, join (' ', @one_binlist));
7485             }
7486
7487             variable_delete ($one_name);
7488             while (@condvals)
7489             {
7490                 my $cond = shift (@condvals);
7491                 my @val = split (' ', shift (@condvals));
7492                 define_pretty_variable ($one_name, $cond, @val);
7493             }
7494         }
7495
7496         # "EXTRA" shouldn't be used when generating clean targets,
7497         # all, or install targets.
7498         if ($X eq 'EXTRA')
7499           {
7500             # We used to warn if EXTRA_FOO was defined uselessly,
7501             # but this was annoying.
7502             next;
7503           }
7504
7505         if ($X eq 'check')
7506           {
7507             push (@check, '$(' . $one_name . ')');
7508           }
7509         else
7510           {
7511             push (@used, '$(' . $one_name . ')');
7512           }
7513
7514         # Is this to be installed?
7515         my $install_p = $X ne 'noinst' && $X ne 'check';
7516
7517         # If so, with install-exec? (or install-data?).
7518         my $exec_p = (defined $exec_dir_p {$X}
7519                       ? $exec_dir_p {$X}
7520                       : ($X =~ /exec/));
7521
7522         # Singular form of $PRIMARY.
7523         (my $one_primary = $primary) =~ s/S$//;
7524         $output_rules .= &file_contents ($file,
7525                                          ('FIRST' => $first,
7526
7527                                           'PRIMARY'     => $primary,
7528                                           'ONE_PRIMARY' => $one_primary,
7529                                           'DIR'         => $X,
7530                                           'NDIR'        => $nodir_name,
7531                                           'BASE'        => $strip_subdir,
7532
7533                                           'EXEC'    => $exec_p,
7534                                           'INSTALL' => $install_p,
7535                                           'DIST'    => $dist_p));
7536
7537         $first = 0;
7538     }
7539
7540     # The JAVA variable is used as the name of the Java interpreter.
7541     # The PYTHON variable is used as the name of the Python interpreter.
7542     if (@used && $primary ne 'JAVA' && $primary ne 'PYTHON')
7543     {
7544         # Define it.
7545         define_pretty_variable ($primary, '', @used);
7546         $output_vars .= "\n";
7547     }
7548
7549     if ($require_extra && ! &variable_defined ('EXTRA_' . $primary))
7550     {
7551         &am_line_error ($require_extra,
7552                         "`$require_extra' contains configure substitution, but `EXTRA_$primary' not defined");
7553     }
7554
7555     # Push here because PRIMARY might be configure time determined.
7556     push (@all, '$(' . $primary . ')')
7557         if @used && $primary ne 'JAVA' && $primary ne 'PYTHON';
7558
7559     # Make the result unique.  This lets the user use conditionals in
7560     # a natural way, but still lets us program lazily -- we don't have
7561     # to worry about handling a particular object more than once.
7562     return uniq (sort @result);
7563 }
7564
7565
7566 ################################################################
7567
7568 # Each key in this hash is the name of a directory holding a
7569 # Makefile.in.  These variables are local to `is_make_dir'.
7570 my %make_dirs = ();
7571 my $make_dirs_set = 0;
7572
7573 sub is_make_dir
7574 {
7575     my ($dir) = @_;
7576     if (! $make_dirs_set)
7577     {
7578         foreach my $iter (@configure_input_files)
7579         {
7580             $make_dirs{dirname ($iter)} = 1;
7581         }
7582         # We also want to notice Makefile.in's.
7583         foreach my $iter (@other_input_files)
7584         {
7585             if ($iter =~ /Makefile\.in$/)
7586             {
7587                 $make_dirs{dirname ($iter)} = 1;
7588             }
7589         }
7590         $make_dirs_set = 1;
7591     }
7592     return defined $make_dirs{$dir};
7593 }
7594
7595 ################################################################
7596
7597 # This variable is local to the "require file" set of functions.
7598 my @require_file_paths = ();
7599
7600 # If a file name appears as a key in this hash, then it has already
7601 # been checked for.  This variable is local to the "require file"
7602 # functions.
7603 %require_file_found = ();
7604
7605 # See if we want to push this file onto dist_common.  This function
7606 # encodes the rules for deciding when to do so.
7607 sub maybe_push_required_file
7608 {
7609     my ($dir, $file, $fullfile) = @_;
7610
7611     if ($dir eq $relative_dir)
7612     {
7613         &push_dist_common ($file);
7614     }
7615     elsif ($relative_dir eq '.' && ! &is_make_dir ($dir))
7616     {
7617         # If we are doing the topmost directory, and the file is in a
7618         # subdir which does not have a Makefile, then we distribute it
7619         # here.
7620         &push_dist_common ($fullfile);
7621     }
7622 }
7623
7624
7625 # &require_file_internal ($IS_CONFIGURE, $LINE, $MYSTRICT, @FILES)
7626 # ----------------------------------------------------------------
7627 # Verify that the file must exist in the current directory.
7628 # $MYSTRICT is the strictness level at which this file becomes required.
7629 #
7630 # Must set require_file_paths before calling this function.
7631 # require_file_paths is set to hold a single directory (the one in
7632 # which the first file was found) before return.
7633 sub require_file_internal
7634 {
7635     my ($is_configure, $line, $mystrict, @files) = @_;
7636
7637     foreach my $file (@files)
7638     {
7639         my $fullfile;
7640         my $errdir;
7641         my $errfile;
7642         my $save_dir;
7643
7644         my $found_it = 0;
7645         my $dangling_sym = 0;
7646         foreach my $dir (@require_file_paths)
7647         {
7648             $fullfile = $dir . "/" . $file;
7649             $errdir = $dir unless $errdir;
7650
7651             # Use different name for "error filename".  Otherwise on
7652             # an error the bad file will be reported as eg
7653             # `../../install-sh' when using the default
7654             # config_aux_path.
7655             $errfile = $errdir . '/' . $file;
7656
7657             if (-l $fullfile && ! -f $fullfile)
7658             {
7659                 $dangling_sym = 1;
7660                 last;
7661             }
7662             elsif (-f $fullfile)
7663             {
7664                 $found_it = 1;
7665                 &maybe_push_required_file ($dir, $file, $fullfile);
7666                 $save_dir = $dir;
7667                 last;
7668             }
7669         }
7670
7671         # `--force-missing' only has an effect if `--add-missing' is
7672         # specified.
7673         if ($found_it && (! $add_missing || ! $force_missing))
7674         {
7675             # Prune the path list.
7676             @require_file_paths = $save_dir;
7677         }
7678         else
7679         {
7680             # If we've already looked for it, we're done.  You might
7681             # wonder why we don't do this before searching for the
7682             # file.  If we do that, then something like
7683             # AC_OUTPUT(subdir/foo foo) will fail to put foo.in into
7684             # DIST_COMMON.
7685             if (! $found_it)
7686             {
7687                 next if defined $require_file_found{$file};
7688                 $require_file_found{$file} = 1;
7689             }
7690
7691             if ($strictness >= $mystrict)
7692             {
7693                 if ($dangling_sym && $add_missing)
7694                 {
7695                     unlink ($fullfile);
7696                 }
7697
7698                 my $trailer = '';
7699                 my $suppress = 0;
7700
7701                 # Only install missing files according to our desired
7702                 # strictness level.
7703                 my $message = "required file `$errfile' not found";
7704                 if ($add_missing)
7705                 {
7706                     $suppress = 1;
7707
7708                     # Maybe run libtoolize.
7709                     my @syslist = ('libtoolize', '--automake');
7710                     push @syslist, '--copy'
7711                         if $copy_missing;
7712                     if ($seen_libtool
7713                         && grep ($_ eq $file, @libtoolize_files)
7714                         && system (@syslist))
7715                     {
7716                         $message = "installing `$errfile'";
7717                         $suppress = 0;
7718                         $trailer = "; cannot run `libtoolize': $!";
7719                     }
7720                     elsif (-f ("$libdir/$file"))
7721                     {
7722                         # Install the missing file.  Symlink if we
7723                         # can, copy if we must.  Note: delete the file
7724                         # first, in case it is a dangling symlink.
7725                         $message = "installing `$errfile'";
7726                         # Windows Perl will hang if we try to delete a
7727                         # file that doesn't exist.
7728                         unlink ($errfile) if -f $errfile;
7729                         if ($symlink_exists && ! $copy_missing)
7730                         {
7731                             if (! symlink ("$libdir/$file", $errfile))
7732                             {
7733                                 $suppress = 0;
7734                                 $trailer = "; error while making link: $!";
7735                             }
7736                         }
7737                         elsif (system ('cp', "$libdir/$file", $errfile))
7738                         {
7739                             $suppress = 0;
7740                             $trailer = "\n    error while copying";
7741                         }
7742                     }
7743
7744                     &maybe_push_required_file (dirname ($errfile),
7745                                                $file, $errfile);
7746
7747                     # Prune the path list.
7748                     @require_file_paths = &dirname ($errfile);
7749                 }
7750
7751                 # If --force-missing was specified, and we have
7752                 # actually found the file, then do nothing.
7753                 next
7754                     if $found_it && $force_missing;
7755
7756                 if ($suppress)
7757                 {
7758                     if ($is_configure)
7759                     {
7760                         # FIXME: allow actual file to be specified.
7761                         &am_conf_line_warning ($configure_ac, $line,
7762                                                "$message$trailer");
7763                     }
7764                     else
7765                     {
7766                         &am_line_warning ($line, "$message$trailer");
7767                     }
7768                 }
7769                 else
7770                 {
7771                     if ($is_configure)
7772                     {
7773                         # FIXME: allow actual file to be specified.
7774                         &am_conf_line_error ($configure_ac, $line,
7775                                              "$message$trailer");
7776                     }
7777                     else
7778                     {
7779                         &am_line_error ($line, "$message$trailer");
7780                     }
7781                 }
7782             }
7783         }
7784     }
7785 }
7786
7787 # Like require_file_with_line, but error messages refer to
7788 # configure.ac, not the current Makefile.am.
7789 sub require_file_with_conf_line
7790 {
7791     @require_file_paths = $relative_dir;
7792     &require_file_internal (1, @_);
7793 }
7794
7795 sub require_file_with_line
7796 {
7797     @require_file_paths = $relative_dir;
7798     &require_file_internal (0, @_);
7799 }
7800
7801 sub require_file
7802 {
7803     @require_file_paths = $relative_dir;
7804     &require_file_internal (0, '', @_);
7805 }
7806
7807 # Require an auxiliary file.
7808 # Looks in configuration path, as specified by AC_CONFIG_AUX_DIR.
7809 sub require_aux_file_with_line
7810 {
7811     my $from = shift;  # 1 for configure.ac, 0 for Makefile.am
7812     my $line = shift;
7813     @require_file_paths = @config_aux_path;
7814     &require_file_internal ($from, $line, @_);
7815     my $dir = $require_file_paths[0];
7816     # &require_file_internal pruned the file path to the
7817     # exact directory where the file is lying.  Update
7818     # @config_aux_path to speed up future uses.
7819     @config_aux_path = @require_file_paths;
7820      # Avoid unsightly '/.'s.
7821     $config_aux_dir = '$(top_srcdir)' . ($dir eq '.' ? "" : "/$dir");
7822 }
7823
7824 # Assumes that the line number is in Makefile.am.
7825 sub require_conf_file_with_line
7826 {
7827     &require_aux_file_with_line (0, @_);
7828 }
7829
7830 # File required from a Makefile.am.  No line number available.
7831 sub require_conf_file
7832 {
7833     &require_conf_file_with_line ('', @_);
7834 }
7835
7836 # Assumes that the line number is in configure.ac.
7837 sub require_conf_file_with_conf_line
7838 {
7839     &require_aux_file_with_line (1, @_);
7840 }
7841
7842 # Require a file that is also required by Autoconf.  No line number available.
7843 sub require_config_file
7844 {
7845     &require_conf_file_with_conf_line ('', @_);
7846 }
7847
7848 ################################################################
7849
7850 # &require_build_directory ($DIRECTORY)
7851 # ------------------------------------
7852 # Emit rules to create $DIRECTORY if needed, and return
7853 # the file that any target requiring this directory should be made
7854 # dependent upon.
7855 sub require_build_directory ($)
7856 {
7857     my $directory = shift;
7858     my $dirstamp = "$directory/.dirstamp";
7859
7860     # Don't emit the rule twice.
7861     if (! defined $directory_map{$directory})
7862     {
7863         $directory_map{$directory} = 1;
7864
7865         # Directory must be removed by `make distclean'.
7866         $compile_clean_files{$dirstamp} = $DIST_CLEAN;
7867
7868         $output_rules .= ("$dirstamp:\n"
7869                           . "\t\@\$(mkinstalldirs) $directory\n"
7870                           . "\t\@: > $dirstamp\n");
7871     }
7872
7873     return $dirstamp;
7874 }
7875
7876 # &require_build_directory_maybe ($FILE)
7877 # --------------------------------------
7878 # If $FILE lies in a subdirectory, emit a rule to create this
7879 # directory and return the file that $FILE should be made
7880 # dependent upon.  Otherwise, just return the empty string.
7881 sub require_build_directory_maybe ($)
7882 {
7883     my $file = shift;
7884     my $directory = dirname ($file);
7885
7886     if ($directory ne '.')
7887     {
7888         return &require_build_directory ($directory);
7889     }
7890     else
7891     {
7892         return '';
7893     }
7894 }
7895
7896 ################################################################
7897
7898 # Push a list of files onto dist_common.
7899 sub push_dist_common
7900 {
7901     &prog_error ("push_dist_common run after handle_dist")
7902         if $handle_dist_run;
7903     macro_define ('DIST_COMMON', 1, '+', '', join (' ', @_), '');
7904 }
7905
7906
7907 # Set strictness.
7908 sub set_strictness
7909 {
7910     $strictness_name = $_[0];
7911     if ($strictness_name eq 'gnu')
7912     {
7913         $strictness = $GNU;
7914     }
7915     elsif ($strictness_name eq 'gnits')
7916     {
7917         $strictness = $GNITS;
7918     }
7919     elsif ($strictness_name eq 'foreign')
7920     {
7921         $strictness = $FOREIGN;
7922     }
7923     else
7924     {
7925         die "$me: level `$strictness_name' not recognized\n";
7926     }
7927 }
7928
7929
7930 ################################################################
7931
7932 # Ensure a file exists.
7933 sub create
7934 {
7935     my ($file) = @_;
7936
7937     my $touch = new IO::File (">> $file");
7938     $touch->close;
7939 }
7940
7941 # Glob something.  Do this to avoid indentation screwups everywhere we
7942 # want to glob.  Gross!
7943 sub my_glob
7944 {
7945     my ($pat) = @_;
7946     return <${pat}>;
7947 }
7948
7949 # Remove one level of brackets and strip leading spaces,
7950 # as does m4 to function arguments.
7951 sub unquote_m4_arg
7952 {
7953     $_ = shift;
7954     s/^\s*//;
7955
7956     my @letters = split //;
7957     my @result = ();
7958     my $depth = 0;
7959
7960     foreach (@letters)
7961     {
7962         if ($_ eq '[')
7963         {
7964             ++$depth;
7965             next if $depth == 1;
7966         }
7967         elsif ($_ eq ']')
7968         {
7969             --$depth;
7970             next if $depth == 0;
7971             # don't count orphan right brackets
7972             $depth = 0 if $depth < 0;
7973         }
7974         push @result, $_;
7975     }
7976     return join '', @result;
7977 }
7978
7979 ################################################################
7980
7981 # am_print_error ($LEADER, @ARGS)
7982 # -------------------------------
7983 # Do the work of printing the error message.  Join @ARGS with spaces,
7984 # then split at newlines and add $LEADER to each line.  Uses `warn' to
7985 # print message.
7986 sub am_print_error
7987 {
7988     my ($leader, @args) = @_;
7989     my $text = join (' ', @args);
7990     @args = split ("\n", $text);
7991     $text = $leader . join ("\n" . $leader, @args) . "\n";
7992     warn $text;
7993 }
7994
7995 # Print an error message and set exit status.
7996 sub am_error
7997 {
7998     am_print_error ("$me: ${am_file}.am: ", @_);
7999     $exit_status = 1;
8000 }
8001
8002 # am_file_error ($FILE, @ARGS)
8003 # ----------------------------
8004 sub am_file_error
8005 {
8006     my ($file, @args) = @_;
8007
8008     am_print_error ("$file: ", @args);
8009     $exit_status = 1;
8010 }
8011
8012 sub am_line_error
8013 {
8014     my ($symbol, @args) = @_;
8015
8016     if ($symbol && "$symbol" ne '-1')
8017     {
8018         my $file = "${am_file}.am";
8019
8020         if ($symbol =~ /^\d+$/)
8021         {
8022             # SYMBOL is a line number, so just add the colon.
8023             $file .= ':' . $symbol;
8024         }
8025         elsif (defined $var_line{$symbol})
8026         {
8027             # SYMBOL is a variable defined in Makefile.am, so add the
8028             # line number we saved from there.
8029             $file .= ':' . $var_line{$symbol};
8030         }
8031         elsif (defined $configure_vars{$symbol})
8032         {
8033             # SYMBOL is a variable defined in configure.ac, so add the
8034             # appropriate line number.
8035             $file = $configure_vars{$symbol};
8036         }
8037         else
8038         {
8039             # Couldn't find the line number.
8040         }
8041
8042         am_print_error ("$file: ", @args);
8043         $exit_status = 1;
8044     }
8045     else
8046     {
8047         &am_error (@args);
8048     }
8049 }
8050
8051 # Like am_error, but while scanning configure.ac.
8052 sub am_conf_error
8053 {
8054     # FIXME: can run in subdirs.
8055     am_print_error ("$me: $configure_ac: ", @_);
8056     $exit_status = 1;
8057 }
8058
8059 # Error message with line number referring to configure.ac.
8060 sub am_conf_line_error
8061 {
8062     my ($file, $line, @args) = @_;
8063
8064     if ($line)
8065     {
8066         am_print_error ("$file: $line: ", @args);
8067         $exit_status = 1;
8068     }
8069     else
8070     {
8071         &am_conf_error (@args);
8072     }
8073 }
8074
8075 # Warning message with line number referring to configure.ac.
8076 # Does not affect exit_status
8077 sub am_conf_line_warning
8078 {
8079     my $saved_exit_status = $exit_status;
8080     my $sig = $SIG{'__WARN__'};
8081     $SIG{'__WARN__'} = 'DEFAULT';
8082     am_conf_line_error (@_);
8083     $exit_status = $saved_exit_status;
8084     $SIG{'__WARN__'} = $sig;
8085 }
8086
8087 # Like am_line_error, but doesn't affect exit status.
8088 sub am_line_warning
8089 {
8090     my $saved_exit_status = $exit_status;
8091     my $sig = $SIG{'__WARN__'};
8092     $SIG{'__WARN__'} = 'DEFAULT';
8093     am_line_error (@_);
8094     $exit_status = $saved_exit_status;
8095     $SIG{'__WARN__'} = $sig;
8096 }
8097
8098 # Tell user where our aclocal.m4 is, but only once.
8099 sub keyed_aclocal_warning
8100 {
8101     my ($key) = @_;
8102     warn "$me: macro `$key' can be generated by `aclocal'\n";
8103 }
8104
8105 # Print usage information.
8106 sub usage
8107 {
8108     print <<EOF;
8109 Usage: $0 [OPTION] ... [Makefile]...
8110
8111 Generate Makefile.in for configure from Makefile.am.
8112
8113 Operation modes:
8114       --help             print this help, then exit
8115       --version          print version number, then exit
8116   -v, --verbose          verbosely list files processed
8117   -o, --output-dir=DIR   put generated Makefile.in's into DIR
8118       --no-force         only update Makefile.in's that are out of date
8119
8120 Dependency tracking:
8121   -i, --ignore-deps      disable dependency tracking code
8122       --include-deps     enable dependency tracking code
8123
8124 Flavors:
8125       --cygnus           assume program is part of Cygnus-style tree
8126       --foreign          set strictness to foreign
8127       --gnits            set strictness to gnits
8128       --gnu              set strictness to gnu
8129
8130 Library files:
8131   -a, --add-missing      add missing standard files to package
8132       --libdir=DIR       directory storing library files
8133   -c, --copy             with -a, copy missing files (default is symlink)
8134   -f, --force-missing    force update of standard files
8135 EOF
8136
8137     my ($last, @lcomm);
8138     $last = '';
8139     foreach my $iter (sort ((@common_files, @common_sometimes)))
8140     {
8141         push (@lcomm, $iter) unless $iter eq $last;
8142         $last = $iter;
8143     }
8144
8145     my @four;
8146     print "\nFiles which are automatically distributed, if found:\n";
8147     format USAGE_FORMAT =
8148   @<<<<<<<<<<<<<<<<   @<<<<<<<<<<<<<<<<   @<<<<<<<<<<<<<<<<   @<<<<<<<<<<<<<<<<
8149   $four[0],           $four[1],           $four[2],           $four[3]
8150 .
8151     $~ = "USAGE_FORMAT";
8152
8153     my $cols = 4;
8154     my $rows = int(@lcomm / $cols);
8155     my $rest = @lcomm % $cols;
8156
8157     if ($rest)
8158     {
8159         $rows++;
8160     }
8161     else
8162     {
8163         $rest = $cols;
8164     }
8165
8166     for (my $y = 0; $y < $rows; $y++)
8167     {
8168         @four = ("", "", "", "");
8169         for (my $x = 0; $x < $cols; $x++)
8170         {
8171             last if $y + 1 == $rows && $x == $rest;
8172
8173             my $idx = (($x > $rest)
8174                        ?  ($rows * $rest + ($rows - 1) * ($x - $rest))
8175                        : ($rows * $x));
8176
8177             $idx += $y;
8178             $four[$x] = $lcomm[$idx];
8179         }
8180         write;
8181     }
8182
8183     print "\nReport bugs to <bug-automake\@gnu.org>.\n";
8184
8185     exit 0;
8186 }
8187
8188 # &version ()
8189 # -----------
8190 # Print version information
8191 sub version ()
8192 {
8193   print <<EOF;
8194 automake (GNU $PACKAGE) $VERSION
8195 Written by Tom Tromey <tromey\@cygnus.com>.
8196
8197 Copyright 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001
8198 Free Software Foundation, Inc.
8199 This is free software; see the source for copying conditions.  There is NO
8200 warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
8201 EOF
8202   exit 0;
8203 }