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