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