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