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