* automake.in ($ac_output_location): Replace with...
[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_CONFIG_FILES/AC_OUTPUT without Makefile.am's,
379 # and their outputs.
380 my @other_input_files = ();
381 # Where the last AC_CONFIG_FILES/AC_OUTPUT appears.
382 my $ac_config_files_location;
383
384 # List of directories to search for configure-required files.  This
385 # can be set by AC_CONFIG_AUX_DIR.
386 my @config_aux_path = ('.', '..', '../..');
387 my $config_aux_dir = '';
388 my $config_aux_dir_set_in_configure_in = 0;
389
390 # Whether AM_GNU_GETTEXT has been seen in configure.ac.
391 my $seen_gettext = 0;
392 # Where AM_GNU_GETTEXT appears.
393 my $ac_gettext_location;
394
395 # TRUE if AC_PROG_LEX or AM_PROG_LEX were seen.
396 my $seen_prog_lex = 0;
397
398 # TRUE if we've seen AC_CANONICAL_(HOST|SYSTEM).  The presence of
399 # AC_CHECK_TOOL also sets this.
400 my $seen_canonical = 0;
401
402 # TRUE if we've seen AC_PROG_LIBTOOL.
403 my $seen_libtool = 0;
404 my $libtool_location;
405
406 # TRUE if we've seen AM_MAINTAINER_MODE.
407 my $seen_maint_mode = 0;
408
409 # Actual version we've seen.
410 my $package_version = '';
411
412 # Where version is defined.
413 my $package_version_location;
414
415 # Where AM_PATH_LISPDIR appears.
416 my $am_lispdir_location;
417
418 # Where AM_PATH_PYTHON appears.
419 my $pythondir_location;
420
421 # TRUE if we've seen AC_ENABLE_MULTILIB.
422 my $seen_multilib = 0;
423
424 # TRUE if we've seen AM_PROG_CC_C_O
425 my $seen_cc_c_o = 0;
426
427 # TRUE if we've seen AM_INIT_AUTOMAKE.
428 my $seen_init_automake = 0;
429
430 # Hash table of discovered configure substitutions.  Keys are names,
431 # values are `FILE:LINE' strings which are used by error message
432 # generation.
433 my %configure_vars = ();
434
435 # This is used to keep track of which variable definitions we are
436 # scanning.  It is only used in certain limited ways, but it has to be
437 # global.  It is declared just for documentation purposes.
438 my %vars_scanned = ();
439
440 # TRUE if --cygnus seen.
441 my $cygnus_mode = 0;
442
443 # Hash table of AM_CONDITIONAL variables seen in configure.
444 my %configure_cond = ();
445
446 # This maps extensions onto language names.
447 my %extension_map = ();
448
449 # List of the DIST_COMMON files we discovered while reading
450 # configure.in
451 my $configure_dist_common = '';
452
453 # This maps languages names onto objects.
454 my %languages = ();
455
456 # List of targets we must always output.
457 # FIXME: Complete, and remove falsely required targets.
458 my %required_targets =
459   (
460    'all'          => 1,
461    'dvi'          => 1,
462    'info'         => 1,
463    'install-info' => 1,
464    'install'      => 1,
465    'install-data' => 1,
466    'install-exec' => 1,
467    'uninstall'    => 1,
468
469    # FIXME: Not required, temporary hacks.
470    # Well, actually they are sort of required: the -recursive
471    # targets will run them anyway...
472    'dvi-am'          => 1,
473    'info-am'         => 1,
474    'install-data-am' => 1,
475    'install-exec-am' => 1,
476    'installcheck-am' => 1,
477    'uninstall-am' => 1,
478
479    'install-man' => 1,
480   );
481
482 \f
483
484 ################################################################
485
486 ## ------------------------------------------ ##
487 ## Variables reset by &initialize_per_input.  ##
488 ## ------------------------------------------ ##
489
490 # Basename and relative dir of the input file.
491 my $am_file_name;
492 my $am_relative_dir;
493
494 # Same but wrt Makefile.in.
495 my $in_file_name;
496 my $relative_dir;
497
498 # These two variables are used when generating each Makefile.in.
499 # They hold the Makefile.in until it is ready to be printed.
500 my $output_rules;
501 my $output_vars;
502 my $output_trailer;
503 my $output_all;
504 my $output_header;
505
506 # Suffixes found during a run.
507 my @suffixes;
508
509 # Handling the variables.
510 #
511 # For a $VAR:
512 # - $var_value{$VAR}{$COND} is its value associated to $COND,
513 # - $var_location{$VAR} is where it was defined,
514 # - $var_comment{$VAR} are the comments associated to it.
515 # - $var_type{$VAR} is how it has been defined (`', `+', or `:'),
516 # - $var_is_am{$VAR} is true if the variable is owned by Automake.
517 my %var_value;
518 my %var_location;
519 my %var_comment;
520 my %var_type;
521 my %var_is_am;
522
523 # This holds a 1 if a particular variable was examined.
524 my %content_seen;
525
526 # This holds the names which are targets.  These also appear in
527 # %contents.
528 my %targets;
529
530 # Same as %VAR_VALUE, but for targets.
531 my %target_conditional;
532
533 # This is the conditional stack.
534 my @cond_stack;
535
536 # This holds the set of included files.
537 my @include_stack;
538
539 # This holds a list of directories which we must create at `dist'
540 # time.  This is used in some strange scenarios involving weird
541 # AC_OUTPUT commands.
542 my %dist_dirs;
543
544 # List of dependencies for the obvious targets.
545 my @all;
546 my @check;
547 my @check_tests;
548
549 # Holds the dependencies of targets which dependencies are factored.
550 # Typically, `.PHONY' will appear in plenty of *.am files, but must
551 # be output once.  Arguably all pure dependencies could be subject
552 # to this factorization, but it is not unpleasant to have paragraphs
553 # in Makefile: keeping related stuff altogether.
554 my %dependencies;
555
556 # Holds the factored actions.  Tied to %DEPENDENCIES, i.e., filled
557 # only when keys exists in %DEPENDENCIES.
558 my %actions;
559
560 # A list of files deleted by `maintainer-clean'.
561 my @maintainer_clean_files;
562
563 # Keys in this hash table are object files or other files in
564 # subdirectories which need to be removed.  This only holds files
565 # which are created by compilations.  The value in the hash indicates
566 # when the file should be removed.
567 my %compile_clean_files;
568
569 # Value of `$(SOURCES)', used by tags.am.
570 my @sources;
571 # Sources which go in the distribution.
572 my @dist_sources;
573
574 # This hash maps object file names onto their corresponding source
575 # file names.  This is used to ensure that each object is created
576 # by a single source file.
577 my %object_map;
578
579 # This keeps track of the directories for which we've already
580 # created `.dirstamp' code.
581 my %directory_map;
582
583 # All .P files.
584 my %dep_files;
585
586 # Strictness levels.
587 my $strictness;
588 my $strictness_name;
589
590 # Options from AUTOMAKE_OPTIONS.
591 my %options;
592
593 # Whether or not dependencies are handled.  Can be further changed
594 # in handle_options.
595 my $use_dependencies;
596
597 # This is a list of all targets to run during "make dist".
598 my @dist_targets;
599
600 # Keys in this hash are the basenames of files which must depend
601 # on ansi2knr.
602 my %de_ansi_files;
603
604 # This maps the source extension of a suffix rule to its
605 # corresponding output extension.
606 my %suffix_rules;
607
608 # This is the name of the redirect `all' target to use.
609 my $all_target;
610
611 # This keeps track of which extensions we've seen (that we care
612 # about).
613 my %extension_seen;
614
615 # This is random scratch space for the language finish functions.
616 # Don't randomly overwrite it; examine other uses of keys first.
617 my %language_scratch;
618
619 # We keep track of which objects need special (per-executable)
620 # handling on a per-language basis.
621 my %lang_specific_files;
622
623 # This is set when `handle_dist' has finished.  Once this happens,
624 # we should no longer push on dist_common.
625 my $handle_dist_run;
626
627 # Used to store a set of linkers needed to generate the sources currently
628 # under consideration.
629 my %linkers_used;
630
631 # True if we need `LINK' defined.  This is a hack.
632 my $need_link;
633
634 # This is the list of such variables to output.
635 # FIXME: Might be useless actually.
636 my @var_list;
637
638 # Was get_object_extension run?
639 # FIXME: This is a hack. a better switch should be found.
640 my $get_object_extension_was_run;
641
642 # Contains a stack of `from' parts of variable substitutions currently in
643 # force.
644 my @substfroms;
645
646 # Contains a stack of `to' parts of variable substitutions currently in
647 # force.
648 my @substtos;
649
650 # Associates a variable name, together with a list of substitutions to be
651 # performed on it, with a number.  Used to provide unique names for generated
652 # variables.
653 my %substnums = ();
654
655 ## --------------------------------- ##
656 ## Forward subroutine declarations.  ##
657 ## --------------------------------- ##
658 sub register_language (%);
659 sub file_contents_internal ($$%);
660 sub define_objects_from_sources ($$$$$$$);
661
662
663 # &initialize_per_input ()
664 # ------------------------
665 # (Re)-Initialize per-Makefile.am variables.
666 sub initialize_per_input ()
667 {
668     $am_file_name = '';
669     $am_relative_dir = '';
670
671     $in_file_name = '';
672     $relative_dir = '';
673
674     $output_rules = '';
675     $output_vars = '';
676     $output_trailer = '';
677     $output_all = '';
678     $output_header = '';
679
680     @suffixes = ();
681
682     %var_value = ();
683     %var_location = ();
684     %var_comment = ();
685     %var_type = ();
686     %var_is_am = ();
687
688     %content_seen = ();
689
690     %targets = ();
691
692     %target_conditional = ();
693
694     @cond_stack = ();
695
696     @include_stack = ();
697
698     $relative_dir = '';
699
700     $am_relative_dir = '';
701
702     %dist_dirs = ();
703
704     @all = ();
705     @check = ();
706     @check_tests = ();
707
708     %dependencies =
709       (
710        # Texinfoing.
711        'dvi'      => [],
712        'dvi-am'   => [],
713        'info'     => [],
714        'info-am'  => [],
715
716        # Installing/uninstalling.
717        'install-data-am'      => [],
718        'install-exec-am'      => [],
719        'uninstall-am'         => [],
720
721        'install-man'          => [],
722        'uninstall-man'        => [],
723
724        'install-info'         => [],
725        'install-info-am'      => [],
726        'uninstall-info'       => [],
727
728        'installcheck-am'      => [],
729
730        # Cleaning.
731        'clean-am'             => [],
732        'mostlyclean-am'       => [],
733        'maintainer-clean-am'  => [],
734        'distclean-am'         => [],
735        'clean'                => [],
736        'mostlyclean'          => [],
737        'maintainer-clean'     => [],
738        'distclean'            => [],
739
740        # Tarballing.
741        'dist-all'             => [],
742
743        # Phoning.
744        '.PHONY'               => []
745       );
746     %actions = ();
747
748     @maintainer_clean_files = ();
749
750     @sources = ();
751     @dist_sources = ();
752
753     %object_map = ();
754
755     %directory_map = ();
756
757     %dep_files = ();
758
759     $strictness = $default_strictness;
760     $strictness_name = $default_strictness_name;
761
762     %options = ();
763
764     $use_dependencies = $cmdline_use_dependencies;
765
766     @dist_targets = ();
767
768     %de_ansi_files = ();
769
770     %suffix_rules = ();
771
772     $all_target = '';
773
774     %extension_seen = ();
775
776     %language_scratch = ();
777
778     %lang_specific_files = ();
779
780     $handle_dist_run = 0;
781
782     $need_link = 0;
783
784     @var_list = ();
785
786     $get_object_extension_was_run = 0;
787
788     %compile_clean_files = ();
789 }
790
791
792 ################################################################
793
794 # Initialize our list of languages that are internally supported.
795
796 # C.
797 register_language ('name' => 'c',
798                    'Name' => 'C',
799                    'config_vars' => ['CC'],
800                    'ansi' => 1,
801                    'autodep' => '',
802                    'flags' => 'CFLAGS',
803                    'compiler' => 'COMPILE',
804                    'compile' => '$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS)',
805                    'lder' => 'CCLD',
806                    'ld' => '$(CC)',
807                    'linker' => 'LINK',
808                    'link' => '$(CCLD) $(AM_CFLAGS) $(CFLAGS) $(AM_LDFLAGS) $(LDFLAGS) -o $@',
809                    'compile_flag' => '-c',
810                    'extensions' => ['c'],
811                    '_finish' => \&lang_c_finish);
812
813 # C++.
814 register_language ('name' => 'cxx',
815                    'Name' => 'C++',
816                    'config_vars' => ['CXX'],
817                    'linker' => 'CXXLINK',
818                    'link' => '$(CXXLD) $(AM_CXXFLAGS) $(CXXFLAGS) $(AM_LDFLAGS) $(LDFLAGS) -o $@',
819                    'autodep' => 'CXX',
820                    'flags' => 'CXXFLAGS',
821                    'compile' => '$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS)',
822                    'compiler' => 'CXXCOMPILE',
823                    'compile_flag' => '-c',
824                    'output_flag' => '-o',
825                    'lder' => 'CXXLD',
826                    'ld' => '$(CXX)',
827                    'pure' => 1,
828                    'extensions' => ['c++', 'cc', 'cpp', 'cxx', 'C']);
829
830 # Objective C.
831 register_language ('name' => 'objc',
832                    'Name' => 'Objective C',
833                    'config_vars' => ['OBJC'],
834                    'linker' => 'OBJCLINK',,
835                    'link' => '$(OBJCLD) $(AM_OBJCFLAGS) $(OBJCFLAGS) $(AM_LDFLAGS) $(LDFLAGS) -o $@',
836                    'autodep' => 'OBJC',
837                    'flags' => 'OBJCFLAGS',
838                    'compile' => '$(OBJC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_OBJCFLAGS) $(OBJCFLAGS)',
839                    'compiler' => 'OBJCCOMPILE',
840                    'compile_flag' => '-c',
841                    'output_flag' => '-o',
842                    'lder' => 'OBJCLD',
843                    'ld' => '$(OBJC)',
844                    'pure' => 1,
845                    'extensions' => ['m']);
846
847 # Headers.
848 register_language ('name' => 'header',
849                    'Name' => 'Header',
850                    'extensions' => ['h', 'H', 'hxx', 'h++', 'hh', 'hpp', 'inc'],
851                    # Nothing to do.
852                    '_finish' => sub { });
853
854 # Yacc (C & C++).
855 register_language ('name' => 'yacc',
856                    'Name' => 'Yacc',
857                    'config_vars' => ['YACC'],
858                    'flags' => 'YFLAGS',
859                    'define_flag' => 0,
860                    'compile' => '$(YACC) $(YFLAGS) $(AM_YFLAGS)',
861                    'compiler' => 'YACCCOMPILE',
862                    'extensions' => ['y'],
863                    'rule_file' => 'yacc',
864                    '_finish' => \&lang_yacc_finish,
865                    '_target_hook' => \&lang_yacc_target_hook);
866 register_language ('name' => 'yaccxx',
867                    'Name' => 'Yacc (C++)',
868                    'config_vars' => ['YACC'],
869                    'rule_file' => 'yacc',
870                    'flags' => 'YFLAGS',
871                    'define_flag' => 0,
872                    'compiler' => 'YACCCOMPILE',
873                    'compile' => '$(YACC) $(YFLAGS) $(AM_YFLAGS)',
874                    'extensions' => ['y++', 'yy', 'yxx', 'ypp'],
875                    '_finish' => \&lang_yacc_finish,
876                    '_target_hook' => \&lang_yacc_target_hook);
877
878 # Lex (C & C++).
879 register_language ('name' => 'lex',
880                    'Name' => 'Lex',
881                    'config_vars' => ['LEX'],
882                    'rule_file' => 'lex',
883                    'flags' => 'LFLAGS',
884                    'define_flag' => 0,
885                    'compile' => '$(LEX) $(LFLAGS) $(AM_LFLAGS)',
886                    'compiler' => 'LEXCOMPILE',
887                    'extensions' => ['l'],
888                    '_finish' => \&lang_lex_finish);
889 register_language ('name' => 'lexxx',
890                    'Name' => 'Lex (C++)',
891                    'config_vars' => ['LEX'],
892                    'rule_file' => 'lex',
893                    'flags' => 'LFLAGS',
894                    'define_flag' => 0,
895                    'compile' => '$(LEX) $(LFLAGS) $(AM_LFLAGS)',
896                    'compiler' => 'LEXCOMPILE',
897                    'extensions' => ['l++', 'll', 'lxx', 'lpp'],
898                    '_finish' => \&lang_lex_finish);
899
900 # Assembler.
901 register_language ('name' => 'asm',
902                    'Name' => 'Assembler',
903                    'config_vars' => ['AS', 'ASFLAGS'],
904
905                    'flags' => 'ASFLAGS',
906                    # Users can set AM_ASFLAGS to includes DEFS, INCLUDES,
907                    # or anything else required.  They can also set AS.
908                    'compile' => '$(AS) $(AM_ASFLAGS) $(ASFLAGS)',
909                    'compiler' => 'ASCOMPILE',
910                    'compile_flag' => '-c',
911                    'extensions' => ['s', 'S'],
912
913                    # With assembly we still use the C linker.
914                    '_finish' => \&lang_c_finish);
915
916 # Fortran 77
917 register_language ('name' => 'f77',
918                    'Name' => 'Fortran 77',
919                    'linker' => 'F77LINK',
920                    'link' => '$(F77LD) $(AM_FFLAGS) $(FFLAGS) $(AM_LDFLAGS) $(LDFLAGS) -o $@',
921                    'flags' => 'FFLAGS',
922                    'compile' => '$(F77) $(AM_FFLAGS) $(FFLAGS)',
923                    'compiler' => 'F77COMPILE',
924                    'compile_flag' => '-c',
925                    'output_flag' => '-o',
926                    'lder' => 'F77LD',
927                    'ld' => '$(F77)',
928                    'pure' => 1,
929                    'extensions' => ['f', 'for', 'f90']);
930
931 # Preprocessed Fortran 77
932 #
933 # The current support for preprocessing Fortran 77 just involves
934 # passing `$(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS)
935 # $(CPPFLAGS)' as additional flags to the Fortran 77 compiler, since
936 # this is how GNU Make does it; see the `GNU Make Manual, Edition 0.51
937 # for `make' Version 3.76 Beta' (specifically, from info file
938 # `(make)Catalogue of Rules').
939 #
940 # A better approach would be to write an Autoconf test
941 # (i.e. AC_PROG_FPP) for a Fortran 77 preprocessor, because not all
942 # Fortran 77 compilers know how to do preprocessing.  The Autoconf
943 # macro AC_PROG_FPP should test the Fortran 77 compiler first for
944 # preprocessing capabilities, and then fall back on cpp (if cpp were
945 # available).
946 register_language ('name' => 'ppf77',
947                    'Name' => 'Preprocessed Fortran 77',
948                    'config_vars' => ['F77'],
949                    'linker' => 'F77LINK',
950                    'link' => '$(F77LD) $(AM_FFLAGS) $(FFLAGS) $(AM_LDFLAGS) $(LDFLAGS) -o $@',
951                    'lder' => 'F77LD',
952                    'ld' => '$(F77)',
953                    'flags' => 'FFLAGS',
954                    'compiler' => 'PPF77COMPILE',
955                    'compile' => '$(F77) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_FFLAGS) $(FFLAGS)',
956                    'compile_flag' => '-c',
957                    'output_flag' => '-o',
958                    'pure' => 1,
959                    'extensions' => ['F']);
960
961 # Ratfor.
962 register_language ('name' => 'ratfor',
963                    'Name' => 'Ratfor',
964                    'config_vars' => ['F77'],
965                    'linker' => 'F77LINK',
966                    'link' => '$(F77LD) $(AM_FFLAGS) $(FFLAGS) $(AM_LDFLAGS) $(LDFLAGS) -o $@',
967                    'lder' => 'F77LD',
968                    'ld' => '$(F77)',
969                    'flags' => 'RFLAGS',
970                    # FIXME also FFLAGS.
971                    'compile' => '$(F77) $(AM_FFLAGS) $(FFLAGS) $(AM_RFLAGS) $(RFLAGS)',
972                    'compiler' => 'RCOMPILE',
973                    'compile_flag' => '-c',
974                    'output_flag' => '-o',
975                    'pure' => 1,
976                    'extensions' => ['r']);
977
978 # Java via gcj.
979 register_language ('name' => 'java',
980                    'Name' => 'Java',
981                    'config_vars' => ['GCJ'],
982                    'linker' => 'GCJLINK',
983                    'link' => '$(GCJLD) $(AM_GCJFLAGS) $(GCJFLAGS) $(AM_LDFLAGS) $(LDFLAGS) -o $@',
984                    'autodep' => 'GCJ',
985                    'flags' => 'GCJFLAGS',
986                    'compile' => '$(GCJ) $(AM_GCJFLAGS) $(GCJFLAGS)',
987                    'compiler' => 'GCJCOMPILE',
988                    'compile_flag' => '-c',
989                    'output_flag' => '-o',
990                    'lder' => 'GCJLD',
991                    'ld' => '$(GCJ)',
992                    'pure' => 1,
993                    'extensions' => ['java', 'class', 'zip', 'jar']);
994
995 ################################################################
996
997 # Parse command line.
998 &parse_arguments;
999
1000 # Do configure.ac scan only once.
1001 &scan_autoconf_files;
1002
1003 die "$me: no `Makefile.am' found or specified\n"
1004     if ! @input_files;
1005
1006 # Now do all the work on each file.
1007 # This guy must be local otherwise it's private to the loop.
1008 use vars '$am_file';
1009 local $am_file;
1010 foreach $am_file (@input_files)
1011 {
1012     if (! -f ($am_file . '.am'))
1013     {
1014         &am_error ("`" . $am_file . ".am' does not exist");
1015     }
1016     else
1017     {
1018         &generate_makefile ($output_files{$am_file}, $am_file);
1019     }
1020 }
1021
1022 exit $exit_status;
1023
1024 # FIXME: This should be `my'ed next to its subs.
1025 use vars '%require_file_found';
1026
1027 ################################################################
1028
1029 # prog_error (@PRINT-ME)
1030 # ----------------------
1031 # Signal a programming error, display PRINT-ME, and exit 1.
1032 sub prog_error (@)
1033 {
1034     print STDERR "$me: programming error: @_\n";
1035     exit 1;
1036 }
1037
1038
1039 # subst ($TEXT)
1040 # -------------
1041 # Return a configure-style substitution using the indicated text.
1042 # We do this to avoid having the substitutions directly in automake.in;
1043 # when we do that they are sometimes removed and this causes confusion
1044 # and bugs.
1045 sub subst ($)
1046 {
1047     my ($text) = @_;
1048     return '@' . $text . '@';
1049 }
1050
1051 ################################################################
1052
1053
1054 # $BACKPATH
1055 # &backname ($REL-DIR)
1056 # --------------------
1057 # If I `cd $REL-DIR', then to come back, I should `cd $BACKPATH'.
1058 # For instance `src/foo' => `../..'.
1059 # Works with non strictly increasing paths, i.e., `src/../lib' => `..'.
1060 sub backname ($)
1061 {
1062     my ($file) = @_;
1063     my @res;
1064     foreach (split (/\//, $file))
1065     {
1066         next if $_ eq '.' || $_ eq '';
1067         if ($_ eq '..')
1068         {
1069             pop @res;
1070         }
1071         else
1072         {
1073             push (@res, '..');
1074         }
1075     }
1076     return join ('/', @res) || '.';
1077 }
1078
1079 ################################################################
1080
1081 # Parse command line.
1082 sub parse_arguments ()
1083 {
1084     # Start off as gnu.
1085     &set_strictness ('gnu');
1086
1087     use Getopt::Long;
1088     Getopt::Long::config ("bundling");
1089     Getopt::Long::GetOptions
1090       (
1091        'version'        => \&version,
1092        'help'           => \&usage,
1093        'libdir:s'       => \$libdir,
1094        'gnu'            => sub { &set_strictness ('gnu'); },
1095        'gnits'          => sub { &set_strictness ('gnits'); },
1096        'cygnus'         => \$cygnus_mode,
1097        'foreign'        => sub { &set_strictness ('foreign'); },
1098        'include-deps'   => sub { $cmdline_use_dependencies = 1; },
1099        'i|ignore-deps'  => sub { $cmdline_use_dependencies = 0; },
1100        'no-force'       => sub { $force_generation = 0; },
1101        'f|force-missing'=> \$force_missing,
1102        'o|output-dir:s' => \$output_directory,
1103        'a|add-missing'  => \$add_missing,
1104        'c|copy'         => \$copy_missing,
1105        'v|verbose'      => \$verbose,
1106        'Werror'         => sub { $SIG{"__WARN__"} = sub { die $_[0] } },
1107        'Wno-error'      => sub { $SIG{"__WARN__"} = 'DEFAULT' }
1108       )
1109         or exit 1;
1110
1111     foreach my $arg (@ARGV)
1112     {
1113       # Handle $local:$input syntax.  Note that we only examine the
1114       # first ":" file to see if it is automake input; the rest are
1115       # just taken verbatim.  We still keep all the files around for
1116       # dependency checking, however.
1117       my ($local, $input, @rest) = split (/:/, $arg);
1118       if (! $input)
1119         {
1120           $input = $local;
1121         }
1122       else
1123         {
1124           # Strip .in; later on .am is tacked on.  That is how the
1125           # automake input file is found.  Maybe not the best way, but
1126           # it is easy to explain.
1127           $input =~ s/\.in$//
1128             or die "$me: invalid input file name `$arg'\n.";
1129         }
1130       push (@input_files, $input);
1131       $output_files{$input} = join (':', ($local, @rest));
1132     }
1133
1134     # Take global strictness from whatever we currently have set.
1135     $default_strictness = $strictness;
1136     $default_strictness_name = $strictness_name;
1137 }
1138
1139 ################################################################
1140
1141 # Generate a Makefile.in given the name of the corresponding Makefile and
1142 # the name of the file output by config.status.
1143 sub generate_makefile
1144 {
1145     my ($output, $makefile) = @_;
1146
1147     # Reset all the Makefile.am related variables.
1148     &initialize_per_input;
1149
1150     # Name of input file ("Makefile.am") and output file
1151     # ("Makefile.in").  These have no directory components.
1152     $am_file_name = basename ($makefile) . '.am';
1153     $in_file_name = basename ($makefile) . '.in';
1154
1155     # $OUTPUT is encoded.  If it contains a ":" then the first element
1156     # is the real output file, and all remaining elements are input
1157     # files.  We don't scan or otherwise deal with these input file,
1158     # other than to mark them as dependencies.  See
1159     # &scan_autoconf_files for details.
1160     my (@secondary_inputs);
1161     ($output, @secondary_inputs) = split (/:/, $output);
1162
1163     $relative_dir = dirname ($output);
1164     $am_relative_dir = dirname ($makefile);
1165
1166     &read_main_am_file ($makefile . '.am');
1167     if (&handle_options)
1168     {
1169         # Fatal error.  Just return, so we can continue with next file.
1170         return;
1171     }
1172
1173     # There are a few install-related variables that you should not define.
1174     foreach my $var ('PRE_INSTALL', 'POST_INSTALL', 'NORMAL_INSTALL')
1175     {
1176         if (&variable_defined ($var) && !$var_is_am{$var})
1177         {
1178             am_macro_error ($var, "`$var' should not be defined");
1179         }
1180     }
1181
1182     &handle_libtool;
1183
1184     # At the toplevel directory, we might need config.guess, config.sub
1185     # or libtool scripts (ltconfig and ltmain.sh).
1186     if ($relative_dir eq '.')
1187     {
1188         # AC_CANONICAL_HOST and AC_CANONICAL_SYSTEM need config.guess and
1189         # config.sub.
1190         &require_config_file ($FOREIGN, 'config.guess', 'config.sub')
1191             if $seen_canonical;
1192     }
1193
1194     # We still need Makefile.in here, because sometimes the `dist'
1195     # target doesn't re-run automake.
1196     if ($am_relative_dir eq $relative_dir)
1197     {
1198         # Only distribute the files if they are in the same subdir as
1199         # the generated makefile.
1200         &push_dist_common ($in_file_name, $am_file_name);
1201     }
1202
1203     push (@sources, '$(SOURCES)')
1204         if &variable_defined ('SOURCES');
1205
1206     # Must do this after reading .am file.  See read_main_am_file to
1207     # understand weird tricks we play there with variables.
1208     &define_variable ('subdir', $relative_dir);
1209
1210     # Check first, because we might modify some state.
1211     &check_cygnus;
1212     &check_gnu_standards;
1213     &check_gnits_standards;
1214
1215     &handle_configure ($output, $makefile, @secondary_inputs);
1216     &handle_gettext;
1217     &handle_libraries;
1218     &handle_ltlibraries;
1219     &handle_programs;
1220     &handle_scripts;
1221
1222     # This must run first so that the ANSI2KNR definition is generated
1223     # before it is used by the _.c rules.  We have to do this because
1224     # a variable which is used in a dependency must be defined before
1225     # the target, or else make won't properly see it.
1226     &handle_compile;
1227     # This must be run after all the sources are scanned.
1228     &handle_languages;
1229
1230     # Re-init SOURCES.  FIXME: other code shouldn't depend on this
1231     # (but currently does).
1232     macro_define ('SOURCES', 1, '', 'TRUE',
1233                      join (' ', @sources), 'internal');
1234     define_pretty_variable ('DIST_SOURCES', '', @dist_sources);
1235
1236     &handle_multilib;
1237     &handle_texinfo;
1238     &handle_emacs_lisp;
1239     &handle_python;
1240     &handle_java;
1241     &handle_man_pages;
1242     &handle_data;
1243     &handle_headers;
1244     &handle_subdirs;
1245     &handle_tags;
1246     &handle_minor_options;
1247     &handle_tests;
1248
1249     # This must come after most other rules.
1250     &handle_dist ($makefile);
1251
1252     &handle_footer;
1253     &do_check_merge_target;
1254     &handle_all ($output);
1255
1256     # FIXME: Gross!
1257     if (&variable_defined('lib_LTLIBRARIES') &&
1258         &variable_defined('bin_PROGRAMS'))
1259     {
1260         $output_rules .= "install-binPROGRAMS: install-libLTLIBRARIES\n\n";
1261     }
1262
1263     &handle_installdirs;
1264     &handle_clean;
1265     &handle_factored_dependencies;
1266
1267     &check_typos;
1268
1269     if (! -d ($output_directory . '/' . $am_relative_dir))
1270     {
1271         mkdir ($output_directory . '/' . $am_relative_dir, 0755);
1272     }
1273
1274     my ($out_file) = $output_directory . '/' . $makefile . ".in";
1275     if (! $force_generation && -e $out_file)
1276     {
1277         my ($am_time) = (stat ($makefile . '.am'))[9];
1278         my ($in_time) = (stat ($out_file))[9];
1279         # FIXME: should cache these times.
1280         my ($conf_time) = (stat ($configure_ac))[9];
1281         # FIXME: how to do unsigned comparison?
1282         if ($am_time < $in_time || $am_time < $conf_time)
1283         {
1284             # No need to update.
1285             return;
1286         }
1287         if (-f 'aclocal.m4')
1288         {
1289             my ($acl_time) = (stat _)[9];
1290             return if ($am_time < $acl_time);
1291         }
1292     }
1293
1294     my $gm_file = new IO::File "> $out_file";
1295     if (! $gm_file)
1296     {
1297         warn "$me: ${am_file}.in: cannot write: $!\n";
1298         $exit_status = 1;
1299         return;
1300     }
1301     print "$me: creating ", $makefile, ".in\n" if $verbose;
1302
1303     # In case we're running under MSWindows, don't write with CRLF
1304     # (as it causes problems for the dependency-file extraction in
1305     # AM_OUTPUT_DEPENDENCY_COMMANDS).
1306     binmode $gm_file;
1307
1308     print $gm_file $output_vars;
1309     # We make sure that `all:' is the first target.
1310     print $gm_file $output_all;
1311     print $gm_file $output_header;
1312     print $gm_file $output_rules;
1313     print $gm_file $output_trailer;
1314
1315     if (! $gm_file->close)
1316       {
1317         warn "$me: $am_file.in: cannot close: $!\n";
1318         $exit_status = 1;
1319         return;
1320       }
1321 }
1322
1323 ################################################################
1324
1325 # A helper which handles the logic of requiring a version number in
1326 # AUTOMAKE_OPTIONS.  Return 1 on error, 0 on success.
1327 sub version_check ($$$$)
1328 {
1329     my ($rmajor, $rminor, $ralpha, $rfork) = ($1, $2, $3, $4);
1330
1331     &prog_error ("version is incorrect: $VERSION")
1332         if $VERSION !~ /(\d+)\.(\d+)([a-z]?)-?([A-Za-z0-9]+)?/;
1333
1334     my ($tmajor, $tminor, $talpha, $tfork) = ($1, $2, $3, $4);
1335
1336     $rfork ||= '';
1337     $tfork ||= '';
1338
1339     my $rminorminor = 0;
1340     my $tminorminor = 0;
1341
1342     # Some versions were labelled like `1.4-p3a'.  This is the same as
1343     # an alpha release labelled `1.4.3a'.  However, a version like
1344     # `1.4g' is the same as `1.4.99g'.  Yes, this sucks.  Moral:
1345     # always listen to the users.
1346     if ($rfork =~ /p([0-9]+)([a-z]?)/)
1347     {
1348         $rminorminor = $1;
1349         # `1.4a-p3b' never existed.  But we'll accept it anyway.
1350         $ralpha = $ralpha || $2 || '';
1351         $rfork = '';
1352     }
1353     if ($tfork =~ /p([0-9]+)([a-z]?)/)
1354     {
1355         $tminorminor = $1;
1356         # `1.4a-p3b' never existed.  But we'll accept it anyway.
1357         $talpha = $talpha || $2 || '';
1358         $tfork = '';
1359     }
1360
1361     $rminorminor = 99 if $ralpha ne '' && $rminorminor == 0;
1362     $tminorminor = 99 if $talpha ne '' && $tminorminor == 0;
1363
1364     # 2.0 is better than 1.0.
1365     # 1.2 is better than 1.1.
1366     # 1.2a is better than 1.2.
1367     # If we require 3.4n-foo then we require something
1368     # >= 3.4n, with the `foo' fork identifier.
1369     # The $r* variables are what the user specified.
1370     # The $t* variables denote automake itself.
1371     if ($rmajor > $tmajor
1372         || ($rmajor == $tmajor && $rminor > $tminor)
1373         || ($rminor == $tminor && $rminor == $tminor
1374             && $rminorminor > $tminorminor)
1375         || ($rminor == $tminor && $rminor == $tminor
1376             && $rminorminor == $tminorminor
1377             && $ralpha gt $talpha)
1378         || ($rfork ne '' && $rfork ne $tfork))
1379     {
1380         am_macro_error ('AUTOMAKE_OPTIONS',
1381                          "require version $_, but have $VERSION");
1382         return 1;
1383     }
1384
1385     return 0;
1386 }
1387
1388 # Handle AUTOMAKE_OPTIONS variable.  Return 1 on error, 0 otherwise.
1389 sub handle_options
1390 {
1391     if (&variable_defined ('AUTOMAKE_OPTIONS'))
1392     {
1393         foreach (&variable_value_as_list_recursive ('AUTOMAKE_OPTIONS', ''))
1394         {
1395             $options{$_} = 1;
1396             if ($_ eq 'gnits' || $_ eq 'gnu' || $_ eq 'foreign')
1397             {
1398                 &set_strictness ($_);
1399             }
1400             elsif ($_ eq 'cygnus')
1401             {
1402                 $cygnus_mode = 1;
1403             }
1404             elsif (/^(.*\/)?ansi2knr$/)
1405             {
1406                 # An option like "../lib/ansi2knr" is allowed.  With
1407                 # no path prefix, we assume the required programs are
1408                 # in this directory.  We save the actual option for
1409                 # later.
1410                 $options{'ansi2knr'} = $_;
1411             }
1412             elsif ($_ eq 'no-installman' || $_ eq 'no-installinfo'
1413                    || $_ eq 'dist-shar' || $_ eq 'dist-zip'
1414                    || $_ eq 'dist-tarZ' || $_ eq 'dist-bzip2'
1415                    || $_ eq 'dejagnu' || $_ eq 'no-texinfo.tex'
1416                    || $_ eq 'readme-alpha' || $_ eq 'check-news'
1417                    || $_ eq 'subdir-objects' || $_ eq 'nostdinc'
1418                    || $_ eq 'no-exeext')
1419             {
1420                 # Explicitly recognize these.
1421             }
1422             elsif ($_ eq 'no-dependencies')
1423             {
1424                 $use_dependencies = 0;
1425             }
1426             elsif (/(\d+)\.(\d+)([a-z]?)(-[A-Za-z0-9]+)?/)
1427             {
1428                 # Got a version number.
1429                 if (version_check ($1, $2, $3, $4))
1430                 {
1431                     return 1;
1432                 }
1433             }
1434             else
1435             {
1436                 am_macro_error ('AUTOMAKE_OPTIONS',
1437                                 "option `" . $_ . "\' not recognized");
1438             }
1439         }
1440     }
1441
1442     if ($strictness == $GNITS)
1443     {
1444         $options{'readme-alpha'} = 1;
1445         $options{'check-news'} = 1;
1446     }
1447
1448     return 0;
1449 }
1450
1451
1452 # get_object_extension ($OUT)
1453 # ---------------------------
1454 # Return object extension.  Just once, put some code into the output.
1455 # OUT is the name of the output file
1456 sub get_object_extension
1457 {
1458     my ($out) = @_;
1459
1460     # Maybe require libtool library object files.
1461     my $extension = '.$(OBJEXT)';
1462     $extension = '.lo' if ($out =~ /\.la$/);
1463
1464     # Check for automatic de-ANSI-fication.
1465     $extension = '$U' . $extension
1466       if defined $options{'ansi2knr'};
1467
1468     $get_object_extension_was_run = 1;
1469
1470     return $extension;
1471 }
1472
1473
1474 # Call finish function for each language that was used.
1475 sub handle_languages
1476 {
1477     if ($use_dependencies)
1478     {
1479         # Include auto-dep code.  Don't include it if DEP_FILES would
1480         # be empty.
1481         if (&saw_sources_p (0) && keys %dep_files)
1482         {
1483             # Set location of depcomp.
1484             &define_variable ('depcomp', "\$(SHELL) $config_aux_dir/depcomp");
1485
1486             &require_conf_file ($FOREIGN, 'depcomp');
1487
1488             my @deplist = sort keys %dep_files;
1489
1490             # We define this as a conditional variable because BSD
1491             # make can't handle backslashes for continuing comments on
1492             # the following line.
1493             define_pretty_variable ('DEP_FILES', 'AMDEP_TRUE', @deplist);
1494
1495             # Generate each `include' individually.  Irix 6 make will
1496             # not properly include several files resulting from a
1497             # variable expansion; generating many separate includes
1498             # seems safest.
1499             $output_rules .= "\n";
1500             foreach my $iter (@deplist)
1501             {
1502                 $output_rules .= (subst ('AMDEP_TRUE')
1503                                   . subst ('am__include')
1504                                   . ' '
1505                                   . subst ('am__quote')
1506                                   . $iter
1507                                   . subst ('am__quote')
1508                                   . "\n");
1509             }
1510
1511             $output_rules .= &file_contents ('depend');
1512         }
1513     }
1514     else
1515     {
1516         &define_variable ('depcomp', '');
1517     }
1518
1519     my %done;
1520
1521     # Is the c linker needed?
1522     my $needs_c = 0;
1523     foreach my $ext (sort keys %extension_seen)
1524     {
1525         next unless $extension_map{$ext};
1526
1527         my $lang = $languages{$extension_map{$ext}};
1528
1529         my $rule_file = $lang->rule_file || 'depend2';
1530
1531         # Get information on $LANG.
1532         my $pfx = $lang->autodep;
1533         my $fpfx = ($pfx eq '') ? 'CC' : $pfx;
1534
1535         my $AMDEP = (($use_dependencies && $lang->autodep ne 'no')
1536                      ? 'AMDEP' : 'FALSE');
1537
1538         my %transform = ('EXT'     => $ext,
1539                          'PFX'     => $pfx,
1540                          'FPFX'    => $fpfx,
1541                          'LIBTOOL' => $seen_libtool,
1542                          'AMDEP'   => $AMDEP,
1543                          '-c'      => $lang->compile_flag || '',
1544                          'MORE-THAN-ONE'
1545                                    => (count_files_for_language ($lang->name) > 1));
1546
1547         # Generate the appropriate rules for this extension.
1548         if (($use_dependencies && $lang->autodep ne 'no')
1549             || defined $lang->compile)
1550         {
1551             # Some C compilers don't support -c -o.  Use it only if really
1552             # needed.
1553             my $output_flag = $lang->output_flag || '';
1554             $output_flag = '-o'
1555               if (! $output_flag
1556                   && $lang->flags eq 'CFLAGS'
1557                   && defined $options{'subdir-objects'});
1558
1559             # FIXME: this is a temporary hack to compute a possible
1560             # derived extension.  This is not used by depend2.am.
1561             (my $der_ext = $ext) =~ tr/yl/cc/;
1562
1563             # Another yacc/lex hack.
1564             my $destfile = '$*.' . $der_ext;
1565
1566             $output_rules .=
1567               file_contents ($rule_file,
1568                              %transform,
1569                              'GENERIC'   => 1,
1570
1571                              'DERIVED-EXT' => $der_ext,
1572
1573                              'BASE'      => '$*',
1574                              'SOURCE'    => '$<',
1575                              'OBJ'       => '$@',
1576                              'OBJOBJ'    => '$@',
1577                              'LTOBJ'     => '$@',
1578
1579                              'COMPILE'   => '$(' . $lang->compiler . ')',
1580                              'LTCOMPILE' => '$(LT' . $lang->compiler . ')',
1581                              '-o'        => $output_flag);
1582         }
1583
1584         # Now include code for each specially handled object with this
1585         # language.
1586         my %seen_files = ();
1587         foreach my $file (@{$lang_specific_files{$lang->name}})
1588         {
1589             my ($derived, $source, $obj, $myext) = split (' ', $file);
1590
1591             # We might see a given object twice, for instance if it is
1592             # used under different conditions.
1593             next if defined $seen_files{$obj};
1594             $seen_files{$obj} = 1;
1595
1596             my $flags = $lang->flags || '';
1597             my $val = "${derived}_${flags}";
1598
1599             &prog_error ("found $lang->name in handle_languages, but compiler not defined")
1600                 unless defined $lang->compile;
1601
1602             (my $obj_compile = $lang->compile) =~ s/\(AM_$flags/\($val/;
1603             my $obj_ltcompile = '$(LIBTOOL) --mode=compile ' . $obj_compile;
1604
1605             # We _need_ `-o' for per object rules.
1606             my $output_flag = $lang->output_flag || '-o';
1607
1608             # Generate a transform which will turn suffix targets in
1609             # depend2.am into real targets for the particular objects we
1610             # are building.
1611             $output_rules .=
1612               file_contents ($rule_file,
1613                              (%transform,
1614                               'GENERIC'   => 0,
1615
1616                               'BASE'      => $obj,
1617                               'SOURCE'    => $source,
1618                               # Use $myext and not `.o' here, in case
1619                               # we are actually building a new source
1620                               # file -- e.g. via yacc.
1621                               'OBJ'       => "$obj$myext",
1622                               'OBJOBJ'    => "$obj.obj",
1623                               'LTOBJ'     => "$obj.lo",
1624
1625                               'COMPILE'   => $obj_compile,
1626                               'LTCOMPILE' => $obj_ltcompile,
1627                               '-o'        => $output_flag));
1628         }
1629
1630         # The rest of the loop is done once per language.
1631         next if defined $done{$lang};
1632         $done{$lang} = 1;
1633
1634         # Load the language dependent Makefile chunks.
1635         my %lang = map { uc ($_) => 0 } keys %languages;
1636         $lang{uc ($lang->name)} = 1;
1637         $output_rules .= file_contents ('lang-compile', %transform, %lang);
1638
1639         # If the source to a program consists entirely of code from a
1640         # `pure' language, for instance C++ for Fortran 77, then we
1641         # don't need the C compiler code.  However if we run into
1642         # something unusual then we do generate the C code.  There are
1643         # probably corner cases here that do not work properly.
1644         # People linking Java code to Fortran code deserve pain.
1645         $needs_c ||= ! $lang->pure;
1646
1647         define_compiler_variable ($lang)
1648           if ($lang->compile);
1649
1650         define_linker_variable ($lang)
1651           if ($lang->link);
1652
1653         foreach my $var (@{$lang->config_vars})
1654           {
1655             am_error ($lang->Name
1656                       . " source seen but `$var' not defined in"
1657                       . " `$configure_ac'")
1658               if !exists $configure_vars{$var};
1659           }
1660
1661         # The compiler's flag must be a configure variable.
1662         define_configure_variable ($lang->flags)
1663             if defined $lang->flags && $lang->define_flag;
1664
1665         # Call the finisher.
1666         $lang->finish;
1667     }
1668
1669     # If the project is entirely C++ or entirely Fortran 77 (i.e., 1
1670     # suffix rule was learned), don't bother with the C stuff.  But if
1671     # anything else creeps in, then use it.
1672     $needs_c = 1
1673       if $need_link || scalar keys %suffix_rules > 1;
1674
1675     if ($needs_c)
1676       {
1677         if (! defined $done{$languages{'c'}})
1678           {
1679             &define_configure_variable ($languages{'c'}->flags);
1680             &define_compiler_variable ($languages{'c'});
1681           }
1682         define_linker_variable ($languages{'c'});
1683       }
1684 }
1685
1686 # Check to make sure a source defined in LIBOBJS is not explicitly
1687 # mentioned.  This is a separate function (as opposed to being inlined
1688 # in handle_source_transform) because it isn't always appropriate to
1689 # do this check.
1690 sub check_libobjs_sources
1691 {
1692     my ($one_file, $unxformed) = @_;
1693
1694     foreach my $prefix ('', 'EXTRA_', 'dist_', 'nodist_',
1695                         'dist_EXTRA_', 'nodist_EXTRA_')
1696     {
1697         my @files;
1698         if (&variable_defined ($prefix . $one_file . '_SOURCES'))
1699         {
1700             @files = &variable_value_as_list_recursive (
1701                                 ($prefix . $one_file . '_SOURCES'),
1702                                 'all');
1703         }
1704         elsif ($prefix eq '')
1705         {
1706             @files = ($unxformed . '.c');
1707         }
1708         else
1709         {
1710             next;
1711         }
1712
1713         foreach my $file (@files)
1714         {
1715             if (defined $libsources{$file})
1716             {
1717                 am_macro_error ($prefix . $one_file . '_SOURCES',
1718                                 "automatically discovered file `$file' should not be explicitly mentioned");
1719             }
1720         }
1721     }
1722 }
1723
1724
1725 # @OBJECTS
1726 # handle_single_transform_list ($VAR, $TOPPARENT, $DERIVED, $OBJ, @FILES)
1727 # -----------------------------------------------------------------------
1728 # Does much of the actual work for handle_source_transform.
1729 # Arguments are:
1730 #   $VAR is the name of the variable that the source filenames come from
1731 #   $TOPPARENT is the name of the _SOURCES variable which is being processed
1732 #   $DERIVED is the name of resulting executable or library
1733 #   $OBJ is the object extension (e.g., `$U.lo')
1734 #   @FILES is the list of source files to transform
1735 # Result is a list of the names of objects
1736 # %linkers_used will be updated with any linkers needed
1737 sub handle_single_transform_list ($$$$@)
1738 {
1739     my ($var, $topparent, $derived, $obj, @files) = @_;
1740     my @result = ();
1741     my $nonansi_obj = $obj;
1742     $nonansi_obj =~ s/\$U//g;
1743
1744     # Turn sources into objects.  We use a while loop like this
1745     # because we might add to @files in the loop.
1746     while (scalar @files > 0)
1747     {
1748         $_ = shift @files;
1749
1750         # Configure substitutions in _SOURCES variables are errors.
1751         if (/^\@.*\@$/)
1752         {
1753             am_macro_error ($var, "`$var' includes configure substitution `$_', and is referred to from `$topparent': configure substitutions not allowed in _SOURCES variables");
1754             next;
1755         }
1756
1757         # If the source file is in a subdirectory then the `.o' is put
1758         # into the current directory, unless the subdir-objects option
1759         # is in effect.
1760
1761         # Split file name into base and extension.
1762         next if ! /^(?:(.*)\/)?([^\/]*)\.(.*)$/;
1763         my $full = $_;
1764         my $directory = $1 || '';
1765         my $base = $2;
1766         my $extension = $3;
1767
1768         # We must generate a rule for the object if it requires its own flags.
1769         my $renamed = 0;
1770         my ($linker, $object);
1771
1772         # This records whether we've seen a derived source file (eg,
1773         # yacc output).
1774         my $derived_source = 0;
1775
1776         # This holds the `aggregate context' of the file we are
1777         # currently examining.  If the file is compiled with
1778         # per-object flags, then it will be the name of the object.
1779         # Otherwise it will be `AM'.  This is used by the target hook
1780         # language function.
1781         my $aggregate = 'AM';
1782
1783         $extension = &derive_suffix ($extension);
1784         my $lang;
1785         if ($extension_map{$extension} &&
1786             ($lang = $languages{$extension_map{$extension}}))
1787         {
1788             # Found the language, so see what it says.
1789             &saw_extension ($extension);
1790
1791             # Note: computed subr call.  The language rewrite function
1792             # should return one of the $LANG_* constants.  It could
1793             # also return a list whose first value is such a constant
1794             # and whose second value is a new source extension which
1795             # should be applied.  This means this particular language
1796             # generates another source file which we must then process
1797             # further.
1798             my $subr = 'lang_' . $lang->name . '_rewrite';
1799             my ($r, $source_extension)
1800                 = & $subr ($directory, $base, $extension);
1801             # Skip this entry if we were asked not to process it.
1802             next if $r == $LANG_IGNORE;
1803
1804             # Now extract linker and other info.
1805             $linker = $lang->linker;
1806
1807             my $this_obj_ext;
1808             if (defined $source_extension)
1809             {
1810                 $this_obj_ext = '.' . $source_extension;
1811                 $derived_source = 1;
1812             }
1813             elsif ($lang->ansi)
1814             {
1815                 $this_obj_ext = $obj;
1816             }
1817             else
1818             {
1819                 $this_obj_ext = $nonansi_obj;
1820             }
1821             $object = $base . $this_obj_ext;
1822
1823             if (defined $lang->flags
1824                 && &variable_defined ($derived . '_' . $lang->flags))
1825             {
1826                 # We have a per-executable flag in effect for this
1827                 # object.  In this case we rewrite the object's
1828                 # name to ensure it is unique.  We also require
1829                 # the `compile' program to deal with compilers
1830                 # where `-c -o' does not work.
1831
1832                 # We choose the name `DERIVED_OBJECT' to ensure
1833                 # (1) uniqueness, and (2) continuity between
1834                 # invocations.  However, this will result in a
1835                 # name that is too long for losing systems, in
1836                 # some situations.  So we provide _SHORTNAME to
1837                 # override.
1838
1839                 my $dname = $derived;
1840                 if (&variable_defined ($derived . '_SHORTNAME'))
1841                 {
1842                     # FIXME: should use the same conditional as
1843                     # the _SOURCES variable.  But this is really
1844                     # silly overkill -- nobody should have
1845                     # conditional shortnames.
1846                     $dname = &variable_value ($derived . '_SHORTNAME');
1847                 }
1848                 $object = $dname . '-' . $object;
1849
1850                 &require_conf_file ($FOREIGN, 'compile')
1851                     if $lang->name eq 'c';
1852
1853                 &prog_error ("$lang->name flags defined without compiler")
1854                     if ! defined $lang->compile;
1855
1856                 $renamed = 1;
1857             }
1858
1859             # If rewrite said it was ok, put the object into a
1860             # subdir.
1861             if ($r == $LANG_SUBDIR && $directory ne '')
1862             {
1863                 $object = $directory . '/' . $object;
1864             }
1865
1866             # If doing dependency tracking, then we can't print
1867             # the rule.  If we have a subdir object, we need to
1868             # generate an explicit rule.  Actually, in any case
1869             # where the object is not in `.' we need a special
1870             # rule.  The per-object rules in this case are
1871             # generated later, by handle_languages.
1872             if ($renamed || $directory ne '')
1873             {
1874                 my $obj_sans_ext = substr ($object, 0,
1875                                            - length ($this_obj_ext));
1876                 my $val = ("$full $obj_sans_ext "
1877                            # Only use $this_obj_ext in the derived
1878                            # source case because in the other case we
1879                            # *don't* want $(OBJEXT) to appear here.
1880                            . ($derived_source ? $this_obj_ext : '.o'));
1881
1882                 # If we renamed the object then we want to use the
1883                 # per-executable flag name.  But if this is simply a
1884                 # subdir build then we still want to use the AM_ flag
1885                 # name.
1886                 if ($renamed)
1887                 {
1888                     $val = "$derived $val";
1889                     $aggregate = $derived;
1890                 }
1891                 else
1892                 {
1893                     $val = "AM $val";
1894                 }
1895
1896                 # Each item on this list is a string consisting of
1897                 # four space-separated values: the derived flag prefix
1898                 # (eg, for `foo_CFLAGS', it is `foo'), the name of the
1899                 # source file, the base name of the output file, and
1900                 # the extension for the object file.
1901                 push (@{$lang_specific_files{$lang->name}}, $val);
1902             }
1903         }
1904         elsif ($extension eq 'o')
1905         {
1906             # This is probably the result of a direct suffix rule.
1907             # In this case we just accept the rewrite.  FIXME:
1908             # this fails if we want libtool objects.
1909             $object = $base . '.' . $extension;
1910             $linker = '';
1911         }
1912         else
1913         {
1914             # No error message here.  Used to have one, but it was
1915             # very unpopular.
1916             # FIXME: we could potentially do more processing here,
1917             # perhaps treating the new extension as though it were a
1918             # new source extension (as above).  This would require
1919             # more restructuring than is appropriate right now.
1920             next;
1921         }
1922
1923         if (defined $object_map{$object})
1924         {
1925             if ($object_map{$object} ne $full)
1926             {
1927                 &am_error ("object `$object' created by `$full' and `$object_map{$object}'");
1928             }
1929         }
1930
1931         # Let the language do some special magic if required.
1932         $lang->target_hook ($aggregate, $object, $full);
1933
1934         if ($derived_source)
1935         {
1936             &prog_error ("$lang->name has automatic dependency tracking")
1937                 if $lang->autodep ne 'no';
1938             # Make sure this new source file is handled next.  That will
1939             # make it appear to be at the right place in the list.
1940             unshift (@files, $object);
1941             # FIXME: nodist.
1942             &push_dist_common ($object);
1943             next;
1944         }
1945
1946         $linkers_used{$linker} = 1;
1947
1948         push (@result, $object);
1949
1950         if (! defined $object_map{$object})
1951         {
1952             my @dep_list = ();
1953             $object_map{$object} = $full;
1954
1955             # If file is in subdirectory, we need explicit
1956             # dependency.
1957             if ($directory ne '' || $renamed)
1958             {
1959                 push (@dep_list, $full);
1960             }
1961
1962             # If resulting object is in subdir, we need to make
1963             # sure the subdir exists at build time.
1964             if ($object =~ /\//)
1965             {
1966                 # FIXME: check that $DIRECTORY is somewhere in the
1967                 # project
1968
1969                 # We don't allow `..' in object file names for
1970                 # *any* source, not just Java.  For Java it just
1971                 # doesn't make sense, but in general it is
1972                 # a problem because we can't pick a good name for
1973                 # the .deps entry.
1974                 if ($object =~ /(\/|^)\.\.\//)
1975                 {
1976                     &am_error ("`$full' contains `..' component but should not");
1977                 }
1978
1979                 # Make sure object is removed by `make mostlyclean'.
1980                 $compile_clean_files{$object} = $MOSTLY_CLEAN;
1981
1982                 push (@dep_list, &require_build_directory ($directory));
1983
1984                 # If we're generating dependencies, we also want
1985                 # to make sure that the appropriate subdir of the
1986                 # .deps directory is created.
1987                 push (@dep_list, &require_build_directory ('$(DEPDIR)/' . $directory))
1988                     if ($use_dependencies);
1989             }
1990
1991             &pretty_print_rule ($object . ':', "\t", @dep_list)
1992                 if scalar @dep_list > 0;
1993         }
1994
1995         # Transform .o or $o file into .P file (for automatic
1996         # dependency code).
1997         if ($lang && $lang->autodep ne 'no')
1998         {
1999             my $depfile = $object;
2000             $depfile =~ s/\.([^.]*)$/.P$1/;
2001             $depfile =~ s/\$\(OBJEXT\)$/o/;
2002             $dep_files{'$(DEPDIR)/' . $depfile} = 1;
2003         }
2004     }
2005
2006     return @result;
2007 }
2008
2009 # $BOOL
2010 # define_objects_from_sources ($VAR, $OBJVAR, $NODEFINE, $ONE_FILE,
2011 #                              $OBJ, $PARENT, $TOPPARENT)
2012 # ---------------------------------------------------------------------
2013 # Define an _OBJECTS variable for a _SOURCES variable (or subvariable)
2014 #
2015 # Arguments are:
2016 #   $VAR is the name of the _SOURCES variable
2017 #   $OBJVAR is the name of the _OBJECTS
2018 #   $NODEFINE is a boolean: if true, $OBJVAR will not be defined (but
2019 #   work done to determine the linker will be).
2020 #   $ONE_FILE is the canonical (transformed) name of object to build
2021 #   $OBJ is the object extension (ie either `.o' or `$o'.
2022 #   $PARENT is the variable in which $VAR is used, or $VAR if not applicable.
2023 #   $TOPPARENT is the _SOURCES variable being processed.
2024 #
2025 # Result is a boolean, true if a linker is needed to deal with the objects.
2026 #
2027 # %linkers_used, %vars_scanned, @substfroms and @substtos should be cleared
2028 # before use:
2029 #   %linkers_used variable will be set to contain the linkers desired.
2030 #   %vars_scanned will be used to check for recursive definitions.
2031 #   @substfroms and @substtos will be used to keep a stack of variable
2032 #   substitutions to be applied.
2033 #
2034 sub define_objects_from_sources ($$$$$$$)
2035 {
2036     my ($var, $objvar, $nodefine, $one_file, $obj, $parent, $topparent) = @_;
2037
2038     if (defined $vars_scanned{$var})
2039     {
2040         am_macro_error ($var, "variable `$var' recursively defined");
2041         return "";
2042     }
2043     $vars_scanned{$var} = 1;
2044
2045     my $needlinker = "";
2046     foreach my $cond (variable_conditions ($var))
2047     {
2048         my @result;
2049         foreach my $val (&variable_value_as_list ($var, $cond, $parent))
2050         {
2051             if ($val =~ /^\$\{([^}]*)\}$/ || $val =~ /^\$\(([^)]*)\)$/)
2052             {
2053                 # Handle a sub variable
2054                 my $subvar = $1;
2055
2056                 # If the user uses a losing variable name, just ignore it.
2057                 # This isn't ideal, but people have requested it.
2058                 next if ($subvar =~ /\@.*\@/);
2059
2060                 # See if the variable is actually a substitution reference
2061                 my ($from, $to);
2062                 my @temp_list;
2063                 if ($subvar =~ /$SUBST_REF_PATTERN/o)
2064                 {
2065                     $subvar = $1;
2066                     $to = $3;
2067                     ($from = $2) =~ s/(\W)/\\$1/g;
2068                 }
2069                 push @substfroms, $from;
2070                 push @substtos, $to;
2071
2072                 my $subobjvar = subobjname ($subvar);
2073                 push (@result, '$('. $subobjvar . ')');
2074
2075                 my $temp = define_objects_from_sources ($subvar, $subobjvar,
2076                                                         $nodefine, $one_file,
2077                                                         $obj, $var, $topparent);
2078                 $needlinker ||= $temp;
2079
2080                 pop @substfroms;
2081                 pop @substtos;
2082             }
2083             else
2084             {
2085                 my $substnum=$#substfroms;
2086                 while ($substnum >= 0)
2087                 {
2088                     $val =~ s/$substfroms[$substnum]$/$substtos[$substnum]/
2089                         if defined $substfroms[$substnum];
2090                     $substnum -= 1;
2091                 }
2092
2093                 my (@transformed) =
2094                       &handle_single_transform_list ($var, $topparent, $one_file, $obj, $val);
2095                 push (@result, @transformed);
2096                 $needlinker = "true" if @transformed;
2097             }
2098         }
2099
2100         # Define _OBJECTS conditionally.
2101         define_pretty_variable ($objvar, $cond, (@result))
2102                 unless $nodefine;
2103     }
2104
2105     delete $vars_scanned{$var};
2106     return $needlinker;
2107 }
2108
2109
2110 # $OBJNAME
2111 # subobjname ($VARNAME)
2112 # ---------------------
2113 # Return a name for an object variable.
2114 #
2115 # Arguments are:
2116 #   $VARNAME is the name of the variable the object variable is being
2117 #   generated from.
2118 #
2119 # This function also looks at @substfroms and @substtos to determine any
2120 # substitutions to be performed on the object variable.
2121 #
2122 # The name returned is unique for the combination of $varname and
2123 # substitutions to be performed.
2124 sub subobjname ($)
2125 {
2126     my ($varname) = @_;
2127     my $key = $varname;
2128     my $substnum=$#substfroms;
2129     while ($substnum >= 0)
2130     {
2131         if (defined $substfroms[$substnum] &&
2132             ($substfroms[$substnum] || $substtos[$substnum]))
2133         {
2134             $key .= ":" . $substfroms[$substnum] . "=" . $substtos[$substnum];
2135         }
2136         $substnum -= 1;
2137     }
2138
2139     my $num = $substnums{$key};
2140     if (! $num)
2141     {
2142         $num = keys(%substnums) + 1;
2143         $substnums{$key} = $num;
2144     }
2145
2146     return "am__objects_$num";
2147 }
2148
2149
2150 # Handle SOURCE->OBJECT transform for one program or library.
2151 # Arguments are:
2152 #   canonical (transformed) name of object to build
2153 #   actual name of object to build
2154 #   object extension (ie either `.o' or `$o'.
2155 # Return result is name of linker variable that must be used.
2156 # Empty return means just use `LINK'.
2157 sub handle_source_transform
2158 {
2159     # one_file is canonical name.  unxformed is given name.  obj is
2160     # object extension.
2161     my ($one_file, $unxformed, $obj) = @_;
2162
2163     my ($linker) = '';
2164
2165     if (&variable_defined ($one_file . "_OBJECTS"))
2166     {
2167         am_macro_error ($one_file . '_OBJECTS',
2168                         $one_file . '_OBJECTS', 'should not be defined');
2169         # No point in continuing.
2170         return;
2171     }
2172
2173     my %used_pfx = ();
2174     my $needlinker;
2175     %linkers_used = ();
2176     foreach my $prefix ('', 'EXTRA_', 'dist_', 'nodist_',
2177                         'dist_EXTRA_', 'nodist_EXTRA_')
2178     {
2179         my $var = $prefix . $one_file . "_SOURCES";
2180         next
2181           if !variable_defined ($var);
2182
2183         # We are going to define _OBJECTS variables using the prefix.
2184         # Then we glom them all together.  So we can't use the null
2185         # prefix here as we need it later.
2186         my $xpfx = ($prefix eq '') ? 'am_' : $prefix;
2187
2188         # Keep track of which prefixes we saw.
2189         $used_pfx{$xpfx} = 1
2190           unless $prefix =~ /EXTRA_/;
2191
2192         push (@sources, '$(' . $prefix . $one_file . "_SOURCES)");
2193         push (@dist_sources, '$(' . $prefix . $one_file . "_SOURCES)")
2194           unless $prefix =~ /^nodist_/;
2195
2196         @substfroms = ();
2197         @substtos = ();
2198         %vars_scanned = ();
2199         my $temp = define_objects_from_sources ($var,
2200                                                 $xpfx . $one_file . '_OBJECTS',
2201                                                 $prefix =~ /EXTRA_/,
2202                                                 $one_file, $obj, $var, $var);
2203         $needlinker ||= $temp;
2204     }
2205     if ($needlinker)
2206     {
2207         $linker ||= &resolve_linker (%linkers_used);
2208     }
2209
2210     my @keys = sort keys %used_pfx;
2211     if (scalar @keys == 0)
2212     {
2213         &define_variable ($one_file . "_SOURCES", $unxformed . ".c");
2214         push (@sources, $unxformed . '.c');
2215         push (@dist_sources, $unxformed . '.c');
2216
2217         %linkers_used = ();
2218         my (@result) =
2219           &handle_single_transform_list ($one_file . '_SOURCES',
2220                                          $one_file . '_SOURCES',
2221                                          $one_file, $obj,
2222                                          "$unxformed.c");
2223         $linker ||= &resolve_linker (%linkers_used);
2224         define_pretty_variable ($one_file . "_OBJECTS", '', @result)
2225     }
2226     else
2227     {
2228         grep ($_ = '$(' . $_ . $one_file . '_OBJECTS)', @keys);
2229         define_pretty_variable ($one_file . '_OBJECTS', '', @keys);
2230     }
2231
2232     # If we want to use `LINK' we must make sure it is defined.
2233     if ($linker eq '')
2234     {
2235         $need_link = 1;
2236     }
2237
2238     return $linker;
2239 }
2240
2241
2242 # handle_lib_objects ($XNAME, $VAR)
2243 # ---------------------------------
2244 # Special-case @ALLOCA@ and @LIBOBJS@ in _LDADD or _LIBADD variables.
2245 # Also, generate _DEPENDENCIES variable if appropriate.
2246 # Arguments are:
2247 #   transformed name of object being built, or empty string if no object
2248 #   name of _LDADD/_LIBADD-type variable to examine
2249 # Returns 1 if LIBOBJS seen, 0 otherwise.
2250 sub handle_lib_objects
2251 {
2252     my ($xname, $var) = @_;
2253
2254     &prog_error ("handle_lib_objects: $var undefined")
2255         if ! &variable_defined ($var);
2256
2257     my $ret = 0;
2258     foreach my $cond (variable_conditions_recursive ($var))
2259       {
2260         if (&handle_lib_objects_cond ($xname, $var, $cond))
2261           {
2262             $ret = 1;
2263           }
2264       }
2265     return $ret;
2266 }
2267
2268 # Subroutine of handle_lib_objects: handle a particular condition.
2269 sub handle_lib_objects_cond
2270 {
2271     my ($xname, $var, $cond) = @_;
2272
2273     # We recognize certain things that are commonly put in LIBADD or
2274     # LDADD.
2275     my @dep_list = ();
2276
2277     my $seen_libobjs = 0;
2278     my $flagvar = 0;
2279
2280     foreach my $lsearch (&variable_value_as_list_recursive ($var, $cond))
2281     {
2282         # Skip -lfoo and -Ldir; these are explicitly allowed.
2283         next if $lsearch =~ /^-[lL]/;
2284         if (! $flagvar && $lsearch =~ /^-/)
2285         {
2286             if ($var =~ /^(.*)LDADD$/)
2287             {
2288                 # Skip -dlopen and -dlpreopen; these are explicitly allowed.
2289                 next if $lsearch =~ /^-dl(pre)?open$/;
2290                 am_macro_error ($var, "linker flags such as `$lsearch' belong in `${1}LDFLAGS");
2291             }
2292             else
2293             {
2294                 # Only get this error once.
2295                 $flagvar = 1;
2296                 am_macro_error ($var, "linker flags such as `$lsearch' belong in `${1}LDFLAGS");
2297             }
2298         }
2299
2300         # Assume we have a file of some sort, and push it onto the
2301         # dependency list.  Autoconf substitutions are not pushed;
2302         # rarely is a new dependency substituted into (eg) foo_LDADD
2303         # -- but "bad things (eg -lX11) are routinely substituted.
2304         # Note that LIBOBJS and ALLOCA are exceptions to this rule,
2305         # and handled specially below.
2306         push (@dep_list, $lsearch)
2307             unless $lsearch =~ /^\@.*\@$/;
2308
2309         # Automatically handle @LIBOBJS@ and @ALLOCA@.  Basically this
2310         # means adding entries to dep_files.
2311         if ($lsearch =~ /^\@(LT)?LIBOBJS\@$/)
2312         {
2313             my $lt = $1 ? $1 : '';
2314             my $myobjext = ($1 ? 'l' : '') . 'o';
2315
2316             push (@dep_list, $lsearch);
2317             $seen_libobjs = 1;
2318             if (! keys %libsources
2319                 && ! &variable_defined ($lt . 'LIBOBJS'))
2320             {
2321                 am_macro_error ($var, "\@$lt" . "LIBOBJS\@ seen but never set in `$configure_ac'");
2322             }
2323
2324             foreach my $iter (keys %libsources)
2325             {
2326                 if ($iter =~ /\.([cly])$/)
2327                 {
2328                     &saw_extension ($1);
2329                     &saw_extension ('c');
2330                 }
2331
2332                 if ($iter =~ /\.h$/)
2333                 {
2334                     require_file_with_macro ($var, $FOREIGN, $iter);
2335                 }
2336                 elsif ($iter ne 'alloca.c')
2337                 {
2338                     my $rewrite = $iter;
2339                     $rewrite =~ s/\.c$/.P$myobjext/;
2340                     $dep_files{'$(DEPDIR)/' . $rewrite} = 1;
2341                     ($rewrite = $iter) =~ s/(\W)/\\$1/g;
2342                     $rewrite = "^" . $rewrite . "\$";
2343                     # Only require the file if it is not a built source.
2344                     if (! &variable_defined ('BUILT_SOURCES')
2345                         || ! grep (/$rewrite/,
2346                                    &variable_value_as_list_recursive (
2347                                         'BUILT_SOURCES', 'all')))
2348                     {
2349                         require_file_with_macro ($var, $FOREIGN, $iter);
2350                     }
2351                 }
2352             }
2353         }
2354         elsif ($lsearch =~ /^\@(LT)?ALLOCA\@$/)
2355         {
2356             my $lt = $1 ? $1 : '';
2357             my $myobjext = ($1 ? 'l' : '') . 'o';
2358
2359             push (@dep_list, $lsearch);
2360             am_macro_error ($var,
2361                             "\@$lt" . "ALLOCA\@ seen but `AC_FUNC_ALLOCA' not in `$configure_ac'")
2362                 if ! defined $libsources{'alloca.c'};
2363             $dep_files{'$(DEPDIR)/alloca.P' . $myobjext} = 1;
2364             require_file_with_macro ($var, $FOREIGN, 'alloca.c');
2365             &saw_extension ('c');
2366         }
2367     }
2368
2369     if ($xname ne '' && ! &variable_defined ($xname . '_DEPENDENCIES', $cond))
2370     {
2371         define_pretty_variable ($xname . '_DEPENDENCIES', $cond, @dep_list);
2372     }
2373
2374     return $seen_libobjs;
2375 }
2376
2377 # Canonicalize the input parameter
2378 sub canonicalize
2379 {
2380     my ($string) = @_;
2381     $string =~ tr/A-Za-z0-9_\@/_/c;
2382     return $string;
2383 }
2384
2385 # Canonicalize a name, and check to make sure the non-canonical name
2386 # is never used.  Returns canonical name.  Arguments are name and a
2387 # list of suffixes to check for.
2388 sub check_canonical_spelling
2389 {
2390     my ($name, @suffixes) = @_;
2391
2392     my $xname = &canonicalize ($name);
2393     if ($xname ne $name)
2394     {
2395         foreach my $xt (@suffixes)
2396         {
2397             am_macro_error ("$name$xt",
2398                             "invalid variable `$name$xt'; "
2399                             . "should be `$xname$xt'")
2400                 if &variable_defined ("$name$xt");
2401         }
2402     }
2403
2404     return $xname;
2405 }
2406
2407
2408 # handle_compile ()
2409 # -----------------
2410 # Set up the compile suite.
2411 sub handle_compile ()
2412 {
2413     return
2414       unless $get_object_extension_was_run;
2415
2416     # Boilerplate.
2417     my $default_includes = '';
2418     if (! defined $options{'nostdinc'})
2419       {
2420         $default_includes = ' -I. -I$(srcdir)';
2421
2422         if (&variable_defined ('CONFIG_HEADER'))
2423           {
2424             foreach my $hdr (split (' ', &variable_value ('CONFIG_HEADER')))
2425               {
2426                 $default_includes .= ' -I' . dirname ($hdr);
2427               }
2428           }
2429       }
2430
2431     my (@mostly_rms, @dist_rms);
2432     foreach my $item (sort keys %compile_clean_files)
2433     {
2434         if ($compile_clean_files{$item} == $MOSTLY_CLEAN)
2435         {
2436             push (@mostly_rms, "\t-rm -f $item");
2437         }
2438         elsif ($compile_clean_files{$item} == $DIST_CLEAN)
2439         {
2440             push (@dist_rms, "\t-rm -f $item");
2441         }
2442         else
2443         {
2444             &prog_error ("invalid entry in \%compile_clean_files");
2445         }
2446     }
2447
2448     my ($coms, $vars, $rules) =
2449       &file_contents_internal (1, "$libdir/am/compile.am",
2450                                ('DEFAULT_INCLUDES' => $default_includes,
2451                                 'MOSTLYRMS' => join ("\n", @mostly_rms),
2452                                 'DISTRMS' => join ("\n", @dist_rms)));
2453     $output_vars .= $vars;
2454     $output_rules .= "$coms$rules";
2455
2456     # Check for automatic de-ANSI-fication.
2457     if (defined $options{'ansi2knr'})
2458       {
2459         if (! $am_c_prototypes)
2460           {
2461             am_macro_error ('AUTOMAKE_OPTIONS',
2462                             "option `ansi2knr' in use but `AM_C_PROTOTYPES' not in `$configure_ac'");
2463             &keyed_aclocal_warning ('AM_C_PROTOTYPES');
2464             # Only give this error once.
2465             $am_c_prototypes = 1;
2466           }
2467
2468         # topdir is where ansi2knr should be.
2469         if ($options{'ansi2knr'} eq 'ansi2knr')
2470           {
2471             # Only require ansi2knr files if they should appear in
2472             # this directory.
2473             require_file_with_macro ('AUTOMAKE_OPTIONS', $FOREIGN,
2474                                      'ansi2knr.c', 'ansi2knr.1');
2475
2476             # ansi2knr needs to be built before subdirs, so unshift it.
2477             unshift (@all, '$(ANSI2KNR)');
2478           }
2479
2480         my $ansi2knr_dir = '';
2481         $ansi2knr_dir = dirname ($options{'ansi2knr'})
2482           if $options{'ansi2knr'} ne 'ansi2knr';
2483
2484         $output_rules .= &file_contents ('ansi2knr',
2485                                          ('ANSI2KNR-DIR' => $ansi2knr_dir));
2486
2487     }
2488 }
2489
2490 # handle_libtool ()
2491 # -----------------
2492 # Handle libtool rules.
2493 sub handle_libtool
2494 {
2495     return unless $seen_libtool;
2496
2497     # libtool requires some files, but only at top level.
2498     require_conf_file ($libtool_location, $FOREIGN, @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_macro ('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_macro ('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_config_files_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_config_files_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 ! $am_lispdir_location && &variable_defined ('lisp_LISP');
4317
4318     require_conf_file ($am_lispdir_location,  $FOREIGN, 'elisp-comp');
4319     &define_variable ('elisp_comp', $config_aux_dir . '/elisp-comp');
4320 }
4321
4322 # Handle Python
4323 sub handle_python
4324 {
4325     my @pyfiles = &am_install_var ('-defaultdist', 'python', 'PYTHON',
4326                                    'python', 'noinst');
4327     return if ! @pyfiles;
4328
4329     # Found some python.
4330     &am_error ("`python_PYTHON' defined but `AM_PATH_PYTHON' not in `$configure_ac'")
4331         if ! $pythondir_location && &variable_defined ('python_PYTHON');
4332
4333     require_conf_file ($pythondir_location, $FOREIGN, 'py-compile');
4334     &define_variable ('py_compile', $config_aux_dir . '/py-compile');
4335 }
4336
4337 # Handle Java.
4338 sub handle_java
4339 {
4340     my @sourcelist = &am_install_var ('-candist',
4341                                       'java', 'JAVA',
4342                                       'java', 'noinst', 'check');
4343     return if ! @sourcelist;
4344
4345     my %valid = &am_primary_prefixes ('JAVA', 1,
4346                                       'java', 'noinst', 'check');
4347
4348     my $dir;
4349     foreach my $curs (keys %valid)
4350     {
4351         if (! &variable_defined ($curs . '_JAVA') || $curs eq 'EXTRA')
4352         {
4353             next;
4354         }
4355
4356         if (defined $dir)
4357         {
4358             am_macro_error ($curs . '_JAVA',
4359                             "multiple _JAVA primaries in use");
4360         }
4361         $dir = $curs;
4362     }
4363
4364     push (@all, 'class' . $dir . '.stamp');
4365 }
4366
4367
4368 # Handle some of the minor options.
4369 sub handle_minor_options
4370 {
4371     if (defined $options{'readme-alpha'})
4372     {
4373         if ($relative_dir eq '.')
4374         {
4375             if ($package_version !~ /^$GNITS_VERSION_PATTERN$/)
4376             {
4377                 # FIXME: allow real filename.
4378                 &am_file_error ($package_version_location,
4379                                 "version `$package_version' doesn't follow Gnits standards");
4380             }
4381             elsif (defined $1 && -f 'README-alpha')
4382             {
4383                 # This means we have an alpha release.  See
4384                 # GNITS_VERSION_PATTERN for details.
4385                 require_file_with_macro ('AUTOMAKE_OPTIONS',
4386                                          $FOREIGN, 'README-alpha');
4387             }
4388         }
4389     }
4390 }
4391
4392 ################################################################
4393
4394 my %make_list;
4395
4396 # &scan_autoconf_config_files ($CONFIG-FILES)
4397 # -------------------------------------------
4398 # Study $CONFIG-FILES which is the first argument to AC_CONFIG_FILES
4399 # (or AC_OUTPUT).
4400 sub scan_autoconf_config_files
4401 {
4402     my ($config_files) = @_;
4403     # Look at potential Makefile.am's.
4404     foreach (split ' ', $config_files)
4405     {
4406         # Must skip empty string for Perl 4.
4407         next if $_ eq "\\" || $_ eq '';
4408
4409         # Handle $local:$input syntax.  Note that we ignore
4410         # every input file past the first, though we keep
4411         # those around for later.
4412         my ($local, $input, @rest) = split (/:/);
4413         if (! $input)
4414         {
4415             $input = $local;
4416         }
4417         else
4418         {
4419             # FIXME: should be error if .in is missing.
4420             $input =~ s/\.in$//;
4421         }
4422
4423         if (-f $input . '.am')
4424         {
4425             # We have a file that automake should generate.
4426             $make_list{$input} = join (':', ($local, @rest));
4427         }
4428         else
4429         {
4430             # We have a file that automake should cause to be
4431             # rebuilt, but shouldn't generate itself.
4432             push (@other_input_files, $_);
4433         }
4434     }
4435 }
4436
4437
4438 # &scan_autoconf_traces ($FILENAME)
4439 # ---------------------------------
4440 # FIXME: For the time being, we don't care about the FILENAME.
4441 sub scan_autoconf_traces ($)
4442 {
4443   my ($filename) = @_;
4444
4445   my @traced = (
4446                 'AC_CANONICAL_HOST',
4447                 'AC_CANONICAL_SYSTEM',
4448                 'AC_CONFIG_AUX_DIR',
4449                 'AC_CONFIG_FILES',
4450                 'AC_LIBSOURCE',
4451                 'AC_PROG_LIBTOOL', 'AM_PROG_LIBTOOL',
4452                 'AC_PROG_LEX',
4453                 'AC_SUBST',
4454                 'AM_CONDITIONAL',
4455                 'AM_CONFIG_HEADER',
4456                 'AM_C_PROTOTYPES',
4457                 'AM_GNU_GETTEXT',
4458                 'AM_INIT_AUTOMAKE',
4459                 'AM_MAINTAINER_MODE',
4460                 'AM_PATH_LISPDIR',
4461                 'AM_PATH_PYTHON',
4462                 'AM_PROG_CC_C_O',
4463                );
4464
4465   my $traces = "$ENV{amtraces} ";
4466
4467   # Use a separator unlikely to be used, not `:', the default, which
4468   # has a precise meaning for AC_CONFIG_FILES and so on.
4469   $traces .= join (' ',
4470                    map { "--trace=$_" . ':\$f:\$l::\$n::\${::}%' } @traced);
4471
4472   my $tracefh = new Automake::XFile ("$traces |");
4473   verbose "reading $traces";
4474
4475   while ($_ = $tracefh->getline)
4476     {
4477       chomp;
4478       my ($here, @args) = split /::/;
4479       my $macro = $args[0];
4480
4481       # Alphabetical ordering please.
4482       if ($macro eq 'AC_CANONICAL_HOST')
4483         {
4484           $seen_canonical = $AC_CANONICAL_HOST
4485             if ! $seen_canonical;
4486         }
4487       elsif ($macro eq 'AC_CANONICAL_SYSTEM')
4488         {
4489           $seen_canonical = $AC_CANONICAL_SYSTEM;
4490         }
4491       elsif ($macro eq 'AC_CONFIG_AUX_DIR')
4492         {
4493           @config_aux_path = $args[1];
4494           $config_aux_dir_set_in_configure_in = 1;
4495         }
4496       elsif ($macro eq 'AC_CONFIG_FILES')
4497         {
4498           # Look at potential Makefile.am's.
4499           $ac_config_files_location = $here;
4500           &scan_autoconf_config_files ($args[1]);
4501         }
4502       elsif ($macro eq 'AC_LIBSOURCE')
4503         {
4504           # We should actually also `close' the sources: getopt.c
4505           # wants getopt.h etc.  But actually it should be done in the
4506           # macro itself, i.e., we have to first fix Autoconf to extend
4507           # _AC_LIBOBJ_DECL and use it the in various macros.
4508           $libsources{$args[1]} = $here;
4509         }
4510       elsif ($macro =~ /A(C|M)_PROG_LIBTOOL/)
4511         {
4512           $seen_libtool = $here;
4513           $libtool_location = $here;
4514         }
4515       elsif ($macro =~ /AC_PROG_LEX/)
4516         {
4517           $seen_prog_lex = $here;
4518         }
4519       elsif ($macro eq 'AC_SUBST')
4520         {
4521           # Just check for alphanumeric in AC_SUBST.  If you do
4522           # AC_SUBST(5), then too bad.
4523           $configure_vars{$args[1]} = $here
4524             if $args[1] =~ /^\w+$/;
4525         }
4526       elsif ($macro eq 'AM_CONDITIONAL')
4527         {
4528           $configure_cond{$args[1]} = $here;
4529         }
4530       elsif ($macro eq 'AM_CONFIG_HEADER')
4531         {
4532           $config_header_location = $here;
4533           foreach my $one_hdr (split (' ', $args[1]))
4534             {
4535               push (@config_fullnames, $one_hdr);
4536               if ($one_hdr =~ /^([^:]+):(.+)$/)
4537                 {
4538                   push (@config_names, $1);
4539                   push (@config_headers, $2);
4540                 }
4541               else
4542                 {
4543                   push (@config_names, $one_hdr);
4544                   push (@config_headers, $one_hdr . '.in');
4545                 }
4546             }
4547         }
4548       elsif ($macro eq 'AM_C_PROTOTYPES')
4549         {
4550           $am_c_prototypes = $here;
4551         }
4552       elsif ($macro eq 'AM_GNU_GETTEXT')
4553         {
4554           $seen_gettext = $here;
4555           $ac_gettext_location = $here;
4556         }
4557       elsif ($macro eq 'AM_INIT_AUTOMAKE')
4558         {
4559           $package_version = $args[2];
4560           $package_version_location = $here;
4561           $seen_init_automake = 1;
4562         }
4563       elsif ($macro eq 'AM_MAINTAINER_MODE')
4564         {
4565           $seen_maint_mode = $here;
4566         }
4567       elsif ($macro eq 'AM_PATH_LISPDIR')
4568         {
4569           $am_lispdir_location = $here;
4570         }
4571       elsif ($macro eq 'AM_PATH_PYTHON')
4572         {
4573           $pythondir_location = $here;
4574         }
4575       elsif ($macro eq 'AM_PROG_CC_C_O')
4576         {
4577           $seen_cc_c_o = $here;
4578         }
4579    }
4580 }
4581
4582
4583 # &scan_one_autoconf_file ($FILENAME)
4584 # -----------------------------------
4585 # Scan one file for interesting things.  Subroutine of
4586 # &scan_autoconf_files.
4587 sub scan_one_autoconf_file
4588 {
4589     my ($filename) = @_;
4590
4591     # Some macros already provide the right traces to enable generic
4592     # code and specific arguments, instead of dedicated code.  But
4593     # currently we don't handle traces.  Rewrite these dedicated
4594     # macros handling into the generic macro invocation, and let our
4595     # generic case handle them.
4596
4597     my %generalize =
4598       (
4599        'AC_FUNC_ALLOCA'           => 'AC_LIBSOURCES([alloca.c])',
4600        'AC_FUNC_GETLOADAVG'       => 'AC_LIBSOURCES([getloadavg.c])',
4601        'AC_FUNC_MEMCMP'           => 'AC_LIBSOURCES([memcmp.c])',
4602        'AC_STRUCT_ST_BLOCKS'      => 'AC_LIBSOURCES([fileblocks.c])',
4603        'A[CM]_REPLACE_GNU_GETOPT' => 'AC_LIBSOURCES([getopt.c, getopt1.c])',
4604        'A[CM]_FUNC_STRTOD'        => 'AC_LIBSOURCES([strtod.c])',
4605        'AM_WITH_REGEX'      => 'AC_LIBSOURCES([rx.c, rx.h, regex.c, regex.h])',
4606        'AC_FUNC_MKTIME'           => 'AC_LIBSOURCES([mktime.c])',
4607        'A[CM]_FUNC_ERROR_AT_LINE' => 'AC_LIBSOURCES([error.c, error.h])',
4608        'A[CM]_FUNC_OBSTACK'       => 'AC_LIBSOURCES([obstack.c, obstack.h])',
4609       );
4610
4611     my $configfh = new Automake::XFile ("< $filename");
4612     print "$me: reading $filename\n" if $verbose;
4613
4614     my ($in_ac_output, $in_ac_replace) = (0, 0);
4615     while ($_ = $configfh->getline)
4616     {
4617         # Remove comments from current line.
4618         s/\bdnl\b.*$//;
4619         s/\#.*$//;
4620
4621         # Skip macro definitions.  Otherwise we might be confused into
4622         # thinking that a macro that was only defined was actually
4623         # used.
4624         next if /AC_DEFUN/;
4625
4626         # Follow includes.  This is a weirdness commonly in use at
4627         # Cygnus and hopefully nowhere else.
4628         if (/sinclude\((.*)\)/ && -f $1)
4629         {
4630             # $_ being local, if we don't preserve it, when coming
4631             # back we will have $_ undefined, which is bad for the
4632             # the rest of this routine.
4633             my $underscore = $_;
4634             &scan_one_autoconf_file ($1);
4635             $_ = $underscore;
4636         }
4637
4638         for my $generalize (keys %generalize)
4639           {
4640             s/$generalize/$generalize{$generalize}/g;
4641           }
4642
4643
4644         my $here = "$filename:$.";
4645
4646         # Populate libobjs array.
4647         if (/LIBOBJS="(.*)\s+\$LIBOBJS"/
4648                || /LIBOBJS="\$LIBOBJS\s+(.*)"/)
4649         {
4650             foreach my $libobj_iter (split (' ', $1))
4651             {
4652                 if ($libobj_iter =~ /^(.*)\.o(bj)?$/
4653                     || $libobj_iter =~ /^(.*)\.\$ac_objext$/
4654                     || $libobj_iter =~ /^(.*)\.\$\{ac_objext\}$/)
4655                 {
4656                     $libsources{$1 . '.c'} = $here;
4657                 }
4658             }
4659         }
4660         elsif (/AC_LIBOBJ\(([^)]+)\)/)
4661         {
4662             $libsources{"$1.c"} = $here;
4663         }
4664         elsif (/AC_LIBSOURCE\(([^)]+)\)/)
4665         {
4666             $libsources{&unquote_m4_arg ($1)} = $here;
4667         }
4668         elsif (/AC_LIBSOURCES\(([^)]+)\)/)
4669         {
4670             foreach my $lc_iter (split (/[, ]+/, &unquote_m4_arg ($1)))
4671             {
4672                 $libsources{$lc_iter} = $here;
4673             }
4674         }
4675
4676         if (! $in_ac_replace && s/AC_REPLACE_FUNCS\s*\(\[?//)
4677         {
4678             $in_ac_replace = 1;
4679         }
4680         if ($in_ac_replace)
4681         {
4682             $in_ac_replace = 0 if s/[\]\)].*$//;
4683             # Remove trailing backslash.
4684             s/\\$//;
4685             foreach (split)
4686             {
4687                 # Need to skip empty elements for Perl 4.
4688                 next if $_ eq '';
4689                 $libsources{$_ . '.c'} = $here;
4690             }
4691         }
4692
4693         if (/$obsolete_rx/o)
4694         {
4695             my $hint = '';
4696             if ($obsolete_macros{$1} ne '')
4697             {
4698                 $hint = '; ' . $obsolete_macros{$1};
4699             }
4700             &am_file_error ($here, "`$1' is obsolete$hint");
4701         }
4702
4703         # Process the AC_OUTPUT and AC_CONFIG_FILES macros.
4704         if (! $in_ac_output && s/(AC_(OUTPUT|CONFIG_FILES))\s*\(\[?//)
4705         {
4706             $in_ac_output = $1;
4707             $ac_config_files_location = $here;
4708         }
4709         if ($in_ac_output)
4710         {
4711             my $closing = 0;
4712             if (s/[\]\),].*$//)
4713             {
4714                 $in_ac_output = 0;
4715                 $closing = 1;
4716             }
4717
4718             # Look at potential Makefile.am's.
4719             &scan_autoconf_config_files ($_);
4720
4721             if ($closing
4722                 && scalar keys %make_list == 0
4723                 && @other_input_files == 0)
4724             {
4725                 am_file_error ($ac_config_files_location,
4726                                "no files mentioned in `$in_ac_output'");
4727                 exit 1;
4728             }
4729         }
4730
4731         if (/$AC_CONFIG_AUX_DIR_PATTERN/o)
4732         {
4733             @config_aux_path = &unquote_m4_arg ($1);
4734             $config_aux_dir_set_in_configure_in = $here;
4735         }
4736
4737         # Check for ansi2knr.
4738         $am_c_prototypes = $here if /AM_C_PROTOTYPES/;
4739
4740         # Check for `-c -o' code.
4741         $seen_cc_c_o = $here if /AM_PROG_CC_C_O/;
4742
4743         # Check for NLS support.
4744         if (/AM_GNU_GETTEXT/)
4745         {
4746             $seen_gettext = $here;
4747             $ac_gettext_location = $here;
4748         }
4749
4750         # Handle configuration headers.  A config header of `[$1]'
4751         # means we are actually scanning AM_CONFIG_HEADER from
4752         # aclocal.m4.
4753         if (/A([CM])_CONFIG_HEADERS?\s*\((.*)\)/
4754             && $2 ne '[$1]')
4755         {
4756             &am_file_error ($here,
4757                "`automake requires `AM_CONFIG_HEADER', not `AC_CONFIG_HEADER'")
4758               if $1 eq 'C';
4759
4760             $config_header_location = $here;
4761             foreach my $one_hdr (split (' ', &unquote_m4_arg ($2)))
4762             {
4763                 push (@config_fullnames, $one_hdr);
4764                 if ($one_hdr =~ /^([^:]+):(.+)$/)
4765                 {
4766                     push (@config_names, $1);
4767                     push (@config_headers, $2);
4768                 }
4769                 else
4770                 {
4771                     push (@config_names, $one_hdr);
4772                     push (@config_headers, $one_hdr . '.in');
4773                 }
4774             }
4775         }
4776
4777         # Handle AC_CANONICAL_*.  Always allow upgrading to
4778         # AC_CANONICAL_SYSTEM, but never downgrading.
4779         $seen_canonical = $AC_CANONICAL_HOST
4780             if ! $seen_canonical
4781                 && (/AC_CANONICAL_HOST/ || /AC_CHECK_TOOL/);
4782         $seen_canonical = $AC_CANONICAL_SYSTEM if /AC_CANONICAL_SYSTEM/;
4783
4784         # If using X, include some extra variable definitions.  NOTE
4785         # we don't want to force these into CFLAGS or anything,
4786         # because not all programs will necessarily use X.
4787         if (/AC_PATH_XTRA/)
4788           {
4789             foreach my $var ('X_CFLAGS', 'X_LIBS', 'X_EXTRA_LIBS',
4790                              'X_PRE_LIBS')
4791               {
4792                 $configure_vars{$var} = $here;
4793               }
4794           }
4795
4796         # This macro handles several different things.
4797         if (/$AM_INIT_AUTOMAKE_PATTERN/o)
4798         {
4799             ($package_version = $1) =~ s/$AM_PACKAGE_VERSION_PATTERN/$1/o;
4800             $package_version_location = $here;
4801             $seen_init_automake = $here;
4802         }
4803
4804         if (/AM_PROG_LEX/)
4805         {
4806             $configure_vars{'LEX'} = $here;
4807             $seen_prog_lex = $here;
4808         }
4809         if (/AC_PROG_LEX/ && $filename =~ /configure\.(ac|in)$/)
4810         {
4811             $configure_vars{'LEX'} = $here;
4812             $seen_prog_lex = $here;
4813             &am_file_warning ($here,
4814                    "automake requires `AM_PROG_LEX', not `AC_PROG_LEX'");
4815         }
4816
4817         if (/AC_PROG_(F77|YACC|RANLIB|CC|CXXCPP|CXX|LEX|AWK|CPP|LN_S)/)
4818         {
4819             $configure_vars{$1} = $here;
4820         }
4821         if (/$AC_CHECK_PATTERN/o)
4822         {
4823             $configure_vars{$3} = $here;
4824         }
4825         if (/$AM_MISSING_PATTERN/o
4826             && $1 ne 'ACLOCAL'
4827             && $1 ne 'AUTOCONF'
4828             && $1 ne 'AUTOMAKE'
4829             && $1 ne 'AUTOHEADER'
4830             # AM_INIT_AUTOMAKE is AM_MISSING_PROG'ing MAKEINFO.  But
4831             # we handle it elsewhere.
4832             && $1 ne 'MAKEINFO')
4833         {
4834             $configure_vars{$1} = $here;
4835         }
4836
4837         # Explicitly avoid ANSI2KNR -- we AC_SUBST that in protos.m4,
4838         # but later define it elsewhere.  This is pretty hacky.  We
4839         # also explicitly avoid INSTALL_SCRIPT and some other
4840         # variables because they are defined in header-vars.am.
4841         # AMDEPBACKSLASH might be subst'd by `\', which certainly would
4842         # not be appreciated by Make.
4843         if (/$AC_SUBST_PATTERN/o
4844             && $1 ne 'ANSI2KNR'
4845             && $1 ne 'INSTALL_SCRIPT'
4846             && $1 ne 'INSTALL_DATA'
4847             && $1 ne 'AMDEPBACKSLASH')
4848         {
4849             $configure_vars{$1} = $here;
4850         }
4851
4852         if (/AM_MAINTAINER_MODE/)
4853         {
4854             $seen_maint_mode = $here;
4855             $configure_cond{'MAINTAINER_MODE'} = $here;
4856         }
4857
4858         $am_lispdir_location = $here if /AM_PATH_LISPDIR/;
4859
4860         if (/AM_PATH_PYTHON/)
4861           {
4862             $pythondir_location = $here;
4863             $configure_vars{'pythondir'} = $here;
4864             $configure_vars{'PYTHON'} = $here;
4865           }
4866
4867         if (/A(C|M)_PROG_LIBTOOL/)
4868         {
4869             # We're not ready for this yet.  People still use a
4870             # libtool with no AC_PROG_LIBTOOL.  Once that is the
4871             # dominant version we can reenable this code -- but next
4872             # time by mentioning the macro in %obsolete_macros, both
4873             # here and in aclocal.in.
4874
4875             # if (/AM_PROG_LIBTOOL/)
4876             # {
4877             #   &am_file_warning ($here, "`AM_PROG_LIBTOOL' is obsolete, use `AC_PROG_LIBTOOL' instead");
4878             # }
4879             $seen_libtool = $here;
4880             $libtool_location = $here;
4881             $configure_vars{'LIBTOOL'} = $here;
4882             $configure_vars{'RANLIB'} = $here;
4883             $configure_vars{'CC'} = $here;
4884             # AC_PROG_LIBTOOL runs AC_CANONICAL_HOST.  Make sure we
4885             # never downgrade (if we've seen AC_CANONICAL_SYSTEM).
4886             $seen_canonical = $AC_CANONICAL_HOST if ! $seen_canonical;
4887         }
4888
4889         $seen_multilib = $here if (/AM_ENABLE_MULTILIB/);
4890
4891         if (/$AM_CONDITIONAL_PATTERN/o)
4892         {
4893             $configure_cond{$1} = $here;
4894         }
4895
4896         # Check for Fortran 77 intrinsic and run-time libraries.
4897         if (/AC_F77_LIBRARY_LDFLAGS/)
4898         {
4899             $configure_vars{'FLIBS'} = $here;
4900         }
4901     }
4902
4903     $configfh->close;
4904 }
4905
4906
4907 # &scan_autoconf_files ()
4908 # -----------------------
4909 # Check whether we use `configure.ac' or `configure.in'.
4910 # Scan it (and possibly `aclocal.m4') for interesting things.
4911 # We must scan aclocal.m4 because there might be AC_SUBSTs and such there.
4912 sub scan_autoconf_files
4913 {
4914     # Reinitialize libsources here.  This isn't really necessary,
4915     # since we currently assume there is only one configure.ac.  But
4916     # that won't always be the case.
4917     %libsources = ();
4918
4919     $configure_ac = find_configure_ac;
4920     die "$me: `configure.ac' or `configure.in' is required\n"
4921         if !$configure_ac;
4922
4923     if (defined $ENV{'amtraces'})
4924     {
4925         print STDERR "$me: Autoconf traces is an experimental feature\n";
4926         print STDERR "$me: use at your own risks\n";
4927
4928         scan_autoconf_traces ($configure_ac);
4929     }
4930     else
4931       {
4932         scan_one_autoconf_file ($configure_ac);
4933         scan_one_autoconf_file ('aclocal.m4')
4934           if -f 'aclocal.m4';
4935       }
4936
4937     # Set input and output files if not specified by user.
4938     if (! @input_files)
4939     {
4940         @input_files = sort keys %make_list;
4941         %output_files = %make_list;
4942     }
4943
4944     @configure_input_files = sort keys %make_list;
4945
4946     &am_conf_error ("`AM_INIT_AUTOMAKE' must be used")
4947         if ! $seen_init_automake;
4948
4949     # Look for some files we need.  Always check for these.  This
4950     # check must be done for every run, even those where we are only
4951     # looking at a subdir Makefile.  We must set relative_dir so that
4952     # the file-finding machinery works.
4953     # FIXME: Is this broken because it needs dynamic scopes.
4954     # My tests seems to show it's not the case.
4955     $relative_dir = '.';
4956     &require_config_file ($FOREIGN, 'install-sh', 'mkinstalldirs', 'missing');
4957     &am_error ("`install.sh' is an anachronism; use `install-sh' instead")
4958         if -f $config_aux_path[0] . '/install.sh';
4959
4960     &require_config_file ($FOREIGN, 'py-compile')
4961         if $pythondir_location;
4962
4963     # Preserve dist_common for later.
4964     $configure_dist_common = variable_value ('DIST_COMMON', 'TRUE') || '';
4965 }
4966
4967 ################################################################
4968
4969 # Set up for Cygnus mode.
4970 sub check_cygnus
4971 {
4972     return unless $cygnus_mode;
4973
4974     &set_strictness ('foreign');
4975     $options{'no-installinfo'} = 1;
4976     $options{'no-dependencies'} = 1;
4977     $use_dependencies = 0;
4978
4979     am_conf_error ("`AM_MAINTAINER_MODE' required when --cygnus specified")
4980       if !$seen_maint_mode;
4981 }
4982
4983 # Do any extra checking for GNU standards.
4984 sub check_gnu_standards
4985 {
4986     if ($relative_dir eq '.')
4987     {
4988         # In top level (or only) directory.
4989         require_file ('',
4990                       $GNU, 'INSTALL', 'NEWS', 'README', 'COPYING',
4991                       'AUTHORS', 'ChangeLog');
4992     }
4993
4994     if ($strictness >= $GNU
4995         && defined $options{'no-installman'})
4996     {
4997         am_macro_error ('AUTOMAKE_OPTIONS',
4998                         "option `no-installman' disallowed by GNU standards");
4999     }
5000
5001     if ($strictness >= $GNU
5002         && defined $options{'no-installinfo'})
5003     {
5004         am_macro_error ('AUTOMAKE_OPTIONS',
5005                         "option `no-installinfo' disallowed by GNU standards");
5006     }
5007 }
5008
5009 # Do any extra checking for GNITS standards.
5010 sub check_gnits_standards
5011 {
5012     if ($relative_dir eq '.')
5013     {
5014         # In top level (or only) directory.
5015         require_file ('', $GNITS, 'THANKS');
5016     }
5017 }
5018
5019 ################################################################
5020 #
5021 # Functions to handle files of each language.
5022
5023 # Each `lang_X_rewrite($DIRECTORY, $BASE, $EXT)' function follows a
5024 # simple formula: Return value is $LANG_SUBDIR if the resulting object
5025 # file should be in a subdir if the source file is, $LANG_PROCESS if
5026 # file is to be dealt with, $LANG_IGNORE otherwise.
5027
5028 # Much of the actual processing is handled in
5029 # handle_single_transform_list.  These functions exist so that
5030 # auxiliary information can be recorded for a later cleanup pass.
5031 # Note that the calls to these functions are computed, so don't bother
5032 # searching for their precise names in the source.
5033
5034 # This is just a convenience function that can be used to determine
5035 # when a subdir object should be used.
5036 sub lang_sub_obj
5037 {
5038     return defined $options{'subdir-objects'} ? $LANG_SUBDIR : $LANG_PROCESS;
5039 }
5040
5041 # Rewrite a single C source file.
5042 sub lang_c_rewrite
5043 {
5044     my ($directory, $base, $ext) = @_;
5045
5046     if (defined $options{'ansi2knr'} && $base =~ /_$/)
5047     {
5048         # FIXME: include line number in error.
5049         &am_error ("C source file `$base.c' would be deleted by ansi2knr rules");
5050     }
5051
5052     my $r = $LANG_PROCESS;
5053     if (defined $options{'subdir-objects'})
5054     {
5055         $r = $LANG_SUBDIR;
5056         $base = $directory . '/' . $base;
5057
5058         if (! $seen_cc_c_o)
5059         {
5060             # Only give error once.
5061             $seen_cc_c_o = 1;
5062             # FIXME: line number.
5063             &am_error ("C objects in subdir but `AM_PROG_CC_C_O' not in `$configure_ac'");
5064         }
5065
5066         &require_conf_file ($FOREIGN, 'compile');
5067     }
5068
5069     $de_ansi_files{$base} = 1;
5070     return $r;
5071 }
5072
5073 # Rewrite a single C++ source file.
5074 sub lang_cxx_rewrite
5075 {
5076     return &lang_sub_obj;
5077 }
5078
5079 # Rewrite a single header file.
5080 sub lang_header_rewrite
5081 {
5082     # Header files are simply ignored.
5083     return $LANG_IGNORE;
5084 }
5085
5086 # Rewrite a single yacc file.
5087 sub lang_yacc_rewrite
5088 {
5089     my ($directory, $base, $ext) = @_;
5090
5091     my $r = &lang_sub_obj;
5092     (my $newext = $ext) =~ tr/y/c/;
5093     return ($r, $newext);
5094 }
5095
5096 # Rewrite a single yacc++ file.
5097 sub lang_yaccxx_rewrite
5098 {
5099     my ($directory, $base, $ext) = @_;
5100
5101     my $r = &lang_sub_obj;
5102     (my $newext = $ext) =~ tr/y/c/;
5103     return ($r, $newext);
5104 }
5105
5106 # Rewrite a single lex file.
5107 sub lang_lex_rewrite
5108 {
5109     my ($directory, $base, $ext) = @_;
5110
5111     my $r = &lang_sub_obj;
5112     (my $newext = $ext) =~ tr/l/c/;
5113     return ($r, $newext);
5114 }
5115
5116 # Rewrite a single lex++ file.
5117 sub lang_lexxx_rewrite
5118 {
5119     my ($directory, $base, $ext) = @_;
5120
5121     my $r = &lang_sub_obj;
5122     (my $newext = $ext) =~ tr/l/c/;
5123     return ($r, $newext);
5124 }
5125
5126 # Rewrite a single assembly file.
5127 sub lang_asm_rewrite
5128 {
5129     return &lang_sub_obj;
5130 }
5131
5132 # Rewrite a single Fortran 77 file.
5133 sub lang_f77_rewrite
5134 {
5135     return $LANG_PROCESS;
5136 }
5137
5138 # Rewrite a single preprocessed Fortran 77 file.
5139 sub lang_ppf77_rewrite
5140 {
5141     return $LANG_PROCESS;
5142 }
5143
5144 # Rewrite a single ratfor file.
5145 sub lang_ratfor_rewrite
5146 {
5147     return $LANG_PROCESS;
5148 }
5149
5150 # Rewrite a single Objective C file.
5151 sub lang_objc_rewrite
5152 {
5153     return &lang_sub_obj;
5154 }
5155
5156 # Rewrite a single Java file.
5157 sub lang_java_rewrite
5158 {
5159     return $LANG_SUBDIR;
5160 }
5161
5162 # The lang_X_finish functions are called after all source file
5163 # processing is done.  Each should handle defining rules for the
5164 # language, etc.  A finish function is only called if a source file of
5165 # the appropriate type has been seen.
5166
5167 sub lang_c_finish
5168 {
5169     # Push all libobjs files onto de_ansi_files.  We actually only
5170     # push files which exist in the current directory, and which are
5171     # genuine source files.
5172     foreach my $file (keys %libsources)
5173     {
5174         if ($file =~ /^(.*)\.[cly]$/ && -f "$relative_dir/$file")
5175         {
5176             $de_ansi_files{$1} = 1;
5177         }
5178     }
5179
5180     if (defined $options{'ansi2knr'} && keys %de_ansi_files)
5181     {
5182         # Make all _.c files depend on their corresponding .c files.
5183         my @objects;
5184         foreach my $base (sort keys %de_ansi_files)
5185         {
5186             # Each _.c file must depend on ansi2knr; otherwise it
5187             # might be used in a parallel build before it is built.
5188             # We need to support files in the srcdir and in the build
5189             # dir (because these files might be auto-generated.  But
5190             # we can't use $< -- some makes only define $< during a
5191             # suffix rule.
5192             $output_rules .= ($base . "_.c: $base.c \$(ANSI2KNR)\n\t"
5193                               . '$(CPP) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) '
5194                               . '`if test -f $(srcdir)/' . $base . '.c'
5195                               . '; then echo $(srcdir)/' . $base . '.c'
5196                               . '; else echo ' . $base . '.c; fi` '
5197                               . "| sed 's/^# \\([0-9]\\)/#line \\1/' "
5198                               . '| $(ANSI2KNR) > ' . $base . "_.c"
5199                               # If ansi2knr fails then we shouldn't
5200                               # create the _.c file
5201                               . " || rm -f ${base}_.c\n");
5202             push (@objects, $base . '_.$(OBJEXT)');
5203             push (@objects, $base . '_.lo')
5204               if $seen_libtool;
5205         }
5206
5207         # Make all _.o (and _.lo) files depend on ansi2knr.
5208         # Use a sneaky little hack to make it print nicely.
5209         &pretty_print_rule ('', '', @objects, ':', '$(ANSI2KNR)');
5210     }
5211 }
5212
5213 # This is a yacc helper which is called whenever we have decided to
5214 # compile a yacc file.
5215 sub lang_yacc_target_hook
5216 {
5217     my ($self, $aggregate, $output, $input) = @_;
5218
5219     my $flag = $aggregate . "_YFLAGS";
5220     if ((&variable_defined ($flag)
5221          && &variable_value ($flag) =~ /$DASH_D_PATTERN/o)
5222         || (&variable_defined ('YFLAGS')
5223             && &variable_value ('YFLAGS') =~ /$DASH_D_PATTERN/o))
5224     {
5225         (my $output_base = $output) =~ s/\..*$//;
5226         my $header = $output_base . '.h';
5227
5228         # Found a `-d' that applies to the compilation of this file.
5229         # Add a dependency for the generated header file, and arrange
5230         # for that file to be included in the distribution.
5231         # FIXME: this fails for `nodist_*_SOURCES'.
5232         $output_rules .= "${header}: $output\n";
5233         &push_dist_common ($header);
5234         # If the files are built in the build directory, then we want
5235         # to remove them with `make clean'.  If they are in srcdir
5236         # they shouldn't be touched.  However, we can't determine this
5237         # statically, and the GNU rules say that yacc/lex output files
5238         # should be removed by maintainer-clean.  So that's what we
5239         # do.
5240         push (@maintainer_clean_files, $header);
5241     }
5242 }
5243
5244 # This is a helper for both lex and yacc.
5245 sub yacc_lex_finish_helper
5246 {
5247     return if defined $language_scratch{'lex-yacc-done'};
5248     $language_scratch{'lex-yacc-done'} = 1;
5249
5250     # If there is more than one distinct yacc (resp lex) source file
5251     # in a given directory, then the `ylwrap' program is required to
5252     # allow parallel builds to work correctly.  FIXME: for now, no
5253     # line number.
5254     &require_config_file ($FOREIGN, 'ylwrap');
5255     if ($config_aux_dir_set_in_configure_in)
5256     {
5257         &define_variable ('YLWRAP', $config_aux_dir . "/ylwrap");
5258     }
5259     else
5260     {
5261         &define_variable ('YLWRAP', '$(top_srcdir)/ylwrap');
5262     }
5263 }
5264
5265 sub lang_yacc_finish
5266 {
5267     return if defined $language_scratch{'yacc-done'};
5268     $language_scratch{'yacc-done'} = 1;
5269
5270     if (&variable_defined ('YACCFLAGS'))
5271     {
5272         am_macro_error ('YACCFLAGS',
5273                         "`YACCFLAGS' obsolete; use `YFLAGS' instead");
5274     }
5275
5276     if (count_files_for_language ('yacc') > 1)
5277     {
5278         &yacc_lex_finish_helper;
5279     }
5280 }
5281
5282
5283 sub lang_lex_finish
5284 {
5285     return if defined $language_scratch{'lex-done'};
5286     $language_scratch{'lex-done'} = 1;
5287
5288     if (! $seen_prog_lex)
5289     {
5290         &am_error ("lex source seen but `AM_PROG_LEX' not in `$configure_ac'");
5291     }
5292
5293     if (count_files_for_language ('lex') > 1)
5294     {
5295         &yacc_lex_finish_helper;
5296     }
5297 }
5298
5299
5300 # Given a hash table of linker names, pick the name that has the most
5301 # precedence.  This is lame, but something has to have global
5302 # knowledge in order to eliminate the conflict.  Add more linkers as
5303 # required.
5304 sub resolve_linker
5305 {
5306     my (%linkers) = @_;
5307
5308     return 'GCJLINK'
5309         if defined $linkers{'GCJLINK'};
5310     return 'CXXLINK'
5311         if defined $linkers{'CXXLINK'};
5312     return 'F77LINK'
5313         if defined $linkers{'F77LINK'};
5314     return 'OBJCLINK'
5315         if defined $linkers{'OBJCLINK'};
5316     return 'LINK';
5317 }
5318
5319 # Called to indicate that an extension was used.
5320 sub saw_extension
5321 {
5322     my ($ext) = @_;
5323     if (! defined $extension_seen{$ext})
5324     {
5325         $extension_seen{$ext} = 1;
5326     }
5327     else
5328     {
5329         ++$extension_seen{$ext};
5330     }
5331 }
5332
5333 # Return the number of files seen for a given language.  Knows about
5334 # special cases we care about.  FIXME: this is hideous.  We need
5335 # something that involves real language objects.  For instance yacc
5336 # and yaccxx could both derive from a common yacc class which would
5337 # know about the strange ylwrap requirement.  (Or better yet we could
5338 # just not support legacy yacc!)
5339 sub count_files_for_language
5340 {
5341     my ($name) = @_;
5342
5343     my @names;
5344     if ($name eq 'yacc' || $name eq 'yaccxx')
5345     {
5346         @names = ('yacc', 'yaccxx');
5347     }
5348     elsif ($name eq 'lex' || $name eq 'lexxx')
5349     {
5350         @names = ('lex', 'lexxx');
5351     }
5352     else
5353     {
5354         @names = ($name);
5355     }
5356
5357     my $r = 0;
5358     foreach $name (@names)
5359     {
5360         my $lang = $languages{$name};
5361         foreach my $ext (@{$lang->extensions})
5362         {
5363             $r += $extension_seen{$ext}
5364                 if defined $extension_seen{$ext};
5365         }
5366     }
5367
5368     return $r
5369 }
5370
5371 # Called to ask whether source files have been seen . If HEADERS is 1,
5372 # headers can be included.
5373 sub saw_sources_p
5374 {
5375     my ($headers) = @_;
5376
5377     # count all the sources
5378     my $count = 0;
5379     foreach my $val (values %extension_seen)
5380     {
5381         $count += $val;
5382     }
5383
5384     if (!$headers)
5385     {
5386         $count -= count_files_for_language ('header');
5387     }
5388
5389     return $count > 0;
5390 }
5391
5392
5393 # register_language (%ATTRIBUTE)
5394 # ------------------------------
5395 # Register a single language.
5396 # Each %ATTRIBUTE is of the form ATTRIBUTE => VALUE.
5397 sub register_language (%)
5398 {
5399     my (%option) = @_;
5400
5401     # Set the defaults.
5402     $option{'ansi'} = 0
5403       unless defined $option{'ansi'};
5404     $option{'autodep'} = 'no'
5405       unless defined $option{'autodep'};
5406     $option{'linker'} = ''
5407       unless defined $option{'linker'};
5408     $option{'define_flag'} = 1
5409       unless defined $option{'define_flag'};
5410
5411     my $lang = new Language (%option);
5412
5413     # Fill indexes.
5414     grep ($extension_map{$_} = $lang->name, @{$lang->extensions});
5415     $languages{$lang->name} = $lang;
5416 }
5417
5418 # This function is used to find a path from a user-specified suffix to
5419 # `o' or to some other suffix we recognize internally, eg `cc'.
5420 sub derive_suffix
5421 {
5422     my ($source_ext) = @_;
5423
5424     # FIXME: hard-coding `o' is a mistake.  Doing something
5425     # intelligent is harder.
5426     while (! $extension_map{$source_ext}
5427            && $source_ext ne 'o'
5428            && defined $suffix_rules{$source_ext})
5429     {
5430         $source_ext = $suffix_rules{$source_ext};
5431     }
5432
5433     return $source_ext;
5434 }
5435
5436
5437 ################################################################
5438
5439 # Pretty-print something.  HEAD is what should be printed at the
5440 # beginning of the first line, FILL is what should be printed at the
5441 # beginning of every subsequent line.
5442 sub pretty_print_internal
5443 {
5444     my ($head, $fill, @values) = @_;
5445
5446     my $column = length ($head);
5447     my $result = $head;
5448
5449     # Fill length is number of characters.  However, each Tab
5450     # character counts for eight.  So we count the number of Tabs and
5451     # multiply by 7.
5452     my $fill_length = length ($fill);
5453     $fill_length += 7 * ($fill =~ tr/\t/\t/d);
5454
5455     foreach (@values)
5456     {
5457         # "71" because we also print a space.
5458         if ($column + length ($_) > 71)
5459         {
5460             $result .= " \\\n" . $fill;
5461             $column = $fill_length;
5462         }
5463         $result .= ' ' if $result =~ /\S\z/;
5464         $result .= $_;
5465         $column += length ($_) + 1;
5466     }
5467
5468     $result .= "\n";
5469     return $result;
5470 }
5471
5472 # Pretty-print something and append to output_vars.
5473 sub pretty_print
5474 {
5475     $output_vars .= &pretty_print_internal (@_);
5476 }
5477
5478 # Pretty-print something and append to output_rules.
5479 sub pretty_print_rule
5480 {
5481     $output_rules .= &pretty_print_internal (@_);
5482 }
5483
5484
5485 ################################################################
5486
5487
5488 # $STRING
5489 # &conditional_string(@COND-STACK)
5490 # --------------------------------
5491 # Build a string which denotes the conditional in @COND-STACK.  Some
5492 # simplifications are done: `TRUE' entries are elided, and any `FALSE'
5493 # entry results in a return of `FALSE'.
5494 sub conditional_string
5495 {
5496   my (@stack) = @_;
5497
5498   if (grep (/^FALSE$/, @stack))
5499     {
5500       return 'FALSE';
5501     }
5502   else
5503     {
5504       return join (' ', uniq sort grep (!/^TRUE$/, @stack));
5505     }
5506 }
5507
5508
5509 # $BOOLEAN
5510 # &conditional_true_when ($COND, $WHEN)
5511 # -------------------------------------
5512 # See if a conditional is true.  Both arguments are conditional
5513 # strings.  This returns true if the first conditional is true when
5514 # the second conditional is true.
5515 # For instance with $COND = `BAR FOO', and $WHEN = `BAR BAZ FOO',
5516 # obviously return 1, and 0 when, for instance, $WHEN = `FOO'.
5517 sub conditional_true_when ($$)
5518 {
5519     my ($cond, $when) = @_;
5520
5521     # Make a hash holding all the values from $WHEN.
5522     my %cond_vals = map { $_ => 1 } split (' ', $when);
5523
5524     # Check each component of $cond, which looks `COND1 COND2'.
5525     foreach my $comp (split (' ', $cond))
5526     {
5527         # TRUE is always true.
5528         next if $comp eq 'TRUE';
5529         return 0 if ! defined $cond_vals{$comp};
5530     }
5531
5532     return 1;
5533 }
5534
5535
5536 # $BOOLEAN
5537 # &conditional_is_redundant ($COND, @WHENS)
5538 # ----------------------------------------
5539 # Determine whether $COND is redundant with respect to @WHENS.
5540 #
5541 # Returns true if $COND is true for any of the conditions in @WHENS.
5542 #
5543 # If there are no @WHENS, then behave as if @WHENS contained a single empty
5544 # condition.
5545 sub conditional_is_redundant ($@)
5546 {
5547     my ($cond, @whens) = @_;
5548
5549     if (@whens == 0)
5550     {
5551         return 1 if conditional_true_when ($cond, "");
5552     }
5553     else
5554     {
5555         foreach my $when (@whens)
5556         {
5557             return 1 if conditional_true_when ($cond, $when);
5558         }
5559     }
5560
5561     return 0;
5562 }
5563
5564
5565 # $NEGATION
5566 # condition_negate ($COND)
5567 # ------------------------
5568 sub condition_negate ($)
5569 {
5570     my ($cond) = @_;
5571
5572     $cond =~ s/TRUE$/TRUEO/;
5573     $cond =~ s/FALSE$/TRUE/;
5574     $cond =~ s/TRUEO$/FALSE/;
5575
5576     return $cond;
5577 }
5578
5579
5580 # Compare condition names.
5581 # Issue them in alphabetical order, foo_TRUE before foo_FALSE.
5582 sub by_condition
5583 {
5584     # Be careful we might be comparing `' or `#'.
5585     $a =~ /^(.*)_(TRUE|FALSE)$/;
5586     my ($aname, $abool) = ($1 || '', $2 || '');
5587     $b =~ /^(.*)_(TRUE|FALSE)$/;
5588     my ($bname, $bbool) = ($1 || '', $2 || '');
5589     return ($aname cmp $bname
5590             # Don't bother with IFs, given that TRUE is after FALSE
5591             # just cmp in the reverse order.
5592             || $bbool cmp $abool
5593             # Just in case...
5594             || $a cmp $b);
5595 }
5596
5597
5598 # &make_condition (@CONDITIONS)
5599 # -----------------------------
5600 # Transform a list of conditions (themselves can be an internal list
5601 # of conditions, e.g., @CONDITIONS = ('cond1 cond2', 'cond3')) into a
5602 # Make conditional (a pattern for AC_SUBST).
5603 # Correctly returns the empty string when there are no conditions.
5604 sub make_condition
5605 {
5606     my $res = conditional_string (@_);
5607
5608     # There are no conditions.
5609     if ($res eq '')
5610       {
5611         # Nothing to do.
5612       }
5613     # It's impossible.
5614     elsif ($res eq 'FALSE')
5615       {
5616         $res = '#';
5617       }
5618     # Build it.
5619     else
5620       {
5621         $res = '@' . $res . '@';
5622         $res =~ s/ /@@/g;
5623       }
5624
5625     return $res;
5626 }
5627
5628
5629
5630 ## ------------------------------ ##
5631 ## Handling the condition stack.  ##
5632 ## ------------------------------ ##
5633
5634
5635 # $COND_STRING
5636 # cond_stack_if ($NEGATE, $COND, $WHERE)
5637 # --------------------------------------
5638 sub cond_stack_if ($$$)
5639 {
5640   my ($negate, $cond, $where) = @_;
5641
5642   am_file_error ($where, "$cond does not appear in AM_CONDITIONAL")
5643     if ! $configure_cond{$cond} && $cond !~ /^TRUE|FALSE$/;
5644
5645   $cond = "${cond}_TRUE"
5646     unless $cond =~ /^TRUE|FALSE$/;
5647   $cond = condition_negate ($cond)
5648     if $negate;
5649
5650   push (@cond_stack, $cond);
5651
5652   return conditional_string (@cond_stack);
5653 }
5654
5655
5656 # $COND_STRING
5657 # cond_stack_else ($NEGATE, $COND, $WHERE)
5658 # ----------------------------------------
5659 sub cond_stack_else ($$$)
5660 {
5661   my ($negate, $cond, $where) = @_;
5662
5663   if (! @cond_stack)
5664     {
5665       am_file_error ($where, "else without if");
5666       return;
5667     }
5668
5669   $cond_stack[$#cond_stack] = condition_negate ($cond_stack[$#cond_stack]);
5670
5671   # If $COND is given, check against it.
5672   if (defined $cond)
5673     {
5674       $cond = "${cond}_TRUE"
5675         unless $cond =~ /^TRUE|FALSE$/;
5676       $cond = condition_negate ($cond)
5677         if $negate;
5678
5679       am_file_error ($where,
5680                      "else reminder ($negate$cond) incompatible with "
5681                      . "current conditional: $cond_stack[$#cond_stack]")
5682         if $cond_stack[$#cond_stack] ne $cond;
5683     }
5684
5685   return conditional_string (@cond_stack);
5686 }
5687
5688
5689 # $COND_STRING
5690 # cond_stack_endif ($NEGATE, $COND, $WHERE)
5691 # -----------------------------------------
5692 sub cond_stack_endif ($$$)
5693 {
5694   my ($negate, $cond, $where) = @_;
5695   my $old_cond;
5696
5697   if (! @cond_stack)
5698     {
5699       am_file_error ($where, "endif without if: $negate$cond");
5700       return;
5701     }
5702
5703
5704   # If $COND is given, check against it.
5705   if (defined $cond)
5706     {
5707       $cond = "${cond}_TRUE"
5708         unless $cond =~ /^TRUE|FALSE$/;
5709       $cond = condition_negate ($cond)
5710         if $negate;
5711
5712       am_file_error ($where,
5713                      "endif reminder ($negate$cond) incompatible with "
5714                      . "current conditional: $cond_stack[$#cond_stack]")
5715         if $cond_stack[$#cond_stack] ne $cond;
5716     }
5717
5718   pop @cond_stack;
5719
5720   return conditional_string (@cond_stack);
5721 }
5722
5723
5724
5725
5726
5727 ## ------------------------ ##
5728 ## Handling the variables.  ##
5729 ## ------------------------ ##
5730
5731
5732 # check_ambiguous_conditional ($VAR, $COND)
5733 # -----------------------------------------
5734 # Check for an ambiguous conditional.  This is called when a variable
5735 # is being defined conditionally.  If we already know about a
5736 # definition that is true under the same conditions, then we have an
5737 # ambiguity.
5738 sub check_ambiguous_conditional ($$)
5739 {
5740     my ($var, $cond) = @_;
5741     foreach my $vcond (keys %{$var_value{$var}})
5742     {
5743        my $message;
5744        if ($vcond eq $cond)
5745        {
5746            $message = "$var multiply defined in condition $cond";
5747        }
5748        elsif (&conditional_true_when ($vcond, $cond))
5749        {
5750          $message = ("$var was already defined in condition $vcond, "
5751                      . "which implies condition $cond");
5752        }
5753        elsif (&conditional_true_when ($cond, $vcond))
5754        {
5755            $message = ("$var was already defined in condition $vcond, "
5756                        . "which is implied by condition $cond");
5757        }
5758        if ($message)
5759        {
5760            am_macro_error ($var, $message);
5761            macro_dump ($var);
5762        }
5763    }
5764 }
5765
5766
5767 # &macro_define($VAR, $VAR_IS_AM, $TYPE, $COND, $VALUE, $WHERE)
5768 # -------------------------------------------------------------
5769 # The $VAR can go from Automake to user, but not the converse.
5770 sub macro_define ($$$$$$)
5771 {
5772   my ($var, $var_is_am, $type, $cond, $value, $where) = @_;
5773
5774   am_file_error ($where, "bad macro name `$var'")
5775     if $var !~ /$MACRO_PATTERN/o;
5776
5777   $cond ||= 'TRUE';
5778
5779   # An Automake variable must be consistently defined with the same
5780   # sign by Automake.  A user variable must be set by either `=' or
5781   # `:=', and later promoted to `+='.
5782   if ($var_is_am)
5783     {
5784       if (defined $var_type{$var} && $var_type{$var} ne $type)
5785         {
5786           am_macro_error ($var,
5787                          ("$var was set with `$var_type{$var}=' "
5788                           . "and is now set with `$type='"));
5789         }
5790     }
5791   else
5792     {
5793       if (!defined $var_type{$var} && $type eq '+')
5794         {
5795           am_macro_error ($var, "$var must be set with `=' before using `+='");
5796         }
5797     }
5798   $var_type{$var} = $type;
5799
5800   # When adding, since we rewrite, don't try to preserve the
5801   # Automake continuation backslashes.
5802   $value =~ s/\\$//mg
5803     if $type eq '+' && $var_is_am;
5804
5805   # Differentiate the first assignment (including with `+=').
5806   if ($type eq '+' && defined $var_value{$var}{$cond})
5807     {
5808       if (substr ($var_value{$var}{$cond}, -1) eq "\n")
5809         {
5810           # Insert a backslash before a trailing newline.
5811           $var_value{$var}{$cond} =
5812             substr ($var_value{$var}{$cond}, 0, -1) . "\\\n";
5813         }
5814       elsif ($var_value{$var}{$cond})
5815         {
5816           # Insert a separator.
5817           $var_value{$var}{$cond} .= ' ';
5818         }
5819        $var_value{$var}{$cond} .= $value;
5820     }
5821   else
5822     {
5823       # The first assignment to a macro sets its location.  Ideally I
5824       # suppose we would associate line numbers with random bits of text.
5825       # FIXME: We sometimes redefine some variables, but we want to keep
5826       # the original location.  More subs are needed to handle
5827       # properly variables.  Once this done, remove this hack.
5828       $var_location{$var} = $where
5829         unless defined $var_location{$var};
5830
5831       # If Automake tries to override a value specified by the user,
5832       # just don't let it do.
5833       if (defined $var_value{$var}{$cond} && !$var_is_am{$var} && $var_is_am)
5834         {
5835           if ($verbose)
5836             {
5837               print STDERR "$me: refusing to override the user definition of:\n";
5838               macro_dump ($var);
5839               print STDERR "$me: with `$cond' => `$value'\n";
5840             }
5841         }
5842       else
5843         {
5844           # There must be no previous value unless the user is redefining
5845           # an Automake variable or an AC_SUBST variable.
5846           check_ambiguous_conditional ($var, $cond)
5847             unless ($var_is_am{$var} && !$var_is_am
5848                     || exists $configure_vars{$var});
5849
5850           $var_value{$var}{$cond} = $value;
5851         }
5852     }
5853
5854   # An Automake variable can be given to the user, but not the converse.
5855   if (! defined $var_is_am{$var} || !$var_is_am)
5856     {
5857       $var_is_am{$var} = $var_is_am;
5858     }
5859 }
5860
5861
5862 # &variable_delete ($VAR, [@CONDS])
5863 # ---------------------------------
5864 # Forget about $VAR under the conditions @CONDS, or completely if
5865 # @CONDS is empty.
5866 sub variable_delete ($@)
5867 {
5868   my ($var, @conds) = @_;
5869
5870   if (!@conds)
5871     {
5872       delete $var_value{$var};
5873       delete $var_location{$var};
5874       delete $var_is_am{$var};
5875       delete $var_comment{$var};
5876       delete $var_type{$var};
5877     }
5878   else
5879     {
5880       foreach my $cond (@conds)
5881         {
5882           delete $var_value{$var}{$cond};
5883         }
5884     }
5885 }
5886
5887
5888 # &macro_dump ($VAR)
5889 # ------------------
5890 sub macro_dump ($)
5891 {
5892   my ($var) = @_;
5893
5894   if (!exists $var_value{$var})
5895     {
5896       print STDERR "  $var does not exist\n";
5897     }
5898   else
5899     {
5900       my $var_is_am = $var_is_am{$var} ? "Automake" : "User";
5901       my $where = (defined $var_location{$var}
5902                    ? $var_location{$var} : "undefined");
5903       print STDERR "$var_comment{$var}"
5904         if defined $var_comment{$var};
5905       print STDERR "  $var ($var_is_am, where = $where) $var_type{$var}=\n";
5906       print STDERR "  {\n";
5907       foreach my $vcond (sort by_condition keys %{$var_value{$var}})
5908         {
5909           print STDERR "    $vcond => $var_value{$var}{$vcond}\n";
5910         }
5911       print STDERR "  }\n";
5912     }
5913 }
5914
5915
5916 # &macros_dump ()
5917 # ---------------
5918 sub macros_dump ()
5919 {
5920   my ($var) = @_;
5921
5922   print STDERR "%var_value =\n";
5923   print STDERR "{\n";
5924   foreach my $var (sort (keys %var_value))
5925     {
5926       macro_dump ($var);
5927     }
5928   print STDERR "}\n";
5929 }
5930
5931
5932 # $BOOLEAN
5933 # &variable_defined ($VAR, [$COND])
5934 # ---------------------------------
5935 # See if a variable exists.  $VAR is the variable name, and $COND is
5936 # the condition which we should check.  If no condition is given, we
5937 # currently return true if the variable is defined under any
5938 # condition.
5939 sub variable_defined ($$)
5940 {
5941     my ($var, $cond) = @_;
5942
5943     # Unfortunately we can't just check for $var_value{VAR}{COND}
5944     # as this would make perl create $condition{VAR}, which we
5945     # don't want.
5946     if (!exists $var_value{$var})
5947       {
5948         if (defined $targets{$var})
5949           {
5950             am_macro_error ($var, "`$var' is a target; expected a variable")
5951           }
5952         # The variable is not defined
5953         return 0;
5954       }
5955
5956     if ($cond && !exists $var_value{$var}{$cond})
5957       {
5958         # The variable is not defined for the given condition.
5959         return 0;
5960       }
5961
5962     # Even a var_value examination is good enough for us.  FIXME:
5963     # really should maintain examined status on a per-condition basis.
5964     $content_seen{$var} = 1;
5965     return 1;
5966 }
5967
5968 # Mark a variable as examined.
5969 sub examine_variable
5970 {
5971     my ($var) = @_;
5972     &variable_defined ($var);
5973 }
5974
5975 # Return the set of conditions for which a variable is defined.
5976
5977 # If the variable is not defined conditionally, and is not defined in
5978 # terms of any variables which are defined conditionally, then this
5979 # returns the empty list.
5980
5981 # If the variable is defined conditionally, but is not defined in
5982 # terms of any variables which are defined conditionally, then this
5983 # returns the list of conditions for which the variable is defined.
5984
5985 # If the variable is defined in terms of any variables which are
5986 # defined conditionally, then this returns a full set of permutations
5987 # of the subvariable conditions.  For example, if the variable is
5988 # defined in terms of a variable which is defined for COND_TRUE,
5989 # then this returns both COND_TRUE and COND_FALSE.  This is
5990 # because we will need to define the variable under both conditions.
5991
5992 sub variable_conditions_recursive ($)
5993 {
5994     my ($var) = @_;
5995
5996     %vars_scanned = ();
5997
5998     my @new_conds = variable_conditions_recursive_sub ($var, '');
5999     # Now we want to return all permutations of the subvariable
6000     # conditions.
6001     my %allconds = ();
6002     foreach my $item (@new_conds)
6003     {
6004         foreach (split (' ', $item))
6005         {
6006             s/^(.*)_(TRUE|FALSE)$/$1_TRUE/;
6007             $allconds{$_} = 1;
6008         }
6009     }
6010     @new_conds = variable_conditions_permutations (sort keys %allconds);
6011
6012     my %uniqify;
6013     foreach my $cond (@new_conds)
6014     {
6015         my $reduce = variable_conditions_reduce (split (' ', $cond));
6016         next
6017             if $reduce eq 'FALSE';
6018         $uniqify{$cond} = 1;
6019     }
6020
6021     # Note we cannot just do `return sort keys %uniqify', because this
6022     # function is sometimes used in a scalar context.
6023     my @uniq_list = sort by_condition keys %uniqify;
6024     return @uniq_list;
6025 }
6026
6027 # @CONDS
6028 # variable_conditions ($VAR)
6029 # --------------------------
6030 # Get the list of conditions that a variable is defined with, without
6031 # recursing through the conditions of any subvariables.
6032 # Argument is $VAR: the variable to get the conditions of.
6033 # Returns the list of conditions.
6034 sub variable_conditions ($)
6035 {
6036     my ($var) = @_;
6037     my @conds = keys %{$var_value{$var}};
6038     return sort by_condition @conds;
6039 }
6040
6041
6042 # $BOOLEAN
6043 # &variable_conditionally_defined ($VAR)
6044 # --------------------------------------
6045 sub variable_conditionally_defined ($)
6046 {
6047     my ($var) = @_;
6048     foreach my $cond (variable_conditions_recursive ($var))
6049       {
6050         return 1
6051           unless $cond =~ /^TRUE|FALSE$/;
6052       }
6053     return 0;
6054 }
6055
6056
6057
6058 # &variable_conditions_recursive_sub ($VAR, $PARENT)
6059 # -------------------------------------------------------
6060 # A subroutine of variable_conditions_recursive.  This returns all the
6061 # conditions of $VAR, including those of any sub-variables.
6062 sub variable_conditions_recursive_sub
6063 {
6064     my ($var, $parent) = @_;
6065     my @new_conds = ();
6066
6067     if (defined $vars_scanned{$var})
6068     {
6069         am_macro_error ($parent, "variable `$var' recursively defined");
6070         return ();
6071     }
6072     $vars_scanned{$var} = 1;
6073
6074     my @this_conds = ();
6075     # Examine every condition under which $VAR is defined.
6076     foreach my $vcond (keys %{$var_value{$var}})
6077     {
6078         push (@this_conds, $vcond);
6079
6080         # If $VAR references some other variable, then compute the
6081         # conditions for that subvariable.
6082         my @subvar_conds = ();
6083         foreach (split (' ', $var_value{$var}{$vcond}))
6084         {
6085             # If a comment seen, just leave.
6086             last if /^#/;
6087
6088             # Handle variable substitutions.
6089             if (/^\$\{(.*)\}$/ || /^\$\((.*)\)$/)
6090             {
6091                 my $varname = $1;
6092                 if ($varname =~ /$SUBST_REF_PATTERN/o)
6093                 {
6094                     $varname = $1;
6095                 }
6096
6097
6098                 # Here we compute all the conditions under which the
6099                 # subvariable is defined.  Then we go through and add
6100                 # $VCOND to each.
6101                 my @svc = variable_conditions_recursive_sub ($varname, $var);
6102                 foreach my $item (@svc)
6103                 {
6104                     my $val = conditional_string ($vcond, split (' ', $item));
6105                     $val ||= 'TRUE';
6106                     push (@subvar_conds, $val);
6107                 }
6108             }
6109         }
6110
6111         # If there are no conditional subvariables, then we want to
6112         # return this condition.  Otherwise, we want to return the
6113         # permutations of the subvariables, taking into account the
6114         # conditions of $VAR.
6115         if (! @subvar_conds)
6116         {
6117             push (@new_conds, $vcond);
6118         }
6119         else
6120         {
6121             push (@new_conds, variable_conditions_reduce (@subvar_conds));
6122         }
6123     }
6124
6125     # Unset our entry in vars_scanned.  We only care about recursive
6126     # definitions.
6127     delete $vars_scanned{$var};
6128
6129     # If we are being called on behalf of another variable, we need to
6130     # return all possible permutations of the conditions.  We have
6131     # already handled everything in @this_conds along with their
6132     # subvariables.  We now need to add any permutations that are not
6133     # in @this_conds.
6134     foreach my $this_cond (@this_conds)
6135     {
6136         my @perms =
6137             variable_conditions_permutations (split (' ', $this_cond));
6138         foreach my $perm (@perms)
6139         {
6140             my $ok = 1;
6141             foreach my $scan (@this_conds)
6142             {
6143                 if (&conditional_true_when ($perm, $scan)
6144                     || &conditional_true_when ($scan, $perm))
6145                 {
6146                     $ok = 0;
6147                     last;
6148                 }
6149             }
6150             next if ! $ok;
6151
6152             # This permutation was not already handled, and is valid
6153             # for the parents.
6154             push (@new_conds, $perm);
6155         }
6156     }
6157
6158     return @new_conds;
6159 }
6160
6161
6162 # Filter a list of conditionals so that only the exclusive ones are
6163 # retained.  For example, if both `COND1_TRUE COND2_TRUE' and
6164 # `COND1_TRUE' are in the list, discard the latter.
6165 # If the list is empty, return TRUE
6166 sub variable_conditions_reduce
6167 {
6168     my (@conds) = @_;
6169     my @ret = ();
6170     my $cond;
6171     while(@conds > 0)
6172     {
6173         $cond = shift(@conds);
6174
6175         # FALSE is absorbent.
6176         if ($cond eq 'FALSE')
6177           {
6178             return ('FALSE');
6179           }
6180         elsif (!conditional_is_redundant ($cond, @ret, @conds))
6181           {
6182             push (@ret, $cond);
6183           }
6184     }
6185
6186     return "TRUE" if @ret == 0;
6187     return @ret;
6188 }
6189
6190 # @CONDS
6191 # invert_conditions (@CONDS)
6192 # --------------------------
6193 # Invert a list of conditionals.  Returns a set of conditionals which
6194 # are never true for any of the input conditionals, and when taken
6195 # together with the input conditionals cover all possible cases.
6196 #
6197 # For example: invert_conditions("A_TRUE B_TRUE", "A_FALSE B_FALSE") will
6198 # return ("A_FALSE B_TRUE", "A_TRUE B_FALSE")
6199 sub invert_conditions
6200 {
6201     my (@conds) = @_;
6202
6203     my @notconds = ();
6204     foreach my $cond (@conds)
6205     {
6206         foreach my $perm (variable_conditions_permutations (split(' ', $cond)))
6207         {
6208             push @notconds, $perm
6209                     if ! conditional_is_redundant ($perm, @conds);
6210         }
6211     }
6212     return variable_conditions_reduce (@notconds);
6213 }
6214
6215 # Return a list of permutations of a conditional string.
6216 sub variable_conditions_permutations
6217 {
6218     my (@comps) = @_;
6219     return ()
6220         if ! @comps;
6221     my $comp = shift (@comps);
6222     return variable_conditions_permutations (@comps)
6223         if $comp eq '';
6224     my $neg = condition_negate ($comp);
6225
6226     my @ret;
6227     foreach my $sub (variable_conditions_permutations (@comps))
6228     {
6229         push (@ret, "$comp $sub");
6230         push (@ret, "$neg $sub");
6231     }
6232     if (! @ret)
6233     {
6234         push (@ret, $comp);
6235         push (@ret, $neg);
6236     }
6237     return @ret;
6238 }
6239
6240
6241 # $BOOL
6242 # &check_variable_defined_unconditionally($VAR, $PARENT)
6243 # ------------------------------------------------------
6244 # Warn if a variable is conditionally defined.  This is called if we
6245 # are using the value of a variable.
6246 sub check_variable_defined_unconditionally ($$)
6247 {
6248     my ($var, $parent) = @_;
6249     foreach my $cond (keys %{$var_value{$var}})
6250     {
6251         next
6252           if $cond =~ /^TRUE|FALSE$/;
6253
6254         if ($parent)
6255         {
6256             am_macro_error ($parent,
6257                             "warning: automake does not support conditional definition of $var in $parent");
6258         }
6259         else
6260         {
6261             am_macro_error ($parent,
6262                             "warning: automake does not support $var being defined conditionally");
6263         }
6264     }
6265 }
6266
6267
6268 # Get the TRUE value of a variable, warn if the variable is
6269 # conditionally defined.
6270 sub variable_value
6271 {
6272     my ($var) = @_;
6273     &check_variable_defined_unconditionally ($var);
6274     return $var_value{$var}{'TRUE'};
6275 }
6276
6277
6278 # @VALUES
6279 # &value_to_list ($VAR, $VAL, $COND)
6280 # ----------------------------------
6281 # Convert a variable value to a list, split as whitespace.  This will
6282 # recursively follow $(...) and ${...} inclusions.  It preserves @...@
6283 # substitutions.
6284 #
6285 # If COND is 'all', then all values under all conditions should be
6286 # returned; if COND is a particular condition (all conditions are
6287 # surrounded by @...@) then only the value for that condition should
6288 # be returned; otherwise, warn if VAR is conditionally defined.
6289 # SCANNED is a global hash listing whose keys are all the variables
6290 # already scanned; it is an error to rescan a variable.
6291 sub value_to_list
6292 {
6293     my ($var, $val, $cond) = @_;
6294     my @result;
6295
6296     # Strip backslashes
6297     $val =~ s/\\(\n|$)/ /g;
6298
6299     foreach (split (' ', $val))
6300     {
6301         # If a comment seen, just leave.
6302         last if /^#/;
6303
6304         # Handle variable substitutions.
6305         if (/^\$\{([^}]*)\}$/ || /^\$\(([^)]*)\)$/)
6306         {
6307             my $varname = $1;
6308
6309             # If the user uses a losing variable name, just ignore it.
6310             # This isn't ideal, but people have requested it.
6311             next if ($varname =~ /\@.*\@/);
6312
6313             my ($from, $to);
6314             my @temp_list;
6315             if ($varname =~ /$SUBST_REF_PATTERN/o)
6316             {
6317                 $varname = $1;
6318                 $to = $3;
6319                 ($from = $2) =~ s/(\W)/\\$1/g;
6320             }
6321
6322             # Find the value.
6323             @temp_list = &variable_value_as_list_recursive_worker ($1, $cond, $var);
6324
6325             # Now rewrite the value if appropriate.
6326             if (defined $from)
6327             {
6328                 grep (s/$from$/$to/, @temp_list);
6329             }
6330
6331             push (@result, @temp_list);
6332         }
6333         else
6334         {
6335             push (@result, $_);
6336         }
6337     }
6338
6339     return @result;
6340 }
6341
6342 # @VALUES
6343 # variable_value_as_list ($VAR, $COND, $PARENT)
6344 # ---------------------------------------------
6345 # Get the value of a variable given a specified condition. without
6346 # recursing through any subvariables.
6347 # Arguments are:
6348 #   $VAR    is the variable
6349 #   $COND   is the condition.  If this is not given, the value for the
6350 #           "TRUE" condition will be returned.
6351 #   $PARENT is the variable in which the variable is used: this is used
6352 #           only for error messages.
6353 # Returns the list of conditions.
6354 # For example, if A is defined as "foo $(B) bar", and B is defined as
6355 # "baz", this will return ("foo", "$(B)", "bar")
6356 sub variable_value_as_list
6357 {
6358     my ($var, $cond, $parent) = @_;
6359     my @result;
6360
6361     # Check defined
6362     if (! defined $var_value{$var})
6363     {
6364         if (defined $targets{$var})
6365           {
6366             am_macro_error ($var, "`$var' is a target; expected a variable");
6367           }
6368         else
6369           {
6370             am_macro_error ($parent, "variable `$var' not defined");
6371           }
6372     }
6373
6374     # Get value for given condition
6375     $cond ||= 'TRUE';
6376     my $onceflag;
6377     foreach my $vcond (keys %{$var_value{$var}})
6378     {
6379         my $val = $var_value{$var}{$vcond};
6380
6381         if (&conditional_true_when ($vcond, $cond))
6382         {
6383             # Unless variable is not defined conditionally, there should only
6384             # be one value of $vcond true when $cond.
6385             &check_variable_defined_unconditionally ($var, $parent)
6386                     if $onceflag;
6387             $onceflag = 1;
6388
6389             # Strip backslashes
6390             $val =~ s/\\(\n|$)/ /g;
6391
6392             foreach (split (' ', $val))
6393             {
6394                 # If a comment seen, just leave.
6395                 last if /^#/;
6396
6397                 push (@result, $_);
6398             }
6399         }
6400     }
6401
6402     return @result;
6403 }
6404
6405 # Return contents of variable as list, split as whitespace.  This will
6406 # recursively follow $(...) and ${...} inclusions.  It preserves @...@
6407 # substitutions.  If COND is 'all', then all values under all
6408 # conditions should be returned; if COND is a particular condition
6409 # (all conditions are surrounded by @...@) then only the value for
6410 # that condition should be returned; otherwise, warn if VAR is
6411 # conditionally defined.  If PARENT is specified, it is the name of
6412 # the including variable; this is only used for error reports.
6413 sub variable_value_as_list_recursive_worker
6414 {
6415     my ($var, $cond, $parent) = @_;
6416     my @result = ();
6417
6418     if (! defined $var_value{$var})
6419     {
6420         if (defined $targets{$var})
6421           {
6422             am_macro_error ($var, "`$var' is a target; expected a variable");
6423           }
6424         else
6425           {
6426             am_macro_error ($parent, "variable `$var' not defined");
6427           }
6428     }
6429     elsif (defined $vars_scanned{$var})
6430     {
6431         # `vars_scanned' is a global we use to keep track of which
6432         # variables we've already examined.
6433         am_macro_error ($parent, "variable `$var' recursively defined");
6434     }
6435     elsif ($cond eq 'all')
6436     {
6437         $vars_scanned{$var} = 1;
6438         foreach my $vcond (keys %{$var_value{$var}})
6439         {
6440             my $val = $var_value{$var}{$vcond};
6441             push (@result, &value_to_list ($var, $val, $cond));
6442         }
6443     }
6444     else
6445     {
6446         $cond ||= 'TRUE';
6447         $vars_scanned{$var} = 1;
6448         my $onceflag;
6449         foreach my $vcond (keys %{$var_value{$var}})
6450         {
6451             my $val = $var_value{$var}{$vcond};
6452             if (&conditional_true_when ($vcond, $cond))
6453             {
6454                 # Warn if we have an ambiguity.  It's hard to know how
6455                 # to handle this case correctly.
6456                 &check_variable_defined_unconditionally ($var, $parent)
6457                     if $onceflag;
6458                 $onceflag = 1;
6459                 push (@result, &value_to_list ($var, $val, $cond));
6460             }
6461         }
6462     }
6463
6464     # Unset our entry in vars_scanned.  We only care about recursive
6465     # definitions.
6466     delete $vars_scanned{$var};
6467
6468     return @result;
6469 }
6470
6471
6472 # &variable_output ($VAR, [@CONDS])
6473 # ---------------------------------
6474 # Output all the values of $VAR is @COND is not specified, else only
6475 # that corresponding to @COND.
6476 sub variable_output ($@)
6477 {
6478   my ($var, @conds) = @_;
6479
6480   @conds = keys %{$var_value{$var}}
6481     unless @conds;
6482
6483   $output_vars .= $var_comment{$var}
6484     if defined $var_comment{$var};
6485
6486   foreach my $cond (sort by_condition @conds)
6487     {
6488       my $val = $var_value{$var}{$cond};
6489       my $equals = $var_type{$var} eq ':' ? ':=' : '=';
6490       my $output_var = "$var $equals $val";
6491       $output_var =~ s/^/make_condition ($cond)/meg;
6492       $output_vars .= $output_var . "\n";
6493     }
6494 }
6495
6496
6497 # &variable_pretty_output ($VAR, [@CONDS])
6498 # ----------------------------------------
6499 # Likewise, but pretty, i.e., we *split* the values at spaces.   Use only
6500 # with variables holding filenames.
6501 sub variable_pretty_output ($@)
6502 {
6503   my ($var, @conds) = @_;
6504
6505   @conds = keys %{$var_value{$var}}
6506     unless @conds;
6507
6508   $output_vars .= $var_comment{$var}
6509     if defined $var_comment{$var};
6510
6511   foreach my $cond (sort by_condition @conds)
6512     {
6513       my $val = $var_value{$var}{$cond};
6514       my $equals = $var_type{$var} eq ':' ? ':=' : '=';
6515       my $make_condition = make_condition ($cond);
6516       $output_vars .= pretty_print_internal ("$make_condition$var $equals",
6517                                              "$make_condition\t",
6518                                              split (' ' , $val));
6519     }
6520 }
6521
6522
6523 # This is just a wrapper for variable_value_as_list_recursive_worker that
6524 # initializes the global hash `vars_scanned'.  This hash is used to
6525 # avoid infinite recursion.
6526 sub variable_value_as_list_recursive
6527 {
6528     my ($var, $cond, $parent) = @_;
6529     %vars_scanned = ();
6530     return &variable_value_as_list_recursive_worker ($var, $cond, $parent);
6531 }
6532
6533
6534 # Like define_variable, but the value is a list, and the variable may
6535 # be defined conditionally.  The second argument is the conditional
6536 # under which the value should be defined; this should be the empty
6537 # string to define the variable unconditionally.  The third argument
6538 # is a list holding the values to use for the variable.  The value is
6539 # pretty printed in the output file.
6540 sub define_pretty_variable
6541 {
6542     my ($var, $cond, @value) = @_;
6543
6544     # Beware that an empty $cond has a different semantics for
6545     # macro_define and variable_pretty_output.
6546     $cond ||= 'TRUE';
6547
6548     if (! &variable_defined ($var, $cond))
6549     {
6550         macro_define ($var, 1, '', $cond, join (' ', @value), undef);
6551         variable_pretty_output ($var, $cond || 'TRUE');
6552         $content_seen{$var} = 1;
6553     }
6554 }
6555
6556
6557 # define_variable ($VAR, $VALUE)
6558 # ------------------------------
6559 # Define a new user variable VAR to VALUE, but only if not already defined.
6560 sub define_variable
6561 {
6562     my ($var, $value) = @_;
6563
6564     define_pretty_variable ($var, 'TRUE', $value);
6565 }
6566
6567
6568 # Like define_variable, but define a variable to be the configure
6569 # substitution by the same name.
6570 sub define_configure_variable
6571 {
6572     my ($var) = @_;
6573     my $value = '@' . $var . '@';
6574     &define_variable ($var, $value);
6575 }
6576
6577
6578 # define_compiler_variable ($LANG)
6579 # --------------------------------
6580 # Define a compiler variable.  We also handle defining the `LT'
6581 # version of the command when using libtool.
6582 sub define_compiler_variable ($)
6583 {
6584     my ($lang) = @_;
6585
6586     my ($var, $value) = ($lang->compiler, $lang->compile);
6587     &define_variable ($var, $value);
6588     &define_variable ("LT$var", "\$(LIBTOOL) --mode=compile $value")
6589       if $seen_libtool;
6590 }
6591
6592
6593 # define_linker_variable ($LANG)
6594 # ------------------------------
6595 # Define linker variables.
6596 sub define_linker_variable ($)
6597 {
6598     my ($lang) = @_;
6599
6600     my ($var, $value) = ($lang->lder, $lang->ld);
6601     # CCLD = $(CC).
6602     &define_variable ($lang->lder, $lang->ld);
6603     # CCLINK = $(CCLD) blah blah...
6604     &define_variable ($lang->linker,
6605                       (($seen_libtool ? '$(LIBTOOL) --mode=link ' : '')
6606                        . $lang->link));
6607 }
6608
6609 ################################################################
6610
6611 ## ---------------- ##
6612 ## Handling rules.  ##
6613 ## ---------------- ##
6614
6615 # $BOOL
6616 # rule_define ($TARGET, $IS_AM, $COND, $WHERE)
6617 # --------------------------------------------
6618 # Define a new rule.  $TARGET is the rule name.  $IS_AM is a boolean
6619 # which is true if the new rule is defined by the user.  $COND is the
6620 # condition under which the rule is defined.  $WHERE is where the rule
6621 # is defined (file name or line number).  Returns true if it is ok to
6622 # define the rule, false otherwise.
6623 sub rule_define ($$$$)
6624 {
6625   my ($target, $rule_is_am, $cond, $where) = @_;
6626
6627   # For now `foo:' will override `foo$(EXEEXT):'.  This is temporary,
6628   # though, so we emit a warning.
6629   (my $noexe = $target) =~ s,\$\(EXEEXT\)$,,;
6630   if ($noexe ne $target && defined $targets{$noexe})
6631   {
6632       # The no-exeext option enables this feature.
6633       if (! defined $options{'no-exeext'})
6634       {
6635           am_macro_error ($noexe,
6636                           "deprecated feature: `$noexe' overrides `$noexe\$(EXEEXT)'\nchange your target to read `$noexe\$(EXEEXT)'");
6637       }
6638       # Don't define.
6639       return 0;
6640   }
6641
6642   if (defined $targets{$target}
6643       && ($cond
6644           ? ! defined $target_conditional{$target}
6645           : defined $target_conditional{$target}))
6646   {
6647       am_target_error ($target,
6648                       "$target defined both conditionally and unconditionally");
6649   }
6650
6651   # Value here doesn't matter; for targets we only note existence.
6652   $targets{$target} = $where;
6653   if ($cond)
6654   {
6655       if ($target_conditional{$target})
6656       {
6657           &check_ambiguous_conditional ($target, $cond);
6658       }
6659       $target_conditional{$target}{$cond} = $where;
6660   }
6661
6662
6663   # Check the rule for being a suffix rule. If so, store in a hash.
6664
6665   if ((my ($source_suffix, $object_suffix)) = ($target =~ $SUFFIX_RULE_PATTERN))
6666   {
6667       $suffix_rules{$source_suffix} = $object_suffix;
6668       print "Sources ending in .$source_suffix become .$object_suffix\n"
6669           if $verbose;
6670       # Set SUFFIXES from suffix_rules.
6671       push @suffixes, ".$source_suffix", ".$object_suffix";
6672   }
6673
6674   return 1;
6675 }
6676
6677
6678 # See if a target exists.
6679 sub target_defined
6680 {
6681     my ($target) = @_;
6682     return defined $targets{$target};
6683 }
6684
6685
6686 ################################################################
6687
6688 # &read_am_file ($AMFILE)
6689 # -----------------------
6690 # Read Makefile.am and set up %contents.  Simultaneously copy lines
6691 # from Makefile.am into $output_trailer or $output_vars as
6692 # appropriate.  NOTE we put rules in the trailer section.  We want
6693 # user rules to come after our generated stuff.
6694 sub read_am_file ($)
6695 {
6696     my ($amfile) = @_;
6697
6698     my $am_file = new Automake::XFile ("< $amfile");
6699     verbose "reading $amfile";
6700
6701     my $spacing = '';
6702     my $comment = '';
6703     my $blank = 0;
6704
6705     while ($_ = $am_file->getline)
6706     {
6707         if (/$IGNORE_PATTERN/o)
6708         {
6709             # Merely delete comments beginning with two hashes.
6710         }
6711         elsif (/$WHITE_PATTERN/o)
6712         {
6713             # Stick a single white line before the incoming macro or rule.
6714             $spacing = "\n";
6715             $blank = 1;
6716         }
6717         elsif (/$COMMENT_PATTERN/o)
6718         {
6719             # Stick comments before the incoming macro or rule.  Make
6720             # sure a blank line preceeds first block of comments.
6721             $spacing = "\n" unless $blank;
6722             $blank = 1;
6723             $comment .= $spacing . $_;
6724             $spacing = '';
6725         }
6726         else
6727         {
6728             last;
6729         }
6730     }
6731
6732     $output_vars .= $comment . "\n";
6733     $comment = '';
6734     $spacing = "\n";
6735
6736     # We save the conditional stack on entry, and then check to make
6737     # sure it is the same on exit.  This lets us conditonally include
6738     # other files.
6739     my @saved_cond_stack = @cond_stack;
6740     my $cond = conditional_string (@cond_stack);
6741
6742     my $saw_bk = 0;
6743     my $was_rule = 0;
6744     my $last_var_name = '';
6745     my $last_var_type = '';
6746     my $last_var_value = '';
6747     # FIXME: shouldn't use $_ in this loop; it is too big.
6748     while ($_)
6749     {
6750         my $here = "$amfile:$.";
6751
6752         $_ .= "\n"
6753             unless substr ($_, -1, 1) eq "\n";
6754
6755         # Don't look at MAINTAINER_MODE_TRUE here.  That shouldn't be
6756         # used by users.  @MAINT@ is an anachronism now.
6757         $_ =~ s/\@MAINT\@//g
6758             unless $seen_maint_mode;
6759
6760         my $new_saw_bk = /\\$/ && ! /$COMMENT_PATTERN/o;
6761
6762         if (/$IGNORE_PATTERN/o)
6763         {
6764             # Merely delete comments beginning with two hashes.
6765         }
6766         elsif (/$WHITE_PATTERN/o)
6767         {
6768             # Stick a single white line before the incoming macro or rule.
6769             $spacing = "\n";
6770             am_file_error ($here, "blank line following trailing backslash")
6771                 if $saw_bk;
6772         }
6773         elsif (/$COMMENT_PATTERN/o)
6774         {
6775             # Stick comments before the incoming macro or rule.
6776             $comment .= $spacing . $_;
6777             $spacing = '';
6778             am_file_error ($here, "comment following trailing backslash")
6779                 if $saw_bk;
6780         }
6781         elsif ($saw_bk)
6782         {
6783             if ($was_rule)
6784             {
6785                 $output_trailer .= &make_condition (@cond_stack);
6786                 $output_trailer .= $_;
6787             }
6788             else
6789             {
6790               $last_var_value .= ' '
6791                 unless $last_var_value =~ /\s$/;
6792               $last_var_value .= $_;
6793
6794               if (!/\\$/)
6795                 {
6796                   $var_comment{$last_var_name} .= "$spacing"
6797                     if (!defined $var_comment{$last_var_name}
6798                         || substr ($var_comment{$last_var_name}, -1) ne "\n");
6799                   $var_comment{$last_var_name} .= "$comment";
6800                   $comment = $spacing = '';
6801                   macro_define ($last_var_name, 0,
6802                                 $last_var_type, $cond,
6803                                 $last_var_value, $here)
6804                     if $cond ne 'FALSE';
6805                   push (@var_list, $last_var_name);
6806                 }
6807             }
6808         }
6809
6810         elsif (/$IF_PATTERN/o)
6811           {
6812             $cond = cond_stack_if ($1, $2, $here);
6813           }
6814         elsif (/$ELSE_PATTERN/o)
6815           {
6816             $cond = cond_stack_else ($1, $2, $here);
6817           }
6818         elsif (/$ENDIF_PATTERN/o)
6819           {
6820             $cond = cond_stack_endif ($1, $2, $here);
6821           }
6822
6823         elsif (/$RULE_PATTERN/o)
6824         {
6825             # Found a rule.
6826             $was_rule = 1;
6827
6828             rule_define ($1, 0, $cond, $here);
6829
6830             $output_trailer .= $comment . $spacing;
6831             $output_trailer .= &make_condition (@cond_stack);
6832             $output_trailer .= $_;
6833             $comment = $spacing = '';
6834         }
6835         elsif (/$ASSIGNMENT_PATTERN/o)
6836         {
6837             # Found a macro definition.
6838             $was_rule = 0;
6839             $last_var_name = $1;
6840             $last_var_type = $2;
6841             $last_var_value = $3;
6842             if ($3 ne '' && substr ($3, -1) eq "\\")
6843             {
6844                 # We preserve the `\' because otherwise the long lines
6845                 # that are generated will be truncated by broken
6846                 # `sed's.
6847                 $last_var_value = $3 . "\n";
6848             }
6849
6850             if (!/\\$/)
6851               {
6852                 # FIXME: this doesn't always work correctly; it will
6853                 # group all comments for a given variable, no matter
6854                 # where defined.
6855                 # Accumulating variables must not be output.
6856                 $var_comment{$last_var_name} .= "$spacing"
6857                   if (!defined $var_comment{$last_var_name}
6858                       || substr ($var_comment{$last_var_name}, -1) ne "\n");
6859                 $var_comment{$last_var_name} .= "$comment";
6860                 $comment = $spacing = '';
6861
6862                 macro_define ($last_var_name, 0,
6863                               $last_var_type, $cond,
6864                               $last_var_value, $here)
6865                   if $cond ne 'FALSE';
6866                 push (@var_list, $last_var_name);
6867               }
6868         }
6869         elsif (/$INCLUDE_PATTERN/o)
6870         {
6871             my $path = $1;
6872
6873             if ($path =~ s/^\$\(top_srcdir\)\///)
6874             {
6875                 push (@include_stack, "\$\(top_srcdir\)/$path");
6876             }
6877             else
6878             {
6879                 $path =~ s/\$\(srcdir\)\///;
6880                 push (@include_stack, "\$\(srcdir\)/$path");
6881                 $path = $relative_dir . "/" . $path;
6882             }
6883             &read_am_file ($path);
6884         }
6885         else
6886         {
6887             # This isn't an error; it is probably a continued rule.
6888             # In fact, this is what we assume.
6889             $was_rule = 1;
6890             $output_trailer .= $comment . $spacing;
6891             $output_trailer .= &make_condition  (@cond_stack);
6892             $output_trailer .= $_;
6893             $comment = $spacing = '';
6894             am_file_error ($here, "`#' comment at start of rule is unportable")
6895                 if $_ =~ /^\t\s*\#/;
6896         }
6897
6898         $saw_bk = $new_saw_bk;
6899         $_ = $am_file->getline;
6900     }
6901
6902     $output_trailer .= $comment;
6903
6904     if (join (' ', @saved_cond_stack) ne join (' ', @cond_stack))
6905     {
6906         if (@cond_stack)
6907         {
6908             &am_error ("unterminated conditionals: @cond_stack");
6909         }
6910         else
6911         {
6912             # FIXME: better error message here.
6913             &am_error ("conditionals not nested in include file");
6914         }
6915     }
6916 }
6917
6918
6919 # define_standard_variables ()
6920 # ----------------------------
6921 # A helper for read_main_am_file which initializes configure variables
6922 # and variables from header-vars.am.  This is a subr so we can call it
6923 # twice.
6924 sub define_standard_variables
6925 {
6926     my $saved_output_vars = $output_vars;
6927     my ($comments, undef, $rules) =
6928       file_contents_internal (1, "$libdir/am/header-vars.am");
6929
6930     # This will output the definitions in $output_vars, which we don't
6931     # want...
6932     foreach my $var (sort keys %configure_vars)
6933     {
6934         &define_configure_variable ($var);
6935         push (@var_list, $var);
6936     }
6937
6938     # ... hence, we restore $output_vars.
6939     $output_vars = $saved_output_vars . $comments . $rules;
6940 }
6941
6942 # Read main am file.
6943 sub read_main_am_file
6944 {
6945     my ($amfile) = @_;
6946
6947     # This supports the strange variable tricks we are about to play.
6948     if (scalar keys %var_value > 0)
6949       {
6950         macros_dump ();
6951         &prog_error ("variable defined before read_main_am_file");
6952       }
6953
6954     # Generate copyright header for generated Makefile.in.
6955     # We do discard the output of predefined variables, handled below.
6956     $output_vars = ("# $in_file_name generated by automake "
6957                    . $VERSION . " from $am_file_name.\n");
6958     $output_vars .= '# ' . subst ('configure_input') . "\n";
6959     $output_vars .= $gen_copyright;
6960
6961     # We want to predefine as many variables as possible.  This lets
6962     # the user set them with `+=' in Makefile.am.  However, we don't
6963     # want these initial definitions to end up in the output quite
6964     # yet.  So we just load them, but output them later.
6965     &define_standard_variables;
6966
6967     # Read user file, which might override some of our values.
6968     &read_am_file ($amfile);
6969
6970     # Ouput all the Automake variables.  If the user changed one, then
6971     # it is now marked as owned by the user.
6972     foreach my $var (uniq @var_list)
6973     {
6974         # Don't process user variables.
6975         variable_output ($var)
6976           unless !$var_is_am{$var};
6977     }
6978
6979     # Now dump the user variables that were defined.  We do it in the same
6980     # order in which they were defined (skipping duplicates).
6981     foreach my $var (uniq @var_list)
6982     {
6983         # Don't process Automake variables.
6984         variable_output ($var)
6985           unless $var_is_am{$var};
6986     }
6987 }
6988
6989 ################################################################
6990
6991 # $FLATTENED
6992 # &flatten ($STRING)
6993 # ------------------
6994 # Flatten the $STRING and return the result.
6995 sub flatten
6996 {
6997   $_ = shift;
6998
6999   s/\\\n//somg;
7000   s/\s+/ /g;
7001   s/^ //;
7002   s/ $//;
7003
7004   return $_;
7005 }
7006
7007
7008 # @PARAGRAPHS
7009 # &make_paragraphs ($MAKEFILE, [%TRANSFORM])
7010 # ------------------------------------------
7011 # Load a $MAKEFILE, apply the %TRANSFORM, and return it as a list of
7012 # paragraphs.
7013 sub make_paragraphs ($%)
7014 {
7015     my ($file, %transform) = @_;
7016
7017     # Complete %transform with global options and make it a Perl
7018     # $command.
7019     my $command =
7020       "s/$IGNORE_PATTERN//gm;"
7021         . transform (%transform,
7022
7023                      'CYGNUS'          => $cygnus_mode,
7024                      'MAINTAINER-MODE'
7025                      => $seen_maint_mode ? subst ('MAINTAINER_MODE_TRUE') : '',
7026
7027                      'SHAR'        => $options{'dist-shar'} || 0,
7028                      'BZIP2'       => $options{'dist-bzip2'} || 0,
7029                      'ZIP'         => $options{'dist-zip'} || 0,
7030                      'COMPRESS'    => $options{'dist-tarZ'} || 0,
7031
7032                      'INSTALL-INFO' => !$options{'no-installinfo'},
7033                      'INSTALL-MAN'  => !$options{'no-installman'},
7034                      'CK-NEWS'      => $options{'check-news'} || 0,
7035
7036                      'SUBDIRS'      => &variable_defined ('SUBDIRS'),
7037                      'TOPDIR'       => backname ($relative_dir),
7038                      'TOPDIR_P'     => $relative_dir eq '.',
7039                      'CONFIGURE-AC' => $configure_ac,
7040
7041                      'BUILD'    => $seen_canonical == $AC_CANONICAL_SYSTEM,
7042                      'HOST'     => $seen_canonical,
7043                      'TARGET'   => $seen_canonical == $AC_CANONICAL_SYSTEM,
7044
7045                      'LIBTOOL'      => defined $configure_vars{'LIBTOOL'})
7046           # We don't need more than two consecutive new-lines.
7047           . 's/\n{3,}/\n\n/g';
7048
7049     # Swallow the file and apply the COMMAND.
7050     my $fc_file = new Automake::XFile ("< $file");
7051     # Looks stupid?
7052     print "$me: reading $file\n"
7053       if $verbose;
7054     my $saved_dollar_slash = $/;
7055     undef $/;
7056     $_ = $fc_file->getline;
7057     $/ = $saved_dollar_slash;
7058     eval $command;
7059     $fc_file->close;
7060     my $content = $_;
7061
7062     # Split at unescaped new lines.
7063     my @lines = split (/(?<!\\)\n/, $content);
7064     my @res;
7065
7066     while (defined ($_ = shift @lines))
7067       {
7068         my $paragraph = "$_";
7069         # If we are a rule, eat as long as we start with a tab.
7070         if (/$RULE_PATTERN/smo)
7071           {
7072             while (defined ($_ = shift @lines) && $_ =~ /^\t/)
7073               {
7074                 $paragraph .= "\n$_";
7075               }
7076             unshift (@lines, $_);
7077           }
7078
7079         # If we are a comments, eat as much comments as you can.
7080         elsif (/$COMMENT_PATTERN/smo)
7081           {
7082             while (defined ($_ = shift @lines)
7083                    && $_ =~ /$COMMENT_PATTERN/smo)
7084               {
7085                 $paragraph .= "\n$_";
7086               }
7087             unshift (@lines, $_);
7088           }
7089
7090         push @res, $paragraph;
7091         $paragraph = '';
7092       }
7093
7094     return @res;
7095 }
7096
7097
7098
7099 # ($COMMENT, $VARIABLES, $RULES)
7100 # &file_contents_internal ($IS_AM, $FILE, [%TRANSFORM])
7101 # -----------------------------------------------------
7102 # Return contents of a file from $libdir/am, automatically skipping
7103 # macros or rules which are already known. $IS_AM iff the caller is
7104 # reading an Automake file (as opposed to the user's Makefile.am).
7105 sub file_contents_internal ($$%)
7106 {
7107     my ($is_am, $file, %transform) = @_;
7108
7109     my $result_vars = '';
7110     my $result_rules = '';
7111     my $comment = '';
7112     my $spacing = '';
7113
7114     # We save the conditional stack on entry, and then check to make
7115     # sure it is the same on exit.  This lets us conditonally include
7116     # other files.
7117     my @saved_cond_stack = @cond_stack;
7118     my $cond = conditional_string (@cond_stack);
7119
7120     foreach (make_paragraphs ($file, %transform))
7121     {
7122         # Sanity checks.
7123         am_file_error ($file, "blank line following trailing backslash:\n$_")
7124           if /\\$/;
7125         am_file_error ($file, "comment following trailing backslash:\n$_")
7126           if /\\#/;
7127
7128         if (/^$/)
7129         {
7130             # Stick empty line before the incoming macro or rule.
7131             $spacing = "\n";
7132         }
7133         elsif (/$COMMENT_PATTERN/mso)
7134         {
7135             # Stick comments before the incoming macro or rule.
7136             $comment = "$_\n";
7137         }
7138
7139         # Handle inclusion of other files.
7140         elsif (/$INCLUDE_PATTERN/o)
7141         {
7142             if ($cond ne 'FALSE')
7143               {
7144                 my $file = ($is_am ? "$libdir/am/" : '') . $1;
7145                 # N-ary `.=' fails.
7146                 my ($com, $vars, $rules)
7147                   = file_contents_internal ($is_am, $file, %transform);
7148                 $comment .= $com;
7149                 $result_vars .= $vars;
7150                 $result_rules .= $rules;
7151               }
7152         }
7153
7154         # Handling the conditionals.
7155         elsif (/$IF_PATTERN/o)
7156           {
7157             $cond = cond_stack_if ($1, $2, $file);
7158           }
7159         elsif (/$ELSE_PATTERN/o)
7160           {
7161             $cond = cond_stack_else ($1, $2, $file);
7162           }
7163         elsif (/$ENDIF_PATTERN/o)
7164           {
7165             $cond = cond_stack_endif ($1, $2, $file);
7166           }
7167
7168         # Handling rules.
7169         elsif (/$RULE_PATTERN/mso)
7170         {
7171           # Separate relationship from optional actions: the first
7172           # `new-line tab" not preceded by backslash (continuation
7173           # line).
7174           # I'm quite shoked!  It seems that (\\\n|[^\n]) is not the
7175           # same as `([^\n]|\\\n)!!!  Don't swap it, it breaks.
7176           my $paragraph = $_;
7177           /^((?:\\\n|[^\n])*)(?:\n(\t.*))?$/som;
7178           my ($relationship, $actions) = ($1, $2 || '');
7179
7180           # Separate targets from dependencies: the first colon.
7181           $relationship =~ /^([^:]+\S+) *: *(.*)$/som;
7182           my ($targets, $dependencies) = ($1, $2);
7183           # Remove the escaped new lines.
7184           # I don't know why, but I have to use a tmp $flat_deps.
7185           my $flat_deps = &flatten ($dependencies);
7186           my @deps = split (' ', $flat_deps);
7187
7188           foreach (split (' ' , $targets))
7189             {
7190               # FIXME: We are not robust to people defining several targets
7191               # at once, only some of them being in %dependencies.
7192
7193               # Output only if not in FALSE.
7194               if (defined $dependencies{$_}
7195                   && $cond ne 'FALSE')
7196                 {
7197                   &depend ($_, @deps);
7198                   $actions{$_} .= $actions;
7199                 }
7200               else
7201                 {
7202                   # Free-lance dependency.  Output the rule for all the
7203                   # targets instead of one by one.
7204
7205                   # Work out all the conditions for which the target hasn't
7206                   # been defined
7207                   my @undefined_conds;
7208                   if (defined $target_conditional{$targets})
7209                     {
7210                       my @defined_conds = keys %{$target_conditional{$targets}};
7211                       @undefined_conds = invert_conditions(@defined_conds);
7212                     }
7213                   else
7214                     {
7215                       if (defined $targets{$targets})
7216                         {
7217                           # No conditions for which target hasn't been defined
7218                           @undefined_conds = ();
7219                         }
7220                       else
7221                         {
7222                           # Target hasn't been defined for any conditions
7223                           @undefined_conds = ("");
7224                         }
7225                     }
7226
7227                   if ($cond ne 'FALSE')
7228                     {
7229                       my $undefined_cond;
7230                       for $undefined_cond (@undefined_conds)
7231                       {
7232                           my $condparagraph = $paragraph;
7233                           $condparagraph =~ s/^/make_condition (@cond_stack, $undefined_cond)/gme;
7234                           $result_rules .= "$spacing$comment$condparagraph\n"
7235                               if rule_define ($targets, $is_am,
7236                                               "$cond $undefined_cond", $file);
7237                       }
7238                     }
7239                   $comment = $spacing = '';
7240                   last;
7241                 }
7242             }
7243         }
7244
7245         elsif (/$ASSIGNMENT_PATTERN/mso)
7246         {
7247             my ($var, $type, $val) = ($1, $2, $3);
7248             am_file_error ($file, "macro `$var' with trailing backslash")
7249               if /\\$/;
7250
7251             # Accumulating variables must not be output.
7252             $var_comment{$var} .= "$spacing"
7253               if (!defined $var_comment{$var}
7254                   || substr ($var_comment{$var}, -1) ne "\n");
7255             $var_comment{$var} .= "$comment";
7256             macro_define ($var, $is_am, $type, $cond, $val, $file)
7257               if $cond ne 'FALSE';
7258             push (@var_list, $var);
7259
7260             # If the user has set some variables we were in charge
7261             # of (which is detected by the first reading of
7262             # `header-vars.am'), we must not output them.
7263             $result_vars .= "$spacing$comment$_\n"
7264               if $type ne '+' && $var_is_am{$var} && $cond ne 'FALSE';
7265
7266             $comment = $spacing = '';
7267         }
7268         else
7269         {
7270             # This isn't an error; it is probably some tokens which
7271             # configure is supposed to replace, such as `@SET-MAKE@',
7272             # or some part of a rule cut by an if/endif.
7273             if ($cond ne 'FALSE')
7274               {
7275                 s/^/make_condition (@cond_stack)/gme;
7276                 $result_rules .= "$spacing$comment$_\n";
7277               }
7278             $comment = $spacing = '';
7279         }
7280     }
7281
7282     if (join (' ', @saved_cond_stack) ne join (' ', @cond_stack))
7283     {
7284         if (@cond_stack)
7285         {
7286             &am_error ("unterminated conditionals: @cond_stack");
7287         }
7288         else
7289         {
7290             # FIXME: better error message here.
7291             &am_error ("conditionals not nested in include file");
7292         }
7293     }
7294
7295     return ($comment, $result_vars, $result_rules);
7296 }
7297
7298
7299 # $CONTENTS
7300 # &file_contents ($BASENAME, [%TRANSFORM])
7301 # ----------------------------------------
7302 # Return contents of a file from $libdir/am, automatically skipping
7303 # macros or rules which are already known.
7304 sub file_contents ($%)
7305 {
7306     my ($basename, %transform) = @_;
7307     my ($comments, $variables, $rules) =
7308       file_contents_internal (1, "$libdir/am/$basename.am", %transform);
7309     return "$comments$variables$rules";
7310 }
7311
7312
7313 # $REGEXP
7314 # &transform (%PAIRS)
7315 # -------------------
7316 # Foreach ($TOKEN, $VAL) in %PAIRS produce a replacement expression suitable
7317 # for file_contents which:
7318 #   - replaces @$TOKEN@ with $VALUE,
7319 #   - enables/disables ?$TOKEN?.
7320 sub transform (%)
7321 {
7322     my (%pairs) = @_;
7323     my $result = '';
7324
7325     while (my ($token, $val) = each %pairs)
7326     {
7327         $result .= "s/\Q%$token%\E/\Q$val\E/gm;";
7328         if ($val)
7329         {
7330             $result .= "s/\Q?$token?\E//gm;s/^.*\Q?!$token?\E.*\\n//gm;";
7331             $result .= "s/\Q%?$token%\E/TRUE/gm;";
7332         }
7333         else
7334         {
7335             $result .= "s/\Q?!$token?\E//gm;s/^.*\Q?$token?\E.*\\n//gm;";
7336             $result .= "s/\Q%?$token%\E/FALSE/gm;";
7337         }
7338     }
7339
7340     return $result;
7341 }
7342
7343
7344 # Find all variable prefixes that are used for install directories.  A
7345 # prefix `zar' qualifies iff:
7346 # * `zardir' is a variable.
7347 # * `zar_PRIMARY' is a variable.
7348 sub am_primary_prefixes
7349 {
7350     my ($primary, $can_dist, @prefixes) = @_;
7351
7352     my %valid = map { $_ => 0 } @prefixes;
7353     $valid{'EXTRA'} = 0;
7354     foreach my $varname (keys %var_value)
7355     {
7356         # Automake is allowed to define variables that look like they
7357         # are magic variables, such as INSTALL_DATA.
7358         next
7359           if $var_is_am{$varname};
7360
7361         if ($varname =~ /^(nobase_)?(dist_|nodist_)?(.*)_$primary$/)
7362         {
7363             my ($base, $dist, $X) = ($1 || '', $2 || '', $3 || '');
7364             if ($dist ne '' && ! $can_dist)
7365             {
7366                 # Note that a configure variable is always legitimate.
7367                 # It is natural to name such variables after the
7368                 # primary, so we explicitly allow it.
7369                 if (! defined $configure_vars{$varname})
7370                 {
7371                     &am_line_error ($varname,
7372                                     "invalid variable `$varname': `dist' is forbidden");
7373                 }
7374             }
7375             elsif (! defined $valid{$X} && ! &variable_defined ("${X}dir"))
7376             {
7377                 # Note that a configure variable is always legitimate.
7378                 # It is natural to name such variables after the
7379                 # primary, so we explicitly allow it.
7380                 if (! defined $configure_vars{$varname})
7381                 {
7382                     &am_line_error ($varname,
7383                                     "invalid variable `$varname'");
7384                 }
7385             }
7386             else
7387             {
7388                 # Ensure all extended prefixes are actually used.
7389                 $valid{"$base$dist$X"} = 1;
7390             }
7391         }
7392     }
7393
7394     return %valid;
7395 }
7396
7397 # Handle `where_HOW' variable magic.  Does all lookups, generates
7398 # install code, and possibly generates code to define the primary
7399 # variable.  The first argument is the name of the .am file to munge,
7400 # the second argument is the primary variable (eg HEADERS), and all
7401 # subsequent arguments are possible installation locations.  Returns
7402 # list of all values of all _HOW targets.
7403 #
7404 # FIXME: this should be rewritten to be cleaner.  It should be broken
7405 # up into multiple functions.
7406 #
7407 # Usage is: am_install_var (OPTION..., file, HOW, where...)
7408 sub am_install_var
7409 {
7410     my (@args) = @_;
7411
7412     my $do_require = 1;
7413     my $can_dist = 0;
7414     my $default_dist = 0;
7415     while (@args)
7416     {
7417         if ($args[0] eq '-noextra')
7418         {
7419             $do_require = 0;
7420         }
7421         elsif ($args[0] eq '-candist')
7422         {
7423             $can_dist = 1;
7424         }
7425         elsif ($args[0] eq '-defaultdist')
7426         {
7427             $default_dist = 1;
7428             $can_dist = 1;
7429         }
7430         elsif ($args[0] !~ /^-/)
7431         {
7432             last;
7433         }
7434         shift (@args);
7435     }
7436
7437     my ($file, $primary, @prefixes) = @args;
7438
7439     # Now that configure substitutions are allowed in where_HOW
7440     # variables, it is an error to actually define the primary.  We
7441     # allow `JAVA', as it is customarily used to mean the Java
7442     # interpreter.  This is but one of several Java hacks.  Similarly,
7443     # `PYTHON' is customarily used to mean the Python interpreter.
7444     am_macro_error ($primary, "`$primary' is an anachronism")
7445         if &variable_defined ($primary)
7446             && ($primary ne 'JAVA' && $primary ne 'PYTHON');
7447
7448
7449     # Look for misspellings.  It is an error to have a variable ending
7450     # in a "reserved" suffix whose prefix is unknown, eg
7451     # "bni_PROGRAMS".  However, unusual prefixes are allowed if a
7452     # variable of the same name (with "dir" appended) exists.  For
7453     # instance, if the variable "zardir" is defined, then
7454     # "zar_PROGRAMS" becomes valid.  This is to provide a little extra
7455     # flexibility in those cases which need it.
7456     my %valid = &am_primary_prefixes ($primary, $can_dist, @prefixes);
7457
7458     # If a primary includes a configure substitution, then the EXTRA_
7459     # form is required.  Otherwise we can't properly do our job.
7460     my $require_extra;
7461     my $warned_about_extra = 0;
7462
7463     my @used = ();
7464     my @result = ();
7465
7466     # True if the iteration is the first one.  Used for instance to
7467     # output parts of the associated file only once.
7468     my $first = 1;
7469     foreach my $X (sort keys %valid)
7470     {
7471         my $nodir_name = $X;
7472         my $one_name = $X . '_' . $primary;
7473         next
7474           unless (&variable_defined ($one_name));
7475
7476         my $strip_subdir = 1;
7477         # If subdir prefix should be preserved, do so.
7478         if ($nodir_name =~ /^nobase_/)
7479           {
7480             $strip_subdir = 0;
7481             $nodir_name =~ s/^nobase_//;
7482           }
7483
7484         # If files should be distributed, do so.
7485         my $dist_p = 0;
7486         if ($can_dist)
7487           {
7488             $dist_p = (($default_dist && $nodir_name !~ /^nodist_/)
7489                        || (! $default_dist && $nodir_name =~ /^dist_/));
7490             $nodir_name =~ s/^(dist|nodist)_//;
7491           }
7492
7493         # Append actual contents of where_PRIMARY variable to
7494         # result.
7495         foreach my $rcurs (&variable_value_as_list_recursive ($one_name, 'all'))
7496           {
7497             # Skip configure substitutions.  Possibly bogus.
7498             if ($rcurs =~ /^\@.*\@$/)
7499               {
7500                 if ($nodir_name eq 'EXTRA')
7501                   {
7502                     if (! $warned_about_extra)
7503                       {
7504                         $warned_about_extra = 1;
7505                         am_macro_error ($one_name,
7506                                         "`$one_name' contains configure substitution, but shouldn't");
7507                       }
7508                   }
7509                 # Check here to make sure variables defined in
7510                 # configure.ac do not imply that EXTRA_PRIMARY
7511                 # must be defined.
7512                 elsif (! defined $configure_vars{$one_name})
7513                   {
7514                     $require_extra = $one_name
7515                       if $do_require;
7516                   }
7517
7518                 next;
7519               }
7520
7521             push (@result, $rcurs);
7522           }
7523
7524         # A blatant hack: we rewrite each _PROGRAMS primary to include
7525         # EXEEXT.
7526         if ($primary eq 'PROGRAMS')
7527         {
7528             my @conds = variable_conditions_recursive ($one_name);
7529
7530             my @condvals;
7531             foreach my $cond (@conds)
7532             {
7533                 my @one_binlist = ();
7534                 my @condval = &variable_value_as_list_recursive ($one_name,
7535                                                        $cond);
7536                 foreach my $rcurs (@condval)
7537                 {
7538                     # Skip autoconf substs.  Also skip if the user
7539                     # already applied $(EXEEXT).
7540                     if ($rcurs =~ /^\@.*\@$/ || $rcurs =~ /\$\(EXEEXT\)$/)
7541                     {
7542                         push (@one_binlist, $rcurs);
7543                     }
7544                     else
7545                     {
7546                         push (@one_binlist, $rcurs . '$(EXEEXT)');
7547                     }
7548                 }
7549
7550                 push (@condvals, $cond);
7551                 push (@condvals, join (' ', @one_binlist));
7552             }
7553
7554             variable_delete ($one_name);
7555             while (@condvals)
7556             {
7557                 my $cond = shift (@condvals);
7558                 my @val = split (' ', shift (@condvals));
7559                 define_pretty_variable ($one_name, $cond, @val);
7560             }
7561         }
7562
7563         # "EXTRA" shouldn't be used when generating clean targets,
7564         # all, or install targets.
7565         if ($nodir_name eq 'EXTRA')
7566           {
7567             # We used to warn if EXTRA_FOO was defined uselessly,
7568             # but this was annoying.
7569             next;
7570           }
7571
7572         if ($nodir_name eq 'check')
7573           {
7574             push (@check, '$(' . $one_name . ')');
7575           }
7576         else
7577           {
7578             push (@used, '$(' . $one_name . ')');
7579           }
7580
7581         # Is this to be installed?
7582         my $install_p = $nodir_name ne 'noinst' && $nodir_name ne 'check';
7583
7584         # If so, with install-exec? (or install-data?).
7585         my $exec_p = (defined $exec_dir_p {$nodir_name}
7586                       ? $exec_dir_p {$nodir_name}
7587                       : ($nodir_name =~ /exec/));
7588
7589         # Singular form of $PRIMARY.
7590         (my $one_primary = $primary) =~ s/S$//;
7591         $output_rules .= &file_contents ($file,
7592                                          ('FIRST' => $first,
7593
7594                                           'PRIMARY'     => $primary,
7595                                           'ONE_PRIMARY' => $one_primary,
7596                                           'DIR'         => $X,
7597                                           'NDIR'        => $nodir_name,
7598                                           'BASE'        => $strip_subdir,
7599
7600                                           'EXEC'    => $exec_p,
7601                                           'INSTALL' => $install_p,
7602                                           'DIST'    => $dist_p));
7603
7604         $first = 0;
7605     }
7606
7607     # The JAVA variable is used as the name of the Java interpreter.
7608     # The PYTHON variable is used as the name of the Python interpreter.
7609     if (@used && $primary ne 'JAVA' && $primary ne 'PYTHON')
7610     {
7611         # Define it.
7612         define_pretty_variable ($primary, '', @used);
7613         $output_vars .= "\n";
7614     }
7615
7616     if ($require_extra && ! &variable_defined ('EXTRA_' . $primary))
7617     {
7618         am_macro_error ($require_extra,
7619                         "`$require_extra' contains configure substitution, but `EXTRA_$primary' not defined");
7620     }
7621
7622     # Push here because PRIMARY might be configure time determined.
7623     push (@all, '$(' . $primary . ')')
7624         if @used && $primary ne 'JAVA' && $primary ne 'PYTHON';
7625
7626     # Make the result unique.  This lets the user use conditionals in
7627     # a natural way, but still lets us program lazily -- we don't have
7628     # to worry about handling a particular object more than once.
7629     return uniq (sort @result);
7630 }
7631
7632
7633 ################################################################
7634
7635 # Each key in this hash is the name of a directory holding a
7636 # Makefile.in.  These variables are local to `is_make_dir'.
7637 my %make_dirs = ();
7638 my $make_dirs_set = 0;
7639
7640 sub is_make_dir
7641 {
7642     my ($dir) = @_;
7643     if (! $make_dirs_set)
7644     {
7645         foreach my $iter (@configure_input_files)
7646         {
7647             $make_dirs{dirname ($iter)} = 1;
7648         }
7649         # We also want to notice Makefile.in's.
7650         foreach my $iter (@other_input_files)
7651         {
7652             if ($iter =~ /Makefile\.in$/)
7653             {
7654                 $make_dirs{dirname ($iter)} = 1;
7655             }
7656         }
7657         $make_dirs_set = 1;
7658     }
7659     return defined $make_dirs{$dir};
7660 }
7661
7662 ################################################################
7663
7664 # This variable is local to the "require file" set of functions.
7665 my @require_file_paths = ();
7666
7667 # If a file name appears as a key in this hash, then it has already
7668 # been checked for.  This variable is local to the "require file"
7669 # functions.
7670 %require_file_found = ();
7671
7672 # See if we want to push this file onto dist_common.  This function
7673 # encodes the rules for deciding when to do so.
7674 sub maybe_push_required_file
7675 {
7676     my ($dir, $file, $fullfile) = @_;
7677
7678     if ($dir eq $relative_dir)
7679     {
7680         &push_dist_common ($file);
7681     }
7682     elsif ($relative_dir eq '.' && ! &is_make_dir ($dir))
7683     {
7684         # If we are doing the topmost directory, and the file is in a
7685         # subdir which does not have a Makefile, then we distribute it
7686         # here.
7687         &push_dist_common ($fullfile);
7688     }
7689 }
7690
7691
7692 # &require_file_internal ($WHERE, $MYSTRICT, @FILES)
7693 # --------------------------------------------------
7694 # Verify that the file must exist in the current directory.
7695 # $MYSTRICT is the strictness level at which this file becomes required.
7696 #
7697 # Must set require_file_paths before calling this function.
7698 # require_file_paths is set to hold a single directory (the one in
7699 # which the first file was found) before return.
7700 sub require_file_internal
7701 {
7702     my ($where, $mystrict, @files) = @_;
7703
7704     foreach my $file (@files)
7705     {
7706         my $fullfile;
7707         my $errdir;
7708         my $errfile;
7709         my $save_dir;
7710
7711         my $found_it = 0;
7712         my $dangling_sym = 0;
7713         foreach my $dir (@require_file_paths)
7714         {
7715             $fullfile = $dir . "/" . $file;
7716             $errdir = $dir unless $errdir;
7717
7718             # Use different name for "error filename".  Otherwise on
7719             # an error the bad file will be reported as eg
7720             # `../../install-sh' when using the default
7721             # config_aux_path.
7722             $errfile = $errdir . '/' . $file;
7723
7724             if (-l $fullfile && ! -f $fullfile)
7725             {
7726                 $dangling_sym = 1;
7727                 last;
7728             }
7729             elsif (-f $fullfile)
7730             {
7731                 $found_it = 1;
7732                 &maybe_push_required_file ($dir, $file, $fullfile);
7733                 $save_dir = $dir;
7734                 last;
7735             }
7736         }
7737
7738         # `--force-missing' only has an effect if `--add-missing' is
7739         # specified.
7740         if ($found_it && (! $add_missing || ! $force_missing))
7741         {
7742             # Prune the path list.
7743             @require_file_paths = $save_dir;
7744         }
7745         else
7746         {
7747             # If we've already looked for it, we're done.  You might
7748             # wonder why we don't do this before searching for the
7749             # file.  If we do that, then something like
7750             # AC_OUTPUT(subdir/foo foo) will fail to put foo.in into
7751             # DIST_COMMON.
7752             if (! $found_it)
7753             {
7754                 next if defined $require_file_found{$file};
7755                 $require_file_found{$file} = 1;
7756             }
7757
7758             if ($strictness >= $mystrict)
7759             {
7760                 if ($dangling_sym && $add_missing)
7761                 {
7762                     unlink ($fullfile);
7763                 }
7764
7765                 my $trailer = '';
7766                 my $suppress = 0;
7767
7768                 # Only install missing files according to our desired
7769                 # strictness level.
7770                 my $message = "required file `$errfile' not found";
7771                 if ($add_missing)
7772                 {
7773                     $suppress = 1;
7774
7775                     # Maybe run libtoolize.
7776                     my @syslist = ('libtoolize', '--automake');
7777                     push @syslist, '--copy'
7778                         if $copy_missing;
7779                     if ($seen_libtool
7780                         && grep ($_ eq $file, @libtoolize_files)
7781                         && system (@syslist))
7782                     {
7783                         $message = "installing `$errfile'";
7784                         $suppress = 0;
7785                         $trailer = "; cannot run `libtoolize': $!";
7786                     }
7787                     elsif (-f ("$libdir/$file"))
7788                     {
7789                         # Install the missing file.  Symlink if we
7790                         # can, copy if we must.  Note: delete the file
7791                         # first, in case it is a dangling symlink.
7792                         $message = "installing `$errfile'";
7793                         # Windows Perl will hang if we try to delete a
7794                         # file that doesn't exist.
7795                         unlink ($errfile) if -f $errfile;
7796                         if ($symlink_exists && ! $copy_missing)
7797                         {
7798                             if (! symlink ("$libdir/$file", $errfile))
7799                             {
7800                                 $suppress = 0;
7801                                 $trailer = "; error while making link: $!";
7802                             }
7803                         }
7804                         elsif (system ('cp', "$libdir/$file", $errfile))
7805                         {
7806                             $suppress = 0;
7807                             $trailer = "\n    error while copying";
7808                         }
7809                     }
7810
7811                     &maybe_push_required_file (dirname ($errfile),
7812                                                $file, $errfile);
7813
7814                     # Prune the path list.
7815                     @require_file_paths = &dirname ($errfile);
7816                 }
7817
7818                 # If --force-missing was specified, and we have
7819                 # actually found the file, then do nothing.
7820                 next
7821                     if $found_it && $force_missing;
7822
7823                 if ($suppress)
7824                 {
7825                     if ($is_configure)
7826                     {
7827                         # FIXME: allow actual file to be specified.
7828                         am_file_warning ("$configure_ac:$line",
7829                                          "$message$trailer");
7830                     }
7831                     else
7832                     {
7833                         &am_line_warning ($line, "$message$trailer");
7834                     }
7835                 }
7836                 else
7837                 {
7838                     if ($is_configure)
7839                     {
7840                         # FIXME: allow actual file to be specified.
7841                         am_file_error ("$configure_ac:$line",
7842                                        "$message$trailer");
7843                     }
7844                     else
7845                     {
7846                         am_line_error ($line, "$message$trailer");
7847                     }
7848                 }
7849             }
7850         }
7851     }
7852 }
7853
7854 # Like require_file_with_line, but error messages refer to
7855 # configure.ac, not the current Makefile.am.
7856 sub require_file_with_conf_line
7857 {
7858     @require_file_paths = $relative_dir;
7859     &require_file_internal (1, @_);
7860 }
7861
7862 sub require_file_with_line
7863 {
7864     @require_file_paths = $relative_dir;
7865     &require_file_internal (0, @_);
7866 }
7867
7868 sub require_file
7869 {
7870     @require_file_paths = $relative_dir;
7871     &require_file_internal (0, '', @_);
7872 }
7873
7874 # Require an auxiliary file.
7875 # Looks in configuration path, as specified by AC_CONFIG_AUX_DIR.
7876 sub require_aux_file_with_line
7877 {
7878     my $from = shift;  # 1 for configure.ac, 0 for Makefile.am
7879     my $line = shift;
7880     @require_file_paths = @config_aux_path;
7881     &require_file_internal ($from, $line, @_);
7882     my $dir = $require_file_paths[0];
7883     # &require_file_internal pruned the file path to the
7884     # exact directory where the file is lying.  Update
7885     # @config_aux_path to speed up future uses.
7886     @config_aux_path = @require_file_paths;
7887      # Avoid unsightly '/.'s.
7888     $config_aux_dir = '$(top_srcdir)' . ($dir eq '.' ? "" : "/$dir");
7889 }
7890
7891 # Assumes that the line number is in Makefile.am.
7892 sub require_conf_file_with_line
7893 {
7894     &require_aux_file_with_line (0, @_);
7895 }
7896
7897 # File required from a Makefile.am.  No line number available.
7898 sub require_conf_file
7899 {
7900     &require_conf_file_with_line ('', @_);
7901 }
7902
7903 # Assumes that the line number is in configure.ac.
7904 sub require_conf_file_with_conf_line
7905 {
7906     &require_aux_file_with_line (1, @_);
7907 }
7908
7909 # Require a file that is also required by Autoconf.  No line number available.
7910 sub require_config_file
7911 {
7912     &require_conf_file_with_conf_line ('', @_);
7913 }
7914
7915 ################################################################
7916
7917 # &require_build_directory ($DIRECTORY)
7918 # ------------------------------------
7919 # Emit rules to create $DIRECTORY if needed, and return
7920 # the file that any target requiring this directory should be made
7921 # dependent upon.
7922 sub require_build_directory ($)
7923 {
7924     my $directory = shift;
7925     my $dirstamp = "$directory/.dirstamp";
7926
7927     # Don't emit the rule twice.
7928     if (! defined $directory_map{$directory})
7929     {
7930         $directory_map{$directory} = 1;
7931
7932         # Directory must be removed by `make distclean'.
7933         $compile_clean_files{$dirstamp} = $DIST_CLEAN;
7934
7935         $output_rules .= ("$dirstamp:\n"
7936                           . "\t\@\$(mkinstalldirs) $directory\n"
7937                           . "\t\@: > $dirstamp\n");
7938     }
7939
7940     return $dirstamp;
7941 }
7942
7943 # &require_build_directory_maybe ($FILE)
7944 # --------------------------------------
7945 # If $FILE lies in a subdirectory, emit a rule to create this
7946 # directory and return the file that $FILE should be made
7947 # dependent upon.  Otherwise, just return the empty string.
7948 sub require_build_directory_maybe ($)
7949 {
7950     my $file = shift;
7951     my $directory = dirname ($file);
7952
7953     if ($directory ne '.')
7954     {
7955         return &require_build_directory ($directory);
7956     }
7957     else
7958     {
7959         return '';
7960     }
7961 }
7962
7963 ################################################################
7964
7965 # Push a list of files onto dist_common.
7966 sub push_dist_common
7967 {
7968     &prog_error ("push_dist_common run after handle_dist")
7969         if $handle_dist_run;
7970     macro_define ('DIST_COMMON', 1, '+', '', join (' ', @_), '');
7971 }
7972
7973
7974 # Set strictness.
7975 sub set_strictness
7976 {
7977     $strictness_name = $_[0];
7978     if ($strictness_name eq 'gnu')
7979     {
7980         $strictness = $GNU;
7981     }
7982     elsif ($strictness_name eq 'gnits')
7983     {
7984         $strictness = $GNITS;
7985     }
7986     elsif ($strictness_name eq 'foreign')
7987     {
7988         $strictness = $FOREIGN;
7989     }
7990     else
7991     {
7992         die "$me: level `$strictness_name' not recognized\n";
7993     }
7994 }
7995
7996
7997 ################################################################
7998
7999 # Ensure a file exists.
8000 sub create
8001 {
8002     my ($file) = @_;
8003
8004     my $touch = new IO::File (">> $file");
8005     $touch->close;
8006 }
8007
8008 # Glob something.  Do this to avoid indentation screwups everywhere we
8009 # want to glob.  Gross!
8010 sub my_glob
8011 {
8012     my ($pat) = @_;
8013     return <${pat}>;
8014 }
8015
8016 # Remove one level of brackets and strip leading spaces,
8017 # as does m4 to function arguments.
8018 sub unquote_m4_arg
8019 {
8020     $_ = shift;
8021     s/^\s*//;
8022
8023     my @letters = split //;
8024     my @result = ();
8025     my $depth = 0;
8026
8027     foreach (@letters)
8028     {
8029         if ($_ eq '[')
8030         {
8031             ++$depth;
8032             next if $depth == 1;
8033         }
8034         elsif ($_ eq ']')
8035         {
8036             --$depth;
8037             next if $depth == 0;
8038             # don't count orphan right brackets
8039             $depth = 0 if $depth < 0;
8040         }
8041         push @result, $_;
8042     }
8043     return join '', @result;
8044 }
8045
8046 ################################################################
8047
8048 # am_print_error ($LEADER, @ARGS)
8049 # -------------------------------
8050 # Do the work of printing the error message.  Join @ARGS with spaces,
8051 # then split at newlines and add $LEADER to each line.  Uses `warn' to
8052 # print message.  Set exit status.
8053 sub am_print_error
8054 {
8055     my ($leader, @args) = @_;
8056     my $text = join (' ', @args);
8057     @args = split ("\n", $text);
8058     $text = $leader . join ("\n" . $leader, @args) . "\n";
8059     warn $text;
8060     $exit_status = 1;
8061 }
8062
8063 # Print an error message and set exit status.
8064 sub am_error
8065 {
8066     am_print_error ("$me: ${am_file}.am: ", @_);
8067 }
8068
8069 # am_file_error ($FILE, @ARGS)
8070 # ----------------------------
8071 sub am_file_error ($@)
8072 {
8073     my ($file, @args) = @_;
8074
8075     am_print_error ("$file: ", @args);
8076 }
8077
8078
8079 # &am_macro_error ($MACRO, @ARGS)
8080 # -------------------------------
8081 # Report an error, @ARGS, about $MACRO.
8082 sub am_macro_error ($@)
8083 {
8084     my ($macro, @args) = @_;
8085     am_file_error ($var_location{$macro}, @args);
8086 }
8087
8088
8089 # &am_target_error ($TARGET, @ARGS)
8090 # ---------------------------------
8091 # Report an error, @ARGS, about the rule $TARGET.
8092 sub am_target_error ($@)
8093 {
8094     my ($target, @args) = @_;
8095     am_file_error ($targets{$target}, @args);
8096 }
8097
8098
8099 # &am_line_error ($SYMBOL or $LINE, @ARGS)
8100 # ----------------------------------------
8101 # Report an error about $SYMBOL.  The error message is composed of the
8102 # @ARGS, and try to find the location of the error of $SYMBOL.
8103 sub am_line_error ($@)
8104 {
8105     my ($symbol, @args) = @_;
8106
8107     if ($symbol && "$symbol" ne '-1')
8108     {
8109         if ($symbol =~ /^\d+$/)
8110         {
8111             # SYMBOL is a line number, then it must be a Makefile.am.
8112             am_file_error ("${am_file}.am:$symbol", @args);
8113         }
8114         elsif (defined $configure_vars{$symbol})
8115         {
8116             # SYMBOL is a variable defined in configure.ac, so add the
8117             # appropriate line number.
8118             am_file_error ($configure_vars{$symbol}, @args);
8119         }
8120         elsif (defined $var_location{$symbol})
8121         {
8122             croak "use am_macro_error for macros: $symbol\n";
8123         }
8124         elsif (defined $targets{$symbol})
8125         {
8126             croak "use am_target_error for targets: $symbol\n";
8127         }
8128         else
8129         {
8130             # Couldn't find the line number.
8131             am_file_error ("${am_file}.am", @args);
8132         }
8133     }
8134     else
8135     {
8136         &am_error (@args);
8137     }
8138 }
8139
8140 # Like am_error, but while scanning configure.ac.
8141 sub am_conf_error
8142 {
8143     # FIXME: can run in subdirs.
8144     am_print_error ("$me: $configure_ac: ", @_);
8145 }
8146
8147 # Warning message with line number referring to configure.ac.
8148 # Does not affect exit_status
8149 sub am_file_warning (@)
8150 {
8151     my $saved_exit_status = $exit_status;
8152     my $sig = $SIG{'__WARN__'};
8153     $SIG{'__WARN__'} = 'DEFAULT';
8154     am_file_error (@_);
8155     $exit_status = $saved_exit_status;
8156     $SIG{'__WARN__'} = $sig;
8157 }
8158
8159 # Like am_line_error, but doesn't affect exit status.
8160 sub am_line_warning (@)
8161 {
8162     my $saved_exit_status = $exit_status;
8163     my $sig = $SIG{'__WARN__'};
8164     $SIG{'__WARN__'} = 'DEFAULT';
8165     am_line_error (@_);
8166     $exit_status = $saved_exit_status;
8167     $SIG{'__WARN__'} = $sig;
8168 }
8169
8170 # Tell user where our aclocal.m4 is, but only once.
8171 sub keyed_aclocal_warning ($)
8172 {
8173     my ($key) = @_;
8174     warn "$me: macro `$key' can be generated by `aclocal'\n";
8175 }
8176
8177 # Print usage information.
8178 sub usage ()
8179 {
8180     print <<EOF;
8181 Usage: $0 [OPTION] ... [Makefile]...
8182
8183 Generate Makefile.in for configure from Makefile.am.
8184
8185 Operation modes:
8186       --help             print this help, then exit
8187       --version          print version number, then exit
8188   -v, --verbose          verbosely list files processed
8189   -o, --output-dir=DIR   put generated Makefile.in's into DIR
8190       --no-force         only update Makefile.in's that are out of date
8191
8192 Dependency tracking:
8193   -i, --ignore-deps      disable dependency tracking code
8194       --include-deps     enable dependency tracking code
8195
8196 Flavors:
8197       --cygnus           assume program is part of Cygnus-style tree
8198       --foreign          set strictness to foreign
8199       --gnits            set strictness to gnits
8200       --gnu              set strictness to gnu
8201
8202 Library files:
8203   -a, --add-missing      add missing standard files to package
8204       --libdir=DIR       directory storing library files
8205   -c, --copy             with -a, copy missing files (default is symlink)
8206   -f, --force-missing    force update of standard files
8207 EOF
8208
8209     my ($last, @lcomm);
8210     $last = '';
8211     foreach my $iter (sort ((@common_files, @common_sometimes)))
8212     {
8213         push (@lcomm, $iter) unless $iter eq $last;
8214         $last = $iter;
8215     }
8216
8217     my @four;
8218     print "\nFiles which are automatically distributed, if found:\n";
8219     format USAGE_FORMAT =
8220   @<<<<<<<<<<<<<<<<   @<<<<<<<<<<<<<<<<   @<<<<<<<<<<<<<<<<   @<<<<<<<<<<<<<<<<
8221   $four[0],           $four[1],           $four[2],           $four[3]
8222 .
8223     $~ = "USAGE_FORMAT";
8224
8225     my $cols = 4;
8226     my $rows = int(@lcomm / $cols);
8227     my $rest = @lcomm % $cols;
8228
8229     if ($rest)
8230     {
8231         $rows++;
8232     }
8233     else
8234     {
8235         $rest = $cols;
8236     }
8237
8238     for (my $y = 0; $y < $rows; $y++)
8239     {
8240         @four = ("", "", "", "");
8241         for (my $x = 0; $x < $cols; $x++)
8242         {
8243             last if $y + 1 == $rows && $x == $rest;
8244
8245             my $idx = (($x > $rest)
8246                        ?  ($rows * $rest + ($rows - 1) * ($x - $rest))
8247                        : ($rows * $x));
8248
8249             $idx += $y;
8250             $four[$x] = $lcomm[$idx];
8251         }
8252         write;
8253     }
8254
8255     print "\nReport bugs to <bug-automake\@gnu.org>.\n";
8256
8257     exit 0;
8258 }
8259
8260 # &version ()
8261 # -----------
8262 # Print version information
8263 sub version ()
8264 {
8265   print <<EOF;
8266 automake (GNU $PACKAGE) $VERSION
8267 Written by Tom Tromey <tromey\@cygnus.com>.
8268
8269 Copyright 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001
8270 Free Software Foundation, Inc.
8271 This is free software; see the source for copying conditions.  There is NO
8272 warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
8273 EOF
8274   exit 0;
8275 }