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