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