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