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