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