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