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