* automake.in (scan_autoconf_files): Don't complain that
[automake.git] / automake.in
blobe161d2d7fd1281a632b38be274cc22a16de165ae
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     if (! $seen_init_automake)
5362       {
5363         err_ac "`AM_INIT_AUTOMAKE' must be used";
5364       }
5365     else
5366       {
5367         if (! $seen_automake_version)
5368           {
5369             if (-f 'aclocal.m4')
5370               {
5371                 error ($seen_init_automake,
5372                        "your implementation of AM_INIT_AUTOMAKE comes from " .
5373                        "an\nold Automake version.  You should recreate " .
5374                        "aclocal.m4\nwith aclocal and run automake again.\n");
5375               }
5376             else
5377               {
5378                 error ($seen_init_automake,
5379                        "no proper implementation of AM_INIT_AUTOMAKE was " .
5380                        "found,\nprobably because aclocal.m4 is missing...\n" .
5381                        "You should run aclocal to create this file, then\n" .
5382                        "run automake again.\n");
5383               }
5384           }
5385       }
5387     # Look for some files we need.  Always check for these.  This
5388     # check must be done for every run, even those where we are only
5389     # looking at a subdir Makefile.  We must set relative_dir so that
5390     # the file-finding machinery works.
5391     # FIXME: Is this broken because it needs dynamic scopes.
5392     # My tests seems to show it's not the case.
5393     $relative_dir = '.';
5394     require_conf_file ($configure_ac, FOREIGN,
5395                        'install-sh', 'mkinstalldirs', 'missing');
5396     err_am "`install.sh' is an anachronism; use `install-sh' instead"
5397       if -f $config_aux_path[0] . '/install.sh';
5399     # Preserve dist_common for later.
5400     $configure_dist_common = variable_value ('DIST_COMMON', 'TRUE') || '';
5403 ################################################################
5405 # Set up for Cygnus mode.
5406 sub check_cygnus
5408   return unless $cygnus_mode;
5410   &set_strictness ('foreign');
5411   $options{'no-installinfo'} = 1;
5412   $options{'no-dependencies'} = 1;
5413   $use_dependencies = 0;
5415   err_ac "`AM_MAINTAINER_MODE' required when --cygnus specified"
5416     if !$seen_maint_mode;
5419 # Do any extra checking for GNU standards.
5420 sub check_gnu_standards
5422   if ($relative_dir eq '.')
5423     {
5424       # In top level (or only) directory.
5426       # Accept one of these three licenses; default to COPYING.
5427       my $license = 'COPYING';
5428       foreach (qw /COPYING.LIB COPYING.LESSER/)
5429         {
5430           $license = $_ if -f $_;
5431         }
5432       require_file ("$am_file.am", GNU, $license,
5433                     qw/INSTALL NEWS README AUTHORS ChangeLog/);
5434     }
5436   for my $opt ('no-installman', 'no-installinfo')
5437     {
5438       msg_var ('error-gnu', 'AUTOMAKE_OPTIONS',
5439                "option `$opt' disallowed by GNU standards")
5440         if (defined $options{$opt});
5441     }
5444 # Do any extra checking for GNITS standards.
5445 sub check_gnits_standards
5447   if ($relative_dir eq '.')
5448     {
5449       # In top level (or only) directory.
5450       require_file ("$am_file.am", GNITS, 'THANKS');
5451     }
5454 ################################################################
5456 # Functions to handle files of each language.
5458 # Each `lang_X_rewrite($DIRECTORY, $BASE, $EXT)' function follows a
5459 # simple formula: Return value is LANG_SUBDIR if the resulting object
5460 # file should be in a subdir if the source file is, LANG_PROCESS if
5461 # file is to be dealt with, LANG_IGNORE otherwise.
5463 # Much of the actual processing is handled in
5464 # handle_single_transform_list.  These functions exist so that
5465 # auxiliary information can be recorded for a later cleanup pass.
5466 # Note that the calls to these functions are computed, so don't bother
5467 # searching for their precise names in the source.
5469 # This is just a convenience function that can be used to determine
5470 # when a subdir object should be used.
5471 sub lang_sub_obj
5473     return defined $options{'subdir-objects'} ? LANG_SUBDIR : LANG_PROCESS;
5476 # Rewrite a single C source file.
5477 sub lang_c_rewrite
5479   my ($directory, $base, $ext) = @_;
5481   if (defined $options{'ansi2knr'} && $base =~ /_$/)
5482     {
5483       # FIXME: include line number in error.
5484       err_am "C source file `$base.c' would be deleted by ansi2knr rules";
5485     }
5487   my $r = LANG_PROCESS;
5488   if (defined $options{'subdir-objects'})
5489     {
5490       $r = LANG_SUBDIR;
5491       $base = $directory . '/' . $base
5492         unless $directory eq '.' || $directory eq '';
5494       err_am ("C objects in subdir but `AM_PROG_CC_C_O' "
5495               . "not in `$configure_ac'",
5496               uniq_scope => US_GLOBAL)
5497         unless $seen_cc_c_o;
5499       require_conf_file ("$am_file.am", FOREIGN, 'compile');
5501       # In this case we already have the directory information, so
5502       # don't add it again.
5503       $de_ansi_files{$base} = '';
5504     }
5505   else
5506     {
5507       $de_ansi_files{$base} = (($directory eq '.' || $directory eq '')
5508                                ? ''
5509                                : "$directory/");
5510     }
5512     return $r;
5515 # Rewrite a single C++ source file.
5516 sub lang_cxx_rewrite
5518     return &lang_sub_obj;
5521 # Rewrite a single header file.
5522 sub lang_header_rewrite
5524     # Header files are simply ignored.
5525     return LANG_IGNORE;
5528 # Rewrite a single yacc file.
5529 sub lang_yacc_rewrite
5531     my ($directory, $base, $ext) = @_;
5533     my $r = &lang_sub_obj;
5534     (my $newext = $ext) =~ tr/y/c/;
5535     return ($r, $newext);
5538 # Rewrite a single yacc++ file.
5539 sub lang_yaccxx_rewrite
5541     my ($directory, $base, $ext) = @_;
5543     my $r = &lang_sub_obj;
5544     (my $newext = $ext) =~ tr/y/c/;
5545     return ($r, $newext);
5548 # Rewrite a single lex file.
5549 sub lang_lex_rewrite
5551     my ($directory, $base, $ext) = @_;
5553     my $r = &lang_sub_obj;
5554     (my $newext = $ext) =~ tr/l/c/;
5555     return ($r, $newext);
5558 # Rewrite a single lex++ file.
5559 sub lang_lexxx_rewrite
5561     my ($directory, $base, $ext) = @_;
5563     my $r = &lang_sub_obj;
5564     (my $newext = $ext) =~ tr/l/c/;
5565     return ($r, $newext);
5568 # Rewrite a single assembly file.
5569 sub lang_asm_rewrite
5571     return &lang_sub_obj;
5574 # Rewrite a single Fortran 77 file.
5575 sub lang_f77_rewrite
5577     return LANG_PROCESS;
5580 # Rewrite a single preprocessed Fortran 77 file.
5581 sub lang_ppf77_rewrite
5583     return LANG_PROCESS;
5586 # Rewrite a single ratfor file.
5587 sub lang_ratfor_rewrite
5589     return LANG_PROCESS;
5592 # Rewrite a single Objective C file.
5593 sub lang_objc_rewrite
5595     return &lang_sub_obj;
5598 # Rewrite a single Java file.
5599 sub lang_java_rewrite
5601     return LANG_SUBDIR;
5604 # The lang_X_finish functions are called after all source file
5605 # processing is done.  Each should handle defining rules for the
5606 # language, etc.  A finish function is only called if a source file of
5607 # the appropriate type has been seen.
5609 sub lang_c_finish
5611     # Push all libobjs files onto de_ansi_files.  We actually only
5612     # push files which exist in the current directory, and which are
5613     # genuine source files.
5614     foreach my $file (keys %libsources)
5615     {
5616         if ($file =~ /^(.*)\.[cly]$/ && -f "$relative_dir/$file")
5617         {
5618             $de_ansi_files{$1} = ''
5619         }
5620     }
5622     if (defined $options{'ansi2knr'} && keys %de_ansi_files)
5623     {
5624         # Make all _.c files depend on their corresponding .c files.
5625         my @objects;
5626         foreach my $base (sort keys %de_ansi_files)
5627         {
5628             # Each _.c file must depend on ansi2knr; otherwise it
5629             # might be used in a parallel build before it is built.
5630             # We need to support files in the srcdir and in the build
5631             # dir (because these files might be auto-generated.  But
5632             # we can't use $< -- some makes only define $< during a
5633             # suffix rule.
5634             my $ansfile = $de_ansi_files{$base} . $base . '.c';
5635             $output_rules .= ($base . "_.c: $ansfile \$(ANSI2KNR)\n\t"
5636                               . '$(CPP) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) '
5637                               . '`if test -f $(srcdir)/' . $ansfile
5638                               . '; then echo $(srcdir)/' . $ansfile
5639                               . '; else echo ' . $ansfile . '; fi` '
5640                               . "| sed 's/^# \\([0-9]\\)/#line \\1/' "
5641                               . '| $(ANSI2KNR) > $@'
5642                               # If ansi2knr fails then we shouldn't
5643                               # create the _.c file
5644                               . " || rm -f \$\@\n");
5645             push (@objects, $base . '_.$(OBJEXT)');
5646             push (@objects, $base . '_.lo')
5647               if variable_defined ('LIBTOOL');
5648         }
5650         # Make all _.o (and _.lo) files depend on ansi2knr.
5651         # Use a sneaky little hack to make it print nicely.
5652         &pretty_print_rule ('', '', @objects, ':', '$(ANSI2KNR)');
5653     }
5656 # This is a yacc helper which is called whenever we have decided to
5657 # compile a yacc file.
5658 sub lang_yacc_target_hook
5660     my ($self, $aggregate, $output, $input) = @_;
5662     my $flag = $aggregate . "_YFLAGS";
5663     if ((variable_defined ($flag)
5664          && &variable_value ($flag) =~ /$DASH_D_PATTERN/o)
5665         || (variable_defined ('YFLAGS')
5666             && &variable_value ('YFLAGS') =~ /$DASH_D_PATTERN/o))
5667     {
5668         (my $output_base = $output) =~ s/$KNOWN_EXTENSIONS_PATTERN$//;
5669         my $header = $output_base . '.h';
5671         # Found a `-d' that applies to the compilation of this file.
5672         # Add a dependency for the generated header file, and arrange
5673         # for that file to be included in the distribution.
5674         # FIXME: this fails for `nodist_*_SOURCES'.
5675         $output_rules .= ("${header}: $output\n"
5676                           # Recover from removal of $header
5677                           . "\t\@if test ! -f \$@; then \\\n"
5678                           . "\t  rm -f $output; \\\n"
5679                           . "\t  \$(MAKE) $output; \\\n"
5680                           . "\telse :; fi\n");
5681         &push_dist_common ($header);
5682         # If the files are built in the build directory, then we want
5683         # to remove them with `make clean'.  If they are in srcdir
5684         # they shouldn't be touched.  However, we can't determine this
5685         # statically, and the GNU rules say that yacc/lex output files
5686         # should be removed by maintainer-clean.  So that's what we
5687         # do.
5688         $clean_files{$header} = MAINTAINER_CLEAN;
5689     }
5690     # Erase $OUTPUT on `make maintainer-clean' (by GNU standards).
5691     # See the comment above for $HEADER.
5692     $clean_files{$output} = MAINTAINER_CLEAN;
5695 # This is a lex helper which is called whenever we have decided to
5696 # compile a lex file.
5697 sub lang_lex_target_hook
5699     my ($self, $aggregate, $output, $input) = @_;
5700     # If the files are built in the build directory, then we want to
5701     # remove them with `make clean'.  If they are in srcdir they
5702     # shouldn't be touched.  However, we can't determine this
5703     # statically, and the GNU rules say that yacc/lex output files
5704     # should be removed by maintainer-clean.  So that's what we do.
5705     $clean_files{$output} = MAINTAINER_CLEAN;
5708 # This is a helper for both lex and yacc.
5709 sub yacc_lex_finish_helper
5711     return if defined $language_scratch{'lex-yacc-done'};
5712     $language_scratch{'lex-yacc-done'} = 1;
5714     # If there is more than one distinct yacc (resp lex) source file
5715     # in a given directory, then the `ylwrap' program is required to
5716     # allow parallel builds to work correctly.  FIXME: for now, no
5717     # line number.
5718     require_conf_file ($configure_ac, FOREIGN, 'ylwrap');
5719     if ($config_aux_dir_set_in_configure_in)
5720     {
5721         &define_variable ('YLWRAP', $config_aux_dir . "/ylwrap");
5722     }
5723     else
5724     {
5725         &define_variable ('YLWRAP', '$(top_srcdir)/ylwrap');
5726     }
5729 sub lang_yacc_finish
5731   return if defined $language_scratch{'yacc-done'};
5732   $language_scratch{'yacc-done'} = 1;
5734   reject_var 'YACCFLAGS', "`YACCFLAGS' obsolete; use `YFLAGS' instead";
5736   &yacc_lex_finish_helper
5737     if count_files_for_language ('yacc') > 1;
5741 sub lang_lex_finish
5743   return if defined $language_scratch{'lex-done'};
5744   $language_scratch{'lex-done'} = 1;
5746   &yacc_lex_finish_helper
5747     if count_files_for_language ('lex') > 1;
5751 # Given a hash table of linker names, pick the name that has the most
5752 # precedence.  This is lame, but something has to have global
5753 # knowledge in order to eliminate the conflict.  Add more linkers as
5754 # required.
5755 sub resolve_linker
5757     my (%linkers) = @_;
5759     foreach my $l (qw(GCJLINK CXXLINK F77LINK OBJCLINK))
5760     {
5761         return $l if defined $linkers{$l};
5762     }
5763     return 'LINK';
5766 # Called to indicate that an extension was used.
5767 sub saw_extension
5769     my ($ext) = @_;
5770     if (! defined $extension_seen{$ext})
5771     {
5772         $extension_seen{$ext} = 1;
5773     }
5774     else
5775     {
5776         ++$extension_seen{$ext};
5777     }
5780 # Return the number of files seen for a given language.  Knows about
5781 # special cases we care about.  FIXME: this is hideous.  We need
5782 # something that involves real language objects.  For instance yacc
5783 # and yaccxx could both derive from a common yacc class which would
5784 # know about the strange ylwrap requirement.  (Or better yet we could
5785 # just not support legacy yacc!)
5786 sub count_files_for_language
5788     my ($name) = @_;
5790     my @names;
5791     if ($name eq 'yacc' || $name eq 'yaccxx')
5792     {
5793         @names = ('yacc', 'yaccxx');
5794     }
5795     elsif ($name eq 'lex' || $name eq 'lexxx')
5796     {
5797         @names = ('lex', 'lexxx');
5798     }
5799     else
5800     {
5801         @names = ($name);
5802     }
5804     my $r = 0;
5805     foreach $name (@names)
5806     {
5807         my $lang = $languages{$name};
5808         foreach my $ext (@{$lang->extensions})
5809         {
5810             $r += $extension_seen{$ext}
5811                 if defined $extension_seen{$ext};
5812         }
5813     }
5815     return $r
5818 # Called to ask whether source files have been seen . If HEADERS is 1,
5819 # headers can be included.
5820 sub saw_sources_p
5822     my ($headers) = @_;
5824     # count all the sources
5825     my $count = 0;
5826     foreach my $val (values %extension_seen)
5827     {
5828         $count += $val;
5829     }
5831     if (!$headers)
5832     {
5833         $count -= count_files_for_language ('header');
5834     }
5836     return $count > 0;
5840 # register_language (%ATTRIBUTE)
5841 # ------------------------------
5842 # Register a single language.
5843 # Each %ATTRIBUTE is of the form ATTRIBUTE => VALUE.
5844 sub register_language (%)
5846   my (%option) = @_;
5848   # Set the defaults.
5849   $option{'ansi'} = 0
5850     unless defined $option{'ansi'};
5851   $option{'autodep'} = 'no'
5852     unless defined $option{'autodep'};
5853   $option{'linker'} = ''
5854     unless defined $option{'linker'};
5855   $option{'flags'} = []
5856     unless defined $option{'flags'};
5857   $option{'output_extensions'} = sub { return ( '.$(OBJEXT)', '.lo' ) }
5858     unless defined $option{'output_extensions'};
5860   my $lang = new Language (%option);
5862   # Fill indexes.
5863   grep ($extension_map{$_} = $lang->name, @{$lang->extensions});
5864   $languages{$lang->name} = $lang;
5866   # Update the pattern of known extensions.
5867   accept_extensions (@{$lang->extensions});
5869   # Upate the $suffix_rule map.
5870   foreach my $suffix (@{$lang->extensions})
5871     {
5872       foreach my $dest (&{$lang->output_extensions} ($suffix))
5873         {
5874           &register_suffix_rule ('internal', $suffix, $dest);
5875         }
5876     }
5879 # derive_suffix ($EXT, $OBJ)
5880 # --------------------------
5881 # This function is used to find a path from a user-specified suffix $EXT
5882 # to $OBJ or to some other suffix we recognize internally, eg `cc'.
5883 sub derive_suffix ($$)
5885   my ($source_ext, $obj) = @_;
5887   while (! $extension_map{$source_ext}
5888          && $source_ext ne $obj
5889          && exists $suffix_rules->{$source_ext}
5890          && exists $suffix_rules->{$source_ext}{$obj})
5891     {
5892       $source_ext = $suffix_rules->{$source_ext}{$obj}[0];
5893     }
5895   return $source_ext;
5899 ################################################################
5901 # Pretty-print something.  HEAD is what should be printed at the
5902 # beginning of the first line, FILL is what should be printed at the
5903 # beginning of every subsequent line.
5904 sub pretty_print_internal
5906     my ($head, $fill, @values) = @_;
5908     my $column = length ($head);
5909     my $result = $head;
5911     # Fill length is number of characters.  However, each Tab
5912     # character counts for eight.  So we count the number of Tabs and
5913     # multiply by 7.
5914     my $fill_length = length ($fill);
5915     $fill_length += 7 * ($fill =~ tr/\t/\t/d);
5917     foreach (@values)
5918     {
5919         # "71" because we also print a space.
5920         if ($column + length ($_) > 71)
5921         {
5922             $result .= " \\\n" . $fill;
5923             $column = $fill_length;
5924         }
5925         $result .= ' ' if $result =~ /\S\z/;
5926         $result .= $_;
5927         $column += length ($_) + 1;
5928     }
5930     $result .= "\n";
5931     return $result;
5934 # Pretty-print something and append to output_vars.
5935 sub pretty_print
5937     $output_vars .= &pretty_print_internal (@_);
5940 # Pretty-print something and append to output_rules.
5941 sub pretty_print_rule
5943     $output_rules .= &pretty_print_internal (@_);
5947 ################################################################
5950 # $STRING
5951 # &conditional_string(@COND-STACK)
5952 # --------------------------------
5953 # Build a string which denotes the conditional in @COND-STACK.  Some
5954 # simplifications are done: `TRUE' entries are elided, and any `FALSE'
5955 # entry results in a return of `FALSE'.
5956 sub conditional_string
5958   my (@stack) = @_;
5960   if (grep (/^FALSE$/, @stack))
5961     {
5962       return 'FALSE';
5963     }
5964   else
5965     {
5966       return join (' ', uniq sort grep (!/^TRUE$/, @stack));
5967     }
5971 # $BOOLEAN
5972 # &conditional_true_when ($COND, $WHEN)
5973 # -------------------------------------
5974 # See if a conditional is true.  Both arguments are conditional
5975 # strings.  This returns true if the first conditional is true when
5976 # the second conditional is true.
5977 # For instance with $COND = `BAR FOO', and $WHEN = `BAR BAZ FOO',
5978 # obviously return 1, and 0 when, for instance, $WHEN = `FOO'.
5979 sub conditional_true_when ($$)
5981     my ($cond, $when) = @_;
5983     # Make a hash holding all the values from $WHEN.
5984     my %cond_vals = map { $_ => 1 } split (' ', $when);
5986     # Nothing is true when FALSE (not even FALSE itself, but it
5987     # shouldn't hurt if you decide to change that).
5988     return 0 if exists $cond_vals{'FALSE'};
5990     # Check each component of $cond, which looks `COND1 COND2'.
5991     foreach my $comp (split (' ', $cond))
5992     {
5993         # TRUE is always true.
5994         next if $comp eq 'TRUE';
5995         return 0 if ! defined $cond_vals{$comp};
5996     }
5998     return 1;
6002 # $BOOLEAN
6003 # &conditional_is_redundant ($COND, @WHENS)
6004 # ----------------------------------------
6005 # Determine whether $COND is redundant with respect to @WHENS.
6007 # Returns true if $COND is true for any of the conditions in @WHENS.
6009 # If there are no @WHENS, then behave as if @WHENS contained a single empty
6010 # condition.
6011 sub conditional_is_redundant ($@)
6013     my ($cond, @whens) = @_;
6015     @whens = ("") if @whens == 0;
6017     foreach my $when (@whens)
6018     {
6019         return 1 if conditional_true_when ($cond, $when);
6020     }
6021     return 0;
6025 # $BOOLEAN
6026 # &conditional_implies_any ($COND, @CONDS)
6027 # ----------------------------------------
6028 # Returns true iff $COND implies any of the conditions in @CONDS.
6029 sub conditional_implies_any ($@)
6031     my ($cond, @conds) = @_;
6033     @conds = ("") if @conds == 0;
6035     foreach my $c (@conds)
6036     {
6037         return 1 if conditional_true_when ($c, $cond);
6038     }
6039     return 0;
6043 # $NEGATION
6044 # condition_negate ($COND)
6045 # ------------------------
6046 sub condition_negate ($)
6048     my ($cond) = @_;
6050     $cond =~ s/TRUE$/TRUEO/;
6051     $cond =~ s/FALSE$/TRUE/;
6052     $cond =~ s/TRUEO$/FALSE/;
6054     return $cond;
6058 # Compare condition names.
6059 # Issue them in alphabetical order, foo_TRUE before foo_FALSE.
6060 sub by_condition
6062     # Be careful we might be comparing `' or `#'.
6063     $a =~ /^(.*)_(TRUE|FALSE)$/;
6064     my ($aname, $abool) = ($1 || '', $2 || '');
6065     $b =~ /^(.*)_(TRUE|FALSE)$/;
6066     my ($bname, $bbool) = ($1 || '', $2 || '');
6067     return ($aname cmp $bname
6068             # Don't bother with IFs, given that TRUE is after FALSE
6069             # just cmp in the reverse order.
6070             || $bbool cmp $abool
6071             # Just in case...
6072             || $a cmp $b);
6076 # &make_condition (@CONDITIONS)
6077 # -----------------------------
6078 # Transform a list of conditions (themselves can be an internal list
6079 # of conditions, e.g., @CONDITIONS = ('cond1 cond2', 'cond3')) into a
6080 # Make conditional (a pattern for AC_SUBST).
6081 # Correctly returns the empty string when there are no conditions.
6082 sub make_condition
6084     my $res = conditional_string (@_);
6086     # There are no conditions.
6087     if ($res eq '')
6088       {
6089         # Nothing to do.
6090       }
6091     # It's impossible.
6092     elsif ($res eq 'FALSE')
6093       {
6094         $res = '#';
6095       }
6096     # Build it.
6097     else
6098       {
6099         $res = '@' . $res . '@';
6100         $res =~ s/ /@@/g;
6101       }
6103     return $res;
6108 ## ------------------------------ ##
6109 ## Handling the condition stack.  ##
6110 ## ------------------------------ ##
6113 # $COND_STRING
6114 # cond_stack_if ($NEGATE, $COND, $WHERE)
6115 # --------------------------------------
6116 sub cond_stack_if ($$$)
6118   my ($negate, $cond, $where) = @_;
6120   error $where, "$cond does not appear in AM_CONDITIONAL"
6121     if ! $configure_cond{$cond} && $cond !~ /^TRUE|FALSE$/;
6123   $cond = "${cond}_TRUE"
6124     unless $cond =~ /^TRUE|FALSE$/;
6125   $cond = condition_negate ($cond)
6126     if $negate;
6128   push (@cond_stack, $cond);
6130   return conditional_string (@cond_stack);
6134 # $COND_STRING
6135 # cond_stack_else ($NEGATE, $COND, $WHERE)
6136 # ----------------------------------------
6137 sub cond_stack_else ($$$)
6139   my ($negate, $cond, $where) = @_;
6141   if (! @cond_stack)
6142     {
6143       error $where, "else without if";
6144       return;
6145     }
6147   $cond_stack[$#cond_stack] = condition_negate ($cond_stack[$#cond_stack]);
6149   # If $COND is given, check against it.
6150   if (defined $cond)
6151     {
6152       $cond = "${cond}_TRUE"
6153         unless $cond =~ /^TRUE|FALSE$/;
6154       $cond = condition_negate ($cond)
6155         if $negate;
6157       error ($where, "else reminder ($negate$cond) incompatible with "
6158              . "current conditional: $cond_stack[$#cond_stack]")
6159         if $cond_stack[$#cond_stack] ne $cond;
6160     }
6162   return conditional_string (@cond_stack);
6166 # $COND_STRING
6167 # cond_stack_endif ($NEGATE, $COND, $WHERE)
6168 # -----------------------------------------
6169 sub cond_stack_endif ($$$)
6171   my ($negate, $cond, $where) = @_;
6172   my $old_cond;
6174   if (! @cond_stack)
6175     {
6176       error $where, "endif without if: $negate$cond";
6177       return;
6178     }
6181   # If $COND is given, check against it.
6182   if (defined $cond)
6183     {
6184       $cond = "${cond}_TRUE"
6185         unless $cond =~ /^TRUE|FALSE$/;
6186       $cond = condition_negate ($cond)
6187         if $negate;
6189       error ($where, "endif reminder ($negate$cond) incompatible with "
6190              . "current conditional: $cond_stack[$#cond_stack]")
6191         if $cond_stack[$#cond_stack] ne $cond;
6192     }
6194   pop @cond_stack;
6196   return conditional_string (@cond_stack);
6203 ## ------------------------ ##
6204 ## Handling the variables.  ##
6205 ## ------------------------ ##
6208 # check_ambiguous_conditional ($VAR, $COND, $WHERE)
6209 # -------------------------------------------------
6210 # Check for an ambiguous conditional.  This is called when a variable
6211 # is being defined conditionally.  If we already know about a
6212 # definition that is true under the same conditions, then we have an
6213 # ambiguity.
6214 sub check_ambiguous_conditional ($$$)
6216   my ($var, $cond, $where) = @_;
6217   my ($message, $ambig_cond) =
6218     conditional_ambiguous_p ($var, $cond, keys %{$var_value{$var}});
6219   if ($message)
6220     {
6221       msg 'syntax', $where, "$message ...";
6222       msg_var ('syntax', $var, "... `$var' previously defined here.");
6223       verb (macro_dump ($var));
6224     }
6227 # $STRING, $AMBIG_COND
6228 # conditional_ambiguous_p ($WHAT, $COND, @CONDS)
6229 # ----------------------------------------------
6230 # Check for an ambiguous conditional.  Return an error message and
6231 # the other condition involved if we have one, two empty strings otherwise.
6232 #   WHAT:  the thing being defined
6233 #   COND:  the condition under which is is being defined
6234 #   CONDS: the conditons under which is had already been defined
6235 sub conditional_ambiguous_p ($$@)
6237   my ($var, $cond, @conds) = @_;
6238   foreach my $vcond (@conds)
6239     {
6240       # Note that these rules doesn't consider the following
6241       # example as ambiguous.
6242       #
6243       #   if COND1
6244       #     FOO = foo
6245       #   endif
6246       #   if COND2
6247       #     FOO = bar
6248       #   endif
6249       #
6250       # It's up to the user to not define COND1 and COND2
6251       # simultaneously.
6252       my $message;
6253       if ($vcond eq $cond)
6254         {
6255           return ("$var multiply defined in condition $cond", $vcond);
6256         }
6257       elsif (&conditional_true_when ($vcond, $cond))
6258         {
6259           return ("$var was already defined in condition $vcond, "
6260                   . "which implies condition $cond", $vcond);
6261         }
6262       elsif (&conditional_true_when ($cond, $vcond))
6263         {
6264           return ("$var was already defined in condition $vcond, "
6265                    . "which is implied by condition $cond", $vcond);
6266         }
6267     }
6268   return ('', '');
6271 # @MISSING_CONDS
6272 # variable_not_always_defined_in_cond ($VAR, $COND)
6273 # ---------------------------------------------
6274 # Check whether $VAR is always defined for condition $COND.
6275 # Return a list of conditions where the definition is missing.
6277 # For instance, given
6279 #   if COND1
6280 #     if COND2
6281 #       A = foo
6282 #       D = d1
6283 #     else
6284 #       A = bar
6285 #       D = d2
6286 #     endif
6287 #   else
6288 #     D = d3
6289 #   endif
6290 #   if COND3
6291 #     A = baz
6292 #     B = mumble
6293 #   endif
6294 #   C = mumble
6296 # we should have:
6297 #   variable_not_always_defined_in_cond ('A', 'COND1_TRUE COND2_TRUE')
6298 #     => ()
6299 #   variable_not_always_defined_in_cond ('A', 'COND1_TRUE')
6300 #     => ()
6301 #   variable_not_always_defined_in_cond ('A', 'TRUE')
6302 #     => ("COND1_FALSE COND2_FALSE COND3_FALSE",
6303 #         "COND1_FALSE COND2_TRUE COND3_FALSE",
6304 #         "COND1_TRUE COND2_FALSE COND3_FALSE",
6305 #         "COND1_TRUE COND2_TRUE COND3_FALSE")
6306 #   variable_not_always_defined_in_cond ('B', 'COND1_TRUE')
6307 #     => ("COND3_FALSE")
6308 #   variable_not_always_defined_in_cond ('C', 'COND1_TRUE')
6309 #     => ()
6310 #   variable_not_always_defined_in_cond ('D', 'TRUE')
6311 #     => ()
6312 #   variable_not_always_defined_in_cond ('Z', 'TRUE')
6313 #     => ("TRUE")
6315 sub variable_not_always_defined_in_cond ($$)
6317   my ($var, $cond) = @_;
6319   # It's easy to answer if the variable is not defined.
6320   return ("TRUE",) unless exists $var_value{$var};
6322   # How does it work?  Let's take the second example:
6323   #
6324   #   variable_not_always_defined_in_cond ('A', 'COND1_TRUE')
6325   #
6326   # (1) First, we get the list of conditions where A is defined:
6327   #
6328   #   ("COND1_TRUE COND2_TRUE", "COND1_TRUE COND2_FALSE", "COND3_TRUE")
6329   #
6330   # (2) Then we generate the set of inverted conditions:
6331   #
6332   #   ("COND1_FALSE COND2_TRUE COND3_FALSE",
6333   #    "COND1_FALSE COND2_FALSE COND3_FALSE")
6334   #
6335   # (3) Finally we remove these conditions which are not implied by
6336   #     COND1_TRUE.  This yields an empty list and we are done.
6338   my @res = ();
6339   my @cond_defs = keys %{$var_value{$var}}; # (1)
6340   foreach my $icond (invert_conditions (@cond_defs)) # (2)
6341     {
6342       prog_error "invert_conditions returned an input condition"
6343         if exists $var_value{$var}{$icond};
6345       push @res, $icond
6346         if (conditional_true_when ($cond, $icond)); # (3)
6347     }
6348   return @res;
6351 # &macro_define($VAR, $OWNER, $TYPE, $COND, $VALUE, $WHERE)
6352 # -------------------------------------------------------------
6353 # The $VAR can go from Automake to user, but not the converse.
6354 sub macro_define ($$$$$$)
6356   my ($var, $owner, $type, $cond, $value, $where) = @_;
6358   # We will adjust the owener of this variable unless told otherwise.
6359   my $adjust_owner = 1;
6361   error $where, "bad characters in variable name `$var'"
6362     if $var !~ /$MACRO_PATTERN/o;
6364   # NEWS-OS 4.2R complains if a Makefile variable begins with `_'.
6365   msg ('portability', $where,
6366        "$var: variable names starting with `_' are not portable")
6367     if $var =~ /^_/;
6369   # `:='-style assignments are not acknowledged by POSIX.  Moreover it
6370   # has multiple meanings.  In GNU make or BSD make it means "assign
6371   # with immediate expansion", while in OSF make it is used for
6372   # conditional assignments.
6373   msg ('portability', $where, "`:='-style assignments are not portable")
6374     if $type eq ':';
6376   check_variable_expansions ($value, $where);
6378   $cond ||= 'TRUE';
6380   # An Automake variable must be consistently defined with the same
6381   # sign by Automake.  A user variable must be set by either `=' or
6382   # `:=', and later promoted to `+='.
6383   if ($owner == VAR_AUTOMAKE)
6384     {
6385       if (exists $var_type{$var}
6386           && exists $var_type{$var}{$cond}
6387           && $var_type{$var}{$cond} ne $type)
6388         {
6389           error ($where, "$var was set with `$var_type{$var}=' "
6390                  . "and is now set with `$type='");
6391         }
6392     }
6393   else
6394     {
6395       if (!exists $var_type{$var} && $type eq '+')
6396         {
6397           error $where, "$var must be set with `=' before using `+='";
6398         }
6399     }
6400   $var_type{$var}{$cond} = $type;
6402   # Differentiate assignment types.
6404   # 1. append (+=) to a variable defined for current condition
6405   if ($type eq '+' && exists $var_value{$var}{$cond})
6406     {
6407       if (chomp $var_value{$var}{$cond})
6408         {
6409           # Insert a backslash before a trailing newline.
6410           $var_value{$var}{$cond} .= "\\\n";
6411         }
6412       elsif ($var_value{$var}{$cond})
6413         {
6414           # Insert a separator.
6415           $var_value{$var}{$cond} .= ' ';
6416         }
6417        $var_value{$var}{$cond} .= $value;
6418     }
6419   # 2. append (+=) to a variable defined for *another* condition
6420   elsif ($type eq '+' && keys %{$var_value{$var}})
6421     {
6422       # * Generally, $cond is not TRUE.  For instance:
6423       #     FOO = foo
6424       #     if COND
6425       #       FOO += bar
6426       #     endif
6427       #   In this case, we declare an helper variable conditionally,
6428       #   and append it to FOO:
6429       #     FOO = foo $(am__append_1)
6430       #     @COND_TRUE@am__append_1 = bar
6431       #   Of course if FOO is defined under several conditions, we add
6432       #   $(am__append_1) to each definitions.
6433       #
6434       # * If $cond is TRUE, we don't need the helper variable.  E.g., in
6435       #     if COND1
6436       #       FOO = foo1
6437       #     else
6438       #       FOO = foo2
6439       #     endif
6440       #     FOO += bar
6441       #   we can add bar directly to all definition of FOO, and output
6442       #     @COND_TRUE@FOO = foo1 bar
6443       #     @COND_FALSE@FOO = foo2 bar
6445       # Do we need an helper variable?
6446       if ($cond ne 'TRUE')
6447         {
6448             # Does the helper variable already exists?
6449             my $key = "$var:$cond";
6450             if (exists $appendvar{$key})
6451               {
6452                 # Yes, let's simply append to it.
6453                 $var = $appendvar{$key};
6454                 $owner = VAR_AUTOMAKE;
6455               }
6456             else
6457               {
6458                 # No, create it.
6459                 my $num = 1 + keys (%appendvar);
6460                 my $hvar = "am__append_$num";
6461                 $appendvar{$key} = $hvar;
6462                 &macro_define ($hvar, VAR_AUTOMAKE, '+',
6463                                $cond, $value, $where);
6464                 push @var_list, $hvar;
6465                 # Now HVAR is to be added to VAR.
6466                 $value = "\$($hvar)";
6467               }
6468         }
6470       # Add VALUE to all definitions of VAR.
6471       foreach my $vcond (keys %{$var_value{$var}})
6472         {
6473           # We have a bit of error detection to do here.
6474           # This:
6475           #   if COND1
6476           #     X = Y
6477           #   endif
6478           #   X += Z
6479           # should be rejected because X is not defined for all conditions
6480           # where `+=' applies.
6481           my @undef_cond = variable_not_always_defined_in_cond $var, $cond;
6482           if (@undef_cond != 0)
6483             {
6484               error ($where,
6485                      "Cannot apply `+=' because `$var' is not defined "
6486                      . "in\nthe following conditions:\n  "
6487                      . join ("\n  ", @undef_cond)
6488                      . "\nEither define `$var' in these conditions,"
6489                      . " or use\n`+=' in the same conditions as"
6490                      . " the definitions.");
6491             }
6492           else
6493             {
6494               &macro_define ($var, $owner, '+', $vcond, $value, $where);
6495             }
6496         }
6497       # Don't adjust the owner.  The above &macro_define did it in the
6498       # right conditions.
6499       $adjust_owner = 0;
6500     }
6501   # 3. first assignment (=, :=, or +=)
6502   else
6503     {
6504       # If Automake tries to override a value specified by the user,
6505       # just don't let it do.
6506       if (exists $var_value{$var}{$cond}
6507           && $var_owner{$var}{$cond} != VAR_AUTOMAKE
6508           && $owner == VAR_AUTOMAKE)
6509         {
6510           verb ("refusing to override the user definition of:\n"
6511                 . macro_dump ($var)
6512                 ."with `$cond' => `$value'");
6513         }
6514       else
6515         {
6516           # There must be no previous value unless the user is redefining
6517           # an Automake variable or an AC_SUBST variable for an existing
6518           # condition.
6519           check_ambiguous_conditional ($var, $cond, $where)
6520             unless (exists $var_owner{$var}{$cond}
6521                     && (($var_owner{$var}{$cond} == VAR_AUTOMAKE
6522                          && $owner != VAR_AUTOMAKE)
6523                         || $var_owner{$var}{$cond} == VAR_CONFIGURE));
6525           $var_value{$var}{$cond} = $value;
6526           # Assignments to a macro set its location.  We don't adjust
6527           # locations for `+='.  Ideally I suppose we would associate
6528           # line numbers with random bits of text.
6529           $var_location{$var}{$cond} = $where;
6530         }
6531     }
6533   # The owner of a variable can only increase, because an Automake
6534   # variable can be given to the user, but not the converse.
6535   if ($adjust_owner &&
6536       (! exists $var_owner{$var}{$cond}
6537        || $owner > $var_owner{$var}{$cond}))
6538     {
6539       $var_owner{$var}{$cond} = $owner;
6540       # Always adjust the location when the owner changes (even for
6541       # `+=' statements).  The risk otherwise is to warn about
6542       # a VAR_MAKEFILE variable and locate it in configure.ac...
6543       $var_location{$var}{$cond} = $where;
6544     }
6546   # Call var_VAR_trigger if it's defined.
6547   # This hook helps to update some internal state *while*
6548   # parsing the file.  For instance the handling of SUFFIXES
6549   # requires this (see var_SUFFIXES_trigger).
6550   my $var_trigger = "var_${var}_trigger";
6551   &$var_trigger($type, $value) if defined &$var_trigger;
6555 # &macro_delete ($VAR, [@CONDS])
6556 # ------------------------------
6557 # Forget about $VAR under the conditions @CONDS, or completely if
6558 # @CONDS is empty.
6559 sub macro_delete ($@)
6561   my ($var, @conds) = @_;
6563   if (!@conds)
6564     {
6565       delete $var_value{$var};
6566       delete $var_location{$var};
6567       delete $var_owner{$var};
6568       delete $var_comment{$var};
6569       delete $var_type{$var};
6570     }
6571   else
6572     {
6573       foreach my $cond (@conds)
6574         {
6575           delete $var_value{$var}{$cond};
6576           delete $var_location{$var}{$cond};
6577           delete $var_owner{$var}{$cond};
6578           delete $var_comment{$var}{$cond};
6579           delete $var_type{$var}{$cond};
6580         }
6581     }
6585 # &macro_dump ($VAR)
6586 # ------------------
6587 sub macro_dump ($)
6589   my ($var) = @_;
6590   my $text = '';
6592   if (!exists $var_value{$var})
6593     {
6594       $text = "  $var does not exist\n";
6595     }
6596   else
6597     {
6598       $text .= "  $var $var_type{$var}=\n  {\n";
6599       foreach my $vcond (sort by_condition keys %{$var_value{$var}})
6600         {
6601           prog_error ("`$var' is a key in \$var_value, "
6602                       . "but not in \$var_owner\n")
6603             unless exists $var_owner{$var}{$vcond};
6605           my $var_owner;
6606           if ($var_owner{$var}{$vcond} == VAR_AUTOMAKE)
6607             {
6608               $var_owner = 'Automake';
6609             }
6610           elsif ($var_owner{$var}{$vcond} == VAR_CONFIGURE)
6611             {
6612               $var_owner = 'Configure';
6613             }
6614           elsif ($var_owner{$var}{$vcond} == VAR_MAKEFILE)
6615             {
6616               $var_owner = 'Makefile';
6617             }
6618           else
6619             {
6620               prog_error ("unexpected value for `\$var_owner{$var}{$vcond}': "
6621                           . $var_owner{$var}{$vcond})
6622                 unless defined $var_owner;
6623             }
6625           my $where = (defined $var_location{$var}{$vcond}
6626                        ? $var_location{$var}{$vcond} : "undefined");
6627           $text .= "$var_comment{$var}{$vcond}"
6628             if exists $var_comment{$var}{$vcond};
6629           $text .= "    $vcond => $var_value{$var}{$vcond}\n";
6630         }
6631       $text .= "  }\n";
6632     }
6633   return $text;
6637 # &macros_dump ()
6638 # ---------------
6639 sub macros_dump ()
6641   my ($var) = @_;
6643   my $text = "%var_value =\n{\n";
6644   foreach my $var (sort (keys %var_value))
6645     {
6646       $text .= macro_dump ($var);
6647     }
6648   $text .= "}\n";
6649   return $text;
6653 # $BOOLEAN
6654 # variable_defined ($VAR, [$COND])
6655 # ---------------------------------
6656 # See if a variable exists.  $VAR is the variable name, and $COND is
6657 # the condition which we should check.  If no condition is given, we
6658 # currently return true if the variable is defined under any
6659 # condition.
6660 sub variable_defined ($;$)
6662     my ($var, $cond) = @_;
6664     if (! exists $var_value{$var}
6665         || (defined $cond && ! exists $var_value{$var}{$cond}))
6666       {
6667         # VAR is not defined.
6669         # Check there is no target defined with the name of the
6670         # variable we check.
6672         # adl> I'm wondering if this error still makes any sense today. I
6673         # adl> guess it was because targets and variables used to share
6674         # adl> the same namespace in older versions of Automake?
6675         # tom> While what you say is definitely part of it, I think it
6676         # tom> might also have been due to someone making a "spelling error"
6677         # tom> -- writing "foo:..." instead of "foo = ...".
6678         # tom> I'm not sure whether it is really worth diagnosing
6679         # tom> this sort of problem.  In the old days I used to add warnings
6680         # tom> and errors like this pretty randomly, based on bug reports I
6681         # tom> got.  But there's a plausible argument that I was trying
6682         # tom> too hard to prevent people from making mistakes.
6683         if (exists $targets{$var}
6684             && (! defined $cond || exists $targets{$var}{$cond}))
6685           {
6686             for my $tcond ($cond || keys %{$targets{$var}})
6687               {
6688                 prog_error ("\$targets{$var}{$tcond} exists but "
6689                             . "\$target_owner doesn't")
6690                   unless exists $target_owner{$var}{$tcond};
6691                 # Diagnose the first user target encountered, if any.
6692                 # Restricting this test to user targets allows Automake
6693                 # to create rules for things like `bin_PROGRAMS = LDADD'.
6694                 if ($target_owner{$var}{$tcond} == TARGET_USER)
6695                   {
6696                     msg_cond_target ('syntax', $tcond, $var,
6697                                      "`$var' is a target; "
6698                                      . "expected a variable");
6699                     return 0;
6700                   }
6701               }
6702           }
6703         return 0;
6704       }
6706     # Even a var_value examination is good enough for us.  FIXME:
6707     # really should maintain examined status on a per-condition basis.
6708     $content_seen{$var} = 1;
6709     return 1;
6713 # $BOOLEAN
6714 # variable_assert ($VAR, $WHERE)
6715 # ------------------------------
6716 # Make sure a variable exists.  $VAR is the variable name, and $WHERE
6717 # is the name of a macro which refers to $VAR.
6718 sub variable_assert ($$)
6720   my ($var, $where) = @_;
6722   return 1
6723     if variable_defined $var;
6725   require_variables ($where, "variable `$var' is used", 'TRUE', $var);
6727   return 0;
6730 # Mark a variable as examined.
6731 sub examine_variable
6733   my ($var) = @_;
6734   variable_defined ($var);
6738 # &variable_conditions_recursive ($VAR)
6739 # -------------------------------------
6740 # Return the set of conditions for which a variable is defined.
6742 # If the variable is not defined conditionally, and is not defined in
6743 # terms of any variables which are defined conditionally, then this
6744 # returns the empty list.
6746 # If the variable is defined conditionally, but is not defined in
6747 # terms of any variables which are defined conditionally, then this
6748 # returns the list of conditions for which the variable is defined.
6750 # If the variable is defined in terms of any variables which are
6751 # defined conditionally, then this returns a full set of permutations
6752 # of the subvariable conditions.  For example, if the variable is
6753 # defined in terms of a variable which is defined for COND_TRUE,
6754 # then this returns both COND_TRUE and COND_FALSE.  This is
6755 # because we will need to define the variable under both conditions.
6756 sub variable_conditions_recursive ($)
6758     my ($var) = @_;
6760     %vars_scanned = ();
6762     my @new_conds = variable_conditions_recursive_sub ($var, '');
6764     # Now we want to return all permutations of the subvariable
6765     # conditions.
6766     my %allconds = ();
6767     foreach my $item (@new_conds)
6768     {
6769         foreach (split (' ', $item))
6770         {
6771             s/^(.*)_(TRUE|FALSE)$/$1_TRUE/;
6772             $allconds{$_} = 1;
6773         }
6774     }
6775     @new_conds = variable_conditions_permutations (sort keys %allconds);
6777     my %uniqify;
6778     foreach my $cond (@new_conds)
6779     {
6780         my $reduce = variable_conditions_reduce (split (' ', $cond));
6781         next
6782             if $reduce eq 'FALSE';
6783         $uniqify{$cond} = 1;
6784     }
6786     # Note we cannot just do `return sort keys %uniqify', because this
6787     # function is sometimes used in a scalar context.
6788     my @uniq_list = sort by_condition keys %uniqify;
6789     return @uniq_list;
6793 # @CONDS
6794 # variable_conditions ($VAR)
6795 # --------------------------
6796 # Get the list of conditions that a variable is defined with, without
6797 # recursing through the conditions of any subvariables.
6798 # Argument is $VAR: the variable to get the conditions of.
6799 # Returns the list of conditions.
6800 sub variable_conditions ($)
6802     my ($var) = @_;
6803     my @conds = keys %{$var_value{$var}};
6804     return sort by_condition @conds;
6808 # $BOOLEAN
6809 # &variable_conditionally_defined ($VAR)
6810 # --------------------------------------
6811 sub variable_conditionally_defined ($)
6813     my ($var) = @_;
6814     foreach my $cond (variable_conditions_recursive ($var))
6815       {
6816         return 1
6817           unless $cond =~ /^TRUE|FALSE$/;
6818       }
6819     return 0;
6822 # @LIST
6823 # &scan_variable_expansions ($TEXT)
6824 # ---------------------------------
6825 # Return the list of variable names expanded in $TEXT.
6826 # Note that unlike some other functions, $TEXT is not split
6827 # on spaces before we check for subvariables.
6828 sub scan_variable_expansions ($)
6830   my ($text) = @_;
6831   my @result = ();
6833   # Strip comments.
6834   $text =~ s/#.*$//;
6836   # Record each use of ${stuff} or $(stuff) that do not follow a $.
6837   while ($text =~ /(?<!\$)\$(?:\{([^\}]*)\}|\(([^\)]*)\))/g)
6838     {
6839       my $var = $1 || $2;
6840       # The occurent may look like $(string1[:subst1=[subst2]]) but
6841       # we want only `string1'.
6842       $var =~ s/:[^:=]*=[^=]*$//;
6843       push @result, $var;
6844     }
6846   return @result;
6849 # &check_variable_expansions ($TEXT, $WHERE)
6850 # ------------------------------------------
6851 # Check variable expansions in $TEXT and warn about any name that
6852 # does not conform to POSIX.  $WHERE is the location of $TEXT for
6853 # the error message.
6854 sub check_variable_expansions ($$)
6856   my ($text, $where) = @_;
6857   # Catch expansion of variables whose name does not conform to POSIX.
6858   foreach my $var (scan_variable_expansions ($text))
6859     {
6860       if ($var !~ /$MACRO_PATTERN/)
6861         {
6862           # If the variable name contains a space, it's likely
6863           # to be a GNU make extension (such as $(addsuffix ...)).
6864           # Mention this in the diagnostic.
6865           my $gnuext = "";
6866           $gnuext = "\n(probably a GNU make extension)" if $var =~ / /;
6867           msg ('portability', $where,
6868                "$var: non-POSIX variable name$gnuext");
6869         }
6870     }
6873 # &variable_conditions_recursive_sub ($VAR, $PARENT)
6874 # -------------------------------------------------------
6875 # A subroutine of variable_conditions_recursive.  This returns all the
6876 # conditions of $VAR, including those of any sub-variables.
6877 sub variable_conditions_recursive_sub
6879     my ($var, $parent) = @_;
6880     my @new_conds = ();
6882     if (defined $vars_scanned{$var})
6883     {
6884         err_var $parent, "variable `$var' recursively defined";
6885         return ();
6886     }
6887     $vars_scanned{$var} = 1;
6889     my @this_conds = ();
6890     # Examine every condition under which $VAR is defined.
6891     foreach my $vcond (keys %{$var_value{$var}})
6892     {
6893       push (@this_conds, $vcond);
6895       # If $VAR references some other variable, then compute the
6896       # conditions for that subvariable.
6897       my @subvar_conds = ();
6898       foreach my $varname (scan_variable_expansions $var_value{$var}{$vcond})
6899         {
6900           if ($varname =~ /$SUBST_REF_PATTERN/o)
6901             {
6902               $varname = $1;
6903             }
6905           # Here we compute all the conditions under which the
6906           # subvariable is defined.  Then we go through and add
6907           # $VCOND to each.
6908           my @svc = variable_conditions_recursive_sub ($varname, $var);
6909           foreach my $item (@svc)
6910             {
6911               my $val = conditional_string ($vcond, split (' ', $item));
6912               $val ||= 'TRUE';
6913               push (@subvar_conds, $val);
6914             }
6915         }
6917       # If there are no conditional subvariables, then we want to
6918       # return this condition.  Otherwise, we want to return the
6919       # permutations of the subvariables, taking into account the
6920       # conditions of $VAR.
6921       if (! @subvar_conds)
6922         {
6923           push (@new_conds, $vcond);
6924         }
6925       else
6926         {
6927           push (@new_conds, variable_conditions_reduce (@subvar_conds));
6928         }
6929     }
6931     # Unset our entry in vars_scanned.  We only care about recursive
6932     # definitions.
6933     delete $vars_scanned{$var};
6935     # If we are being called on behalf of another variable, we need to
6936     # return all possible permutations of the conditions.  We have
6937     # already handled everything in @this_conds along with their
6938     # subvariables.  We now need to add any permutations that are not
6939     # in @this_conds.
6940     foreach my $this_cond (@this_conds)
6941     {
6942         my @perms =
6943             variable_conditions_permutations (split (' ', $this_cond));
6944         foreach my $perm (@perms)
6945         {
6946             my $ok = 1;
6947             foreach my $scan (@this_conds)
6948             {
6949                 if (&conditional_true_when ($perm, $scan)
6950                     || &conditional_true_when ($scan, $perm))
6951                 {
6952                     $ok = 0;
6953                     last;
6954                 }
6955             }
6956             next if ! $ok;
6958             # This permutation was not already handled, and is valid
6959             # for the parents.
6960             push (@new_conds, $perm);
6961         }
6962     }
6964     return @new_conds;
6968 # Filter a list of conditionals so that only the exclusive ones are
6969 # retained.  For example, if both `COND1_TRUE COND2_TRUE' and
6970 # `COND1_TRUE' are in the list, discard the latter.
6971 # If the list is empty, return TRUE
6972 sub variable_conditions_reduce
6974     my (@conds) = @_;
6975     my @ret = ();
6976     my $cond;
6977     while(@conds > 0)
6978     {
6979         $cond = shift(@conds);
6981         # FALSE is absorbent.
6982         return 'FALSE'
6983           if $cond eq 'FALSE';
6985         if (!conditional_is_redundant ($cond, @ret, @conds))
6986           {
6987             push (@ret, $cond);
6988           }
6989     }
6991     return "TRUE" if @ret == 0;
6992     return @ret;
6995 # @CONDS
6996 # invert_conditions (@CONDS)
6997 # --------------------------
6998 # Invert a list of conditionals.  Returns a set of conditionals which
6999 # are never true for any of the input conditionals, and when taken
7000 # together with the input conditionals cover all possible cases.
7002 # For example:
7003 #   invert_conditions("A_TRUE B_TRUE", "A_FALSE B_FALSE")
7004 #     => ("A_FALSE B_TRUE", "A_TRUE B_FALSE")
7006 #   invert_conditions("A_TRUE B_TRUE", "A_TRUE B_FALSE", "A_FALSE")
7007 #     => ()
7008 sub invert_conditions
7010     my (@conds) = @_;
7012     my @notconds = ();
7014     # Generate all permutation for all inputs.
7015     my @perm =
7016         map { variable_conditions_permutations (split(' ', $_)); } @conds;
7017     # Remove redundant conditions.
7018     @perm = variable_conditions_reduce @perm;
7020     # Now remove all conditions which imply one of the input conditions.
7021     foreach my $perm (@perm)
7022     {
7023         push @notconds, $perm
7024             if ! conditional_implies_any ($perm, @conds);
7025     }
7026     return @notconds;
7029 # Return a list of permutations of a conditional string.
7030 # (But never output FALSE conditions, they are useless.)
7032 # Examples:
7033 #   variable_conditions_permutations ("FOO_FALSE", "BAR_TRUE")
7034 #     => ("FOO_FALSE BAR_FALSE",
7035 #         "FOO_FALSE BAR_TRUE",
7036 #         "FOO_TRUE BAR_FALSE",
7037 #         "FOO_TRUE BAR_TRUE")
7038 #   variable_conditions_permutations ("FOO_FALSE", "TRUE")
7039 #     => ("FOO_FALSE TRUE",
7040 #         "FOO_TRUE TRUE")
7041 #   variable_conditions_permutations ("TRUE")
7042 #     => ("TRUE")
7043 #   variable_conditions_permutations ("FALSE")
7044 #     => ("TRUE")
7045 sub variable_conditions_permutations
7047     my (@comps) = @_;
7048     return ()
7049         if ! @comps;
7050     my $comp = shift (@comps);
7051     return variable_conditions_permutations (@comps)
7052         if $comp eq '';
7053     my $neg = condition_negate ($comp);
7055     my @ret;
7056     foreach my $sub (variable_conditions_permutations (@comps))
7057     {
7058         push (@ret, "$comp $sub") if $comp ne 'FALSE';
7059         push (@ret, "$neg $sub") if $neg ne 'FALSE';
7060     }
7061     if (! @ret)
7062     {
7063         push (@ret, $comp) if $comp ne 'FALSE';
7064         push (@ret, $neg) if $neg ne 'FALSE';
7065     }
7066     return @ret;
7070 # $BOOL
7071 # &check_variable_defined_unconditionally($VAR, $PARENT)
7072 # ------------------------------------------------------
7073 # Warn if a variable is conditionally defined.  This is called if we
7074 # are using the value of a variable.
7075 sub check_variable_defined_unconditionally ($$)
7077   my ($var, $parent) = @_;
7078   foreach my $cond (keys %{$var_value{$var}})
7079     {
7080       next
7081         if $cond =~ /^TRUE|FALSE$/;
7083       if ($parent)
7084         {
7085           msg_var ('unsupported', $parent,
7086                    "automake does not support conditional definition of "
7087                    . "$var in $parent");
7088         }
7089       else
7090         {
7091           msg_var ('unsupported', $var,
7092                    "automake does not support $var being defined "
7093                    . "conditionally");
7094         }
7095     }
7099 # Get the TRUE value of a variable, warn if the variable is
7100 # conditionally defined.
7101 sub variable_value
7103     my ($var) = @_;
7104     &check_variable_defined_unconditionally ($var);
7105     return $var_value{$var}{'TRUE'};
7109 # @VALUES
7110 # &value_to_list ($VAR, $VAL, $COND)
7111 # ----------------------------------
7112 # Convert a variable value to a list, split as whitespace.  This will
7113 # recursively follow $(...) and ${...} inclusions.  It preserves @...@
7114 # substitutions.
7116 # If COND is 'all', then all values under all conditions should be
7117 # returned; if COND is a particular condition (all conditions are
7118 # surrounded by @...@) then only the value for that condition should
7119 # be returned; otherwise, warn if VAR is conditionally defined.
7120 # SCANNED is a global hash listing whose keys are all the variables
7121 # already scanned; it is an error to rescan a variable.
7122 sub value_to_list ($$$)
7124     my ($var, $val, $cond) = @_;
7125     my @result;
7127     # Strip backslashes
7128     $val =~ s/\\(\n|$)/ /g;
7130     foreach (split (' ', $val))
7131     {
7132         # If a comment seen, just leave.
7133         last if /^#/;
7135         # Handle variable substitutions.
7136         if (/^\$\{([^}]*)\}$/ || /^\$\(([^)]*)\)$/)
7137         {
7138             my $varname = $1;
7140             # If the user uses a losing variable name, just ignore it.
7141             # This isn't ideal, but people have requested it.
7142             next if ($varname =~ /\@.*\@/);
7144             my ($from, $to);
7145             my @temp_list;
7146             if ($varname =~ /$SUBST_REF_PATTERN/o)
7147             {
7148                 $varname = $1;
7149                 $to = $3;
7150                 $from = quotemeta $2;
7151             }
7153             # Find the value.
7154             @temp_list =
7155               variable_value_as_list_recursive_worker ($1, $cond, $var);
7157             # Now rewrite the value if appropriate.
7158             if (defined $from)
7159             {
7160                 grep (s/$from$/$to/, @temp_list);
7161             }
7163             push (@result, @temp_list);
7164         }
7165         else
7166         {
7167             push (@result, $_);
7168         }
7169     }
7171     return @result;
7175 # @VALUES
7176 # variable_value_as_list ($VAR, $COND, $PARENT)
7177 # ---------------------------------------------
7178 # Get the value of a variable given a specified condition. without
7179 # recursing through any subvariables.
7180 # Arguments are:
7181 #   $VAR    is the variable
7182 #   $COND   is the condition.  If this is not given, the value for the
7183 #           "TRUE" condition will be returned.
7184 #   $PARENT is the variable in which the variable is used: this is used
7185 #           only for error messages.
7186 # Returns the list of conditions.
7187 # For example, if A is defined as "foo $(B) bar", and B is defined as
7188 # "baz", this will return ("foo", "$(B)", "bar")
7189 sub variable_value_as_list
7191     my ($var, $cond, $parent) = @_;
7192     my @result;
7194     # Check defined
7195     return
7196       unless variable_assert $var, $parent;
7198     # Get value for given condition
7199     $cond ||= 'TRUE';
7200     my $onceflag;
7201     foreach my $vcond (keys %{$var_value{$var}})
7202     {
7203         my $val = $var_value{$var}{$vcond};
7205         if (&conditional_true_when ($vcond, $cond))
7206         {
7207             # Unless variable is not defined conditionally, there should only
7208             # be one value of $vcond true when $cond.
7209             &check_variable_defined_unconditionally ($var, $parent)
7210                     if $onceflag;
7211             $onceflag = 1;
7213             # Strip backslashes
7214             $val =~ s/\\(\n|$)/ /g;
7216             foreach (split (' ', $val))
7217             {
7218                 # If a comment seen, just leave.
7219                 last if /^#/;
7221                 push (@result, $_);
7222             }
7223         }
7224     }
7226     return @result;
7230 # @VALUE
7231 # &variable_value_as_list_recursive_worker ($VAR, $COND, $PARENT)
7232 # ---------------------------------------------------------------
7233 # Return contents of VAR as a list, split on whitespace.  This will
7234 # recursively follow $(...) and ${...} inclusions.  It preserves @...@
7235 # substitutions.  If COND is 'all', then all values under all
7236 # conditions should be returned; if COND is a particular condition
7237 # (all conditions are surrounded by @...@) then only the value for
7238 # that condition should be returned; otherwise, warn if VAR is
7239 # conditionally defined.  If PARENT is specified, it is the name of
7240 # the including variable; this is only used for error reports.
7241 sub variable_value_as_list_recursive_worker ($$$)
7243     my ($var, $cond, $parent) = @_;
7244     my @result = ();
7246     return
7247       unless variable_assert $var, $parent;
7249     if (defined $vars_scanned{$var})
7250     {
7251         # `vars_scanned' is a global we use to keep track of which
7252         # variables we've already examined.
7253         err_var $parent, "variable `$var' recursively defined";
7254     }
7255     elsif ($cond eq 'all')
7256     {
7257         $vars_scanned{$var} = 1;
7258         foreach my $vcond (keys %{$var_value{$var}})
7259         {
7260             my $val = $var_value{$var}{$vcond};
7261             push (@result, &value_to_list ($var, $val, $cond));
7262         }
7263     }
7264     else
7265     {
7266         $cond ||= 'TRUE';
7267         $vars_scanned{$var} = 1;
7268         my $onceflag;
7269         foreach my $vcond (keys %{$var_value{$var}})
7270         {
7271             my $val = $var_value{$var}{$vcond};
7272             if (&conditional_true_when ($vcond, $cond))
7273             {
7274                 # Warn if we have an ambiguity.  It's hard to know how
7275                 # to handle this case correctly.
7276                 &check_variable_defined_unconditionally ($var, $parent)
7277                     if $onceflag;
7278                 $onceflag = 1;
7279                 push (@result, &value_to_list ($var, $val, $cond));
7280             }
7281         }
7282     }
7284     # Unset our entry in vars_scanned.  We only care about recursive
7285     # definitions.
7286     delete $vars_scanned{$var};
7288     return @result;
7292 # &variable_output ($VAR, [@CONDS])
7293 # ---------------------------------
7294 # Output all the values of $VAR is @COND is not specified, else only
7295 # that corresponding to @COND.
7296 sub variable_output ($@)
7298   my ($var, @conds) = @_;
7300   @conds = keys %{$var_value{$var}}
7301     unless @conds;
7303   foreach my $cond (sort by_condition @conds)
7304     {
7305       prog_error ("unknown condition `$cond' for `$var'")
7306         unless exists $var_value{$var}{$cond};
7308       if (exists $var_comment{$var} && exists $var_comment{$var}{$cond})
7309         {
7310           $output_vars .= $var_comment{$var}{$cond};
7311         }
7313       my $val = $var_value{$var}{$cond};
7314       my $equals = $var_type{$var}{$cond} eq ':' ? ':=' : '=';
7315       my $output_var = "$var $equals $val";
7316       $output_var =~ s/^/make_condition ($cond)/meg;
7317       $output_vars .= $output_var . "\n";
7318     }
7322 # &variable_pretty_output ($VAR, [@CONDS])
7323 # ----------------------------------------
7324 # Likewise, but pretty, i.e., we *split* the values at spaces.   Use only
7325 # with variables holding filenames.
7326 sub variable_pretty_output ($@)
7328   my ($var, @conds) = @_;
7330   @conds = keys %{$var_value{$var}}
7331     unless @conds;
7333   foreach my $cond (sort by_condition @conds)
7334     {
7335       prog_error ("unknown condition `$cond' for `$var'")
7336         unless exists $var_value{$var}{$cond};
7338       if (exists $var_comment{$var} && exists $var_comment{$var}{$cond})
7339         {
7340           $output_vars .= $var_comment{$var}{$cond};
7341         }
7343       my $val = $var_value{$var}{$cond};
7344       my $equals = $var_type{$var}{$cond} eq ':' ? ':=' : '=';
7345       my $make_condition = make_condition ($cond);
7347       # Suppress escaped new lines.  &pretty_print_internal will
7348       # add them back, maybe at other places.
7349       $val =~ s/\\$//mg;
7351       $output_vars .= pretty_print_internal ("$make_condition$var $equals",
7352                                              "$make_condition\t",
7353                                              split (' ' , $val));
7354     }
7358 # &variable_value_as_list_recursive ($VAR, $COND, $PARENT)
7359 # --------------------------------------------------------
7360 # This is just a wrapper for variable_value_as_list_recursive_worker that
7361 # initializes the global hash `vars_scanned'.  This hash is used to
7362 # avoid infinite recursion.
7363 sub variable_value_as_list_recursive ($$@)
7365     my ($var, $cond, $parent) = @_;
7366     %vars_scanned = ();
7367     return &variable_value_as_list_recursive_worker ($var, $cond, $parent);
7371 # &define_pretty_variable ($VAR, $COND, @VALUE)
7372 # ---------------------------------------------
7373 # Like define_variable, but the value is a list, and the variable may
7374 # be defined conditionally.  The second argument is the conditional
7375 # under which the value should be defined; this should be the empty
7376 # string to define the variable unconditionally.  The third argument
7377 # is a list holding the values to use for the variable.  The value is
7378 # pretty printed in the output file.
7379 sub define_pretty_variable ($$@)
7381     my ($var, $cond, @value) = @_;
7383     # Beware that an empty $cond has a different semantics for
7384     # macro_define and variable_pretty_output.
7385     $cond ||= 'TRUE';
7387     if (! variable_defined ($var, $cond))
7388     {
7389         macro_define ($var, VAR_AUTOMAKE, '', $cond, "@value", undef);
7390         variable_pretty_output ($var, $cond || 'TRUE');
7391         $content_seen{$var} = 1;
7392     }
7396 # define_variable ($VAR, $VALUE)
7397 # ------------------------------
7398 # Define a new user variable VAR to VALUE, but only if not already defined.
7399 sub define_variable ($$)
7401     my ($var, $value) = @_;
7402     define_pretty_variable ($var, 'TRUE', $value);
7406 # Like define_variable, but define a variable to be the configure
7407 # substitution by the same name.
7408 sub define_configure_variable ($)
7410   my ($var) = @_;
7411   if (! variable_defined ($var, 'TRUE')
7412       # Explicitly avoid ANSI2KNR -- we AC_SUBST that in
7413       # protos.m4, but later define it elsewhere.  This is
7414       # pretty hacky.  We also explicitly avoid AMDEPBACKSLASH:
7415       # it might be subst'd by `\', which certainly would not be
7416       # appreciated by Make.
7417       && ! grep { $_ eq $var } (qw(ANSI2KNR AMDEPBACKSLASH)))
7418     {
7419       macro_define ($var, VAR_CONFIGURE, '', 'TRUE',
7420                     subst $var, $configure_vars{$var});
7421       variable_pretty_output ($var, 'TRUE');
7422     }
7426 # define_compiler_variable ($LANG)
7427 # --------------------------------
7428 # Define a compiler variable.  We also handle defining the `LT'
7429 # version of the command when using libtool.
7430 sub define_compiler_variable ($)
7432     my ($lang) = @_;
7434     my ($var, $value) = ($lang->compiler, $lang->compile);
7435     &define_variable ($var, $value);
7436     &define_variable ("LT$var", "\$(LIBTOOL) --mode=compile $value")
7437       if variable_defined ('LIBTOOL');
7441 # define_linker_variable ($LANG)
7442 # ------------------------------
7443 # Define linker variables.
7444 sub define_linker_variable ($)
7446     my ($lang) = @_;
7448     my ($var, $value) = ($lang->lder, $lang->ld);
7449     # CCLD = $(CC).
7450     &define_variable ($lang->lder, $lang->ld);
7451     # CCLINK = $(CCLD) blah blah...
7452     &define_variable ($lang->linker,
7453                       ((variable_defined ('LIBTOOL')
7454                         ? '$(LIBTOOL) --mode=link ' : '')
7455                        . $lang->link));
7458 ################################################################
7460 ## ---------------- ##
7461 ## Handling rules.  ##
7462 ## ---------------- ##
7464 sub register_suffix_rule ($$$)
7466   my ($where, $src, $dest) = @_;
7468   verb "Sources ending in $src become $dest";
7469   push @suffixes, $src, $dest;
7471   # When tranforming sources to objects, Automake uses the
7472   # %suffix_rules to move from each source extension to
7473   # `.$(OBJEXT)', not to `.o' or `.obj'.  However some people
7474   # define suffix rules for `.o' or `.obj', so internally we will
7475   # consider these extensions equivalent to `.$(OBJEXT)'.  We
7476   # CANNOT rewrite the target (i.e., automagically replace `.o'
7477   # and `.obj' by `.$(OBJEXT)' in the output), or warn the user
7478   # that (s)he'd better use `.$(OBJEXT)', because Automake itself
7479   # output suffix rules for `.o' or `.obj'...
7480   $dest = '.$(OBJEXT)' if ($dest eq '.o' || $dest eq '.obj');
7482   # Reading the comments near the declaration of $suffix_rules might
7483   # help to understand the update of $suffix_rules that follows...
7485   # Register $dest as a possible destination from $src.
7486   # We might have the create the \hash.
7487   if (exists $suffix_rules->{$src})
7488     {
7489       $suffix_rules->{$src}{$dest} = [ $dest, 1 ];
7490     }
7491   else
7492     {
7493       $suffix_rules->{$src} = { $dest => [ $dest, 1 ] };
7494     }
7496   # If we know how to transform $dest in something else, then
7497   # we know how to transform $src in that "something else".
7498   if (exists $suffix_rules->{$dest})
7499     {
7500       for my $dest2 (keys %{$suffix_rules->{$dest}})
7501         {
7502           my $dist = $suffix_rules->{$dest}{$dest2}[1] + 1;
7503           # Overwrite an existing $src->$dest2 path only if
7504           # the path via $dest which is shorter.
7505           if (! exists $suffix_rules->{$src}{$dest2}
7506               || $suffix_rules->{$src}{$dest2}[1] > $dist)
7507             {
7508               $suffix_rules->{$src}{$dest2} = [ $dest, $dist ];
7509             }
7510         }
7511     }
7513   # Similarly, any extension that can be derived into $src
7514   # can be derived into the same extenstions as $src can.
7515   my @dest2 = keys %{$suffix_rules->{$src}};
7516   for my $src2 (keys %$suffix_rules)
7517     {
7518       if (exists $suffix_rules->{$src2}{$src})
7519         {
7520           for my $dest2 (@dest2)
7521             {
7522               my $dist = $suffix_rules->{$src}{$dest2} + 1;
7523               # Overwrite an existing $src2->$dest2 path only if
7524               # the path via $src is shorter.
7525               if (! exists $suffix_rules->{$src2}{$dest2}
7526                   || $suffix_rules->{$src2}{$dest2}[1] > $dist)
7527                 {
7528                   $suffix_rules->{$src2}{$dest2} = [ $src, $dist ];
7529                 }
7530             }
7531         }
7532     }
7535 # @CONDS
7536 # rule_define ($TARGET, $SOURCE, $OWNER, $COND, $WHERE)
7537 # -----------------------------------------------------
7538 # Define a new rule.  $TARGET is the rule name.  $SOURCE
7539 # is the filename the rule comes from.  $OWNER is the
7540 # owener of the rule (TARGET_AUTOMAKE or TARGET_USER).
7541 # $COND is the condition string under which the rule is defined.
7542 # $WHERE is where the rule is defined (file name and/or line number).
7543 # Returns a (possibly empty) list of conditions where the rule
7544 # should be defined.
7545 sub rule_define ($$$$$)
7547   my ($target, $source, $owner, $cond, $where) = @_;
7549   # Don't even think about defining a rule in condition FALSE.
7550   return () if $cond eq 'FALSE';
7552   # For now `foo:' will override `foo$(EXEEXT):'.  This is temporary,
7553   # though, so we emit a warning.
7554   (my $noexe = $target) =~ s,\$\(EXEEXT\)$,,;
7555   if ($noexe ne $target
7556       && exists $targets{$noexe}
7557       && exists $targets{$noexe}{$cond}
7558       && $target_name{$noexe}{$cond} ne $target)
7559     {
7560       # The no-exeext option enables this feature.
7561       if (! defined $options{'no-exeext'})
7562         {
7563           msg ('obsolete', $noexe,
7564                "deprecated feature: `$noexe' overrides `$noexe\$(EXEEXT)'\n"
7565                . "change your target to read `$noexe\$(EXEEXT)'");
7566         }
7567       # Don't define.
7568       return ();
7569     }
7571   # For now on, strip off $(EXEEXT) from $target, so we can diagnose
7572   # a clash if `ctags$(EXEEXT):' is redefined after `ctags:'.
7573   my $realtarget = $target;
7574   $target = $noexe;
7576   # A GNU make-style pattern rule has a single "%" in the target name.
7577   msg ('portability', $where,
7578        "`%'-style pattern rules are a GNU make extension")
7579     if $target =~ /^[^%]*%[^%]*$/;
7581   # Diagnose target redefinitions.
7582   if (exists $target_source{$target}{$cond})
7583     {
7584       # Sanity checks.
7585       prog_error ("\$target_source{$target}{$cond} exists, but \$target_owner"
7586                   . " doesn't.")
7587         unless exists $target_owner{$target}{$cond};
7588       prog_error ("\$target_source{$target}{$cond} exists, but \$targets"
7589                   . " doesn't.")
7590         unless exists $targets{$target}{$cond};
7591       prog_error ("\$target_source{$target}{$cond} exists, but \$target_name"
7592                   . " doesn't.")
7593         unless exists $target_name{$target}{$cond};
7595       my $oldowner  = $target_owner{$target}{$cond};
7597       # Don't mention true conditions in diagnostics.
7598       my $condmsg = $cond ne 'TRUE' ? " in condition `$cond'" : '';
7600       if ($owner == TARGET_USER)
7601         {
7602           if ($oldowner eq TARGET_USER)
7603             {
7604               # Ignore `%'-style pattern rules.  We'd need the
7605               # dependencies to detect duplicates, and they are
7606               # already diagnosed as unportable by -Wportability.
7607               if ($target !~ /^[^%]*%[^%]*$/)
7608                 {
7609                   ## FIXME: Presently we can't diagnose duplcate user rules
7610                   ## because we doesn't distinguish rules with commands
7611                   ## from rules that only add dependencies.  E.g.,
7612                   ##   .PHONY: foo
7613                   ##   .PHONY: bar
7614                   ## is legitimate. (This is phony.test.)
7616                   # msg ('syntax', $where,
7617                   #      "redefinition of `$target'$condmsg...");
7618                   # msg_cond_target ('syntax', $cond, $target,
7619                   #                "... `$target' previously defined here.");
7620                 }
7621               # Return so we don't redefine the rule in our tables,
7622               # don't check for ambiguous conditional, etc.  The rule
7623               # will be output anyway beauce &read_am_file ignore the
7624               # return code.
7625               return ();
7626             }
7627           else
7628             {
7629               # Since we parse the user Makefile.am before reading
7630               # the Automake fragments, this condition should never happen.
7631               prog_error ("user target `$target' seen after Automake's "
7632                           . "definition\nfrom `$targets{$target}$condmsg'");
7633             }
7634         }
7635       else # $owner == TARGET_AUTOMAKE
7636         {
7637           if ($oldowner == TARGET_USER)
7638             {
7639               # Don't overwrite the user definition of TARGET.
7640               return ();
7641             }
7642           else # $oldowner == TARGET_AUTOMAKE
7643             {
7644               # Automake should ignore redefinitions of its own
7645               # rules if they came from the same file.  This makes
7646               # it easier to process a Makefile fragment several times.
7647               # Hower it's an error if the target is defined in many
7648               # files.  E.g., the user might be using bin_PROGRAMS = ctags
7649               # which clashes with our `ctags' rule.
7650               # (It would be more accurate if we had a way to compare
7651               # the *content* of both rules.  Then $targets_source would
7652               # be useless.)
7653               my $oldsource = $target_source{$target}{$cond};
7654               return () if $source eq $oldsource;
7656               msg ('syntax', $where, "redefinition of `$target'$condmsg...");
7657               msg_cond_target ('syntax', $cond, $target,
7658                                "... `$target' previously defined here.");
7659               return ();
7660             }
7661         }
7662       # Never reached.
7663       prog_error ("Unreachable place reached.");
7664     }
7666   # Conditions for which the rule should be defined.
7667   my @conds = $cond;
7669   # Check ambiguous conditional definitions.
7670   my ($message, $ambig_cond) =
7671     conditional_ambiguous_p ($target, $cond, keys %{$targets{$target}});
7672   if ($message)                 # We have an ambiguty.
7673     {
7674       if ($owner == TARGET_USER)
7675         {
7676           # For user rules, just diagnose the ambiguity.
7677           msg 'syntax', $where, "$message ...";
7678           msg_cond_target ('syntax', $ambig_cond, $target,
7679                            "... `$target' previously defined here.");
7680           return ();
7681         }
7682       else
7683         {
7684           # FIXME: for Automake rules, we can't diagnose ambiguities yet.
7685           # The point is that Automake doesn't propagate conditionals
7686           # everywhere.  For instance &handle_PROGRAMS doesn't care if
7687           # bin_PROGRAMS was defined conditionally or not.
7688           # On the following input
7689           #   if COND1
7690           #   foo:
7691           #           ...
7692           #   else
7693           #   bin_PROGRAMS = foo
7694           #   endif
7695           # &handle_PROGRAMS will attempt to define a `foo:' rule
7696           # in condition TRUE (which conflicts with COND1).  Fixing
7697           # this in &handle_PROGRAMS and siblings seems hard: you'd
7698           # have to explain &file_contents what to do with a
7699           # conditional.  So for now we do our best *here*.  If `foo:'
7700           # was already defined in condition COND1 and we want to define
7701           # it in condition TRUE, then define it only in condition !COND1.
7702           # (See cond14.test and cond15.test for some test cases.)
7703           my @defined_conds = keys %{$targets{$target}};
7704           @conds = ();
7705           for my $undefined_cond (invert_conditions(@defined_conds))
7706             {
7707               push @conds, make_condition ($cond, $undefined_cond);
7708             }
7709           # No conditions left to define the rule.
7710           # Warn, because our workaround is meaningless in this case.
7711           if (scalar @conds == 0)
7712             {
7713               msg 'syntax', $where, "$message ...";
7714               msg_cond_target ('syntax', $ambig_cond, $target,
7715                                "... `$target' previously defined here.");
7716               return ();
7717             }
7718         }
7719     }
7721   # Finally define this rule.
7722   for my $c (@conds)
7723     {
7724       $targets{$target}{$c} = $where;
7725       $target_source{$target}{$c} = $source;
7726       $target_owner{$target}{$c} = $owner;
7727       $target_name{$target}{$c} = $realtarget;
7728     }
7730   # We honor inference rules with multiple targets because many
7731   # make support this and people use it.  However this is disallowed
7732   # by POSIX.  We'll print a warning later.
7733   my $target_count = 0;
7734   my $inference_rule_count = 0;
7735   for my $t (split (' ', $target))
7736     {
7737       ++$target_count;
7738       # Check the rule for being a suffix rule. If so, store in a hash.
7739       # Either it's a rule for two known extensions...
7740       if ($t =~ /^($KNOWN_EXTENSIONS_PATTERN)($KNOWN_EXTENSIONS_PATTERN)$/
7741           # ...or it's a rule with unknown extensions (.i.e, the rule
7742           # looks like `.foo.bar:' but `.foo' or `.bar' are not
7743           # declared in SUFFIXES and are not known language
7744           # extensions).  Automake will complete SUFFIXES from
7745           # @suffixes automatically (see handle_footer).
7746           || ($t =~ /$SUFFIX_RULE_PATTERN/o && accept_extensions($1)))
7747         {
7748           ++$inference_rule_count;
7749           register_suffix_rule ($where, $1, $2);
7750         }
7751     }
7753   # POSIX allow multiple targets befor the colon, but disallow
7754   # definitions of multiple Inference rules.  It's also
7755   # disallowed to mix plain targets with inference rules.
7756   msg ('portability', $where,
7757        "Inference rules can have only one target before the colon (POSIX).")
7758     if $inference_rule_count > 0 && $target_count > 1;
7760   # Return "" instead of TRUE so it can be used with make_paragraphs
7761   # directly.
7762   return "" if 1 == @conds && $conds[0] eq 'TRUE';
7763   return @conds;
7767 # See if a target exists.
7768 sub target_defined
7770     my ($target) = @_;
7771     return exists $targets{$target};
7775 ################################################################
7777 # &append_comments ($VARIABLE, $SPACING, $COMMENT)
7778 # ------------------------------------------------
7779 # Apped $COMMENT to the other comments for $VARIABLE, using
7780 # $SPACING as separator.
7781 sub append_comments ($$$$)
7783     my ($cond, $var, $spacing, $comment) = @_;
7784     $var_comment{$var}{$cond} .= $spacing
7785         if (!defined $var_comment{$var}{$cond}
7786             || $var_comment{$var}{$cond} !~ /\n$/o);
7787     $var_comment{$var}{$cond} .= $comment;
7791 # &read_am_file ($AMFILE)
7792 # -----------------------
7793 # Read Makefile.am and set up %contents.  Simultaneously copy lines
7794 # from Makefile.am into $output_trailer or $output_vars as
7795 # appropriate.  NOTE we put rules in the trailer section.  We want
7796 # user rules to come after our generated stuff.
7797 sub read_am_file ($)
7799     my ($amfile) = @_;
7801     my $am_file = new Automake::XFile ("< $amfile");
7802     verb "reading $amfile";
7804     my $spacing = '';
7805     my $comment = '';
7806     my $blank = 0;
7807     my $saw_bk = 0;
7809     use constant IN_VAR_DEF => 0;
7810     use constant IN_RULE_DEF => 1;
7811     use constant IN_COMMENT => 2;
7812     my $prev_state = IN_RULE_DEF;
7814     while ($_ = $am_file->getline)
7815     {
7816         if (/$IGNORE_PATTERN/o)
7817         {
7818             # Merely delete comments beginning with two hashes.
7819         }
7820         elsif (/$WHITE_PATTERN/o)
7821         {
7822             error "$amfile:$.", "blank line following trailing backslash"
7823               if $saw_bk;
7824             # Stick a single white line before the incoming macro or rule.
7825             $spacing = "\n";
7826             $blank = 1;
7827             # Flush all comments seen so far.
7828             if ($comment ne '')
7829             {
7830                 $output_vars .= $comment;
7831                 $comment = '';
7832             }
7833         }
7834         elsif (/$COMMENT_PATTERN/o)
7835         {
7836             # Stick comments before the incoming macro or rule.  Make
7837             # sure a blank line preceeds first block of comments.
7838             $spacing = "\n" unless $blank;
7839             $blank = 1;
7840             $comment .= $spacing . $_;
7841             $spacing = '';
7842             $prev_state = IN_COMMENT;
7843         }
7844         else
7845         {
7846             last;
7847         }
7848         $saw_bk = /\\$/ && ! /$IGNORE_PATTERN/o;
7849     }
7851     # We save the conditional stack on entry, and then check to make
7852     # sure it is the same on exit.  This lets us conditonally include
7853     # other files.
7854     my @saved_cond_stack = @cond_stack;
7855     my $cond = conditional_string (@cond_stack);
7857     my $last_var_name = '';
7858     my $last_var_type = '';
7859     my $last_var_value = '';
7860     # FIXME: shouldn't use $_ in this loop; it is too big.
7861     while ($_)
7862     {
7863         my $here = "$amfile:$.";
7865         # Make sure the line is \n-terminated.
7866         chomp;
7867         $_ .= "\n";
7869         # Don't look at MAINTAINER_MODE_TRUE here.  That shouldn't be
7870         # used by users.  @MAINT@ is an anachronism now.
7871         $_ =~ s/\@MAINT\@//g
7872             unless $seen_maint_mode;
7874         my $new_saw_bk = /\\$/ && ! /$IGNORE_PATTERN/o;
7876         if (/$IGNORE_PATTERN/o)
7877         {
7878             # Merely delete comments beginning with two hashes.
7879         }
7880         elsif (/$WHITE_PATTERN/o)
7881         {
7882             # Stick a single white line before the incoming macro or rule.
7883             $spacing = "\n";
7884             error $here, "blank line following trailing backslash"
7885               if $saw_bk;
7886         }
7887         elsif (/$COMMENT_PATTERN/o)
7888         {
7889             # Stick comments before the incoming macro or rule.
7890             $comment .= $spacing . $_;
7891             $spacing = '';
7892             error $here, "comment following trailing backslash"
7893               if $saw_bk && $comment eq '';
7894             $prev_state = IN_COMMENT;
7895         }
7896         elsif ($saw_bk)
7897         {
7898             if ($prev_state == IN_RULE_DEF)
7899             {
7900                 $output_trailer .= &make_condition (@cond_stack);
7901                 $output_trailer .= $_;
7902             }
7903             elsif ($prev_state == IN_COMMENT)
7904             {
7905                 # If the line doesn't start with a `#', add it.
7906                 # We do this because a continuated comment like
7907                 #   # A = foo \
7908                 #         bar \
7909                 #         baz
7910                 # is not portable.  BSD make doesn't honor
7911                 # escaped newlines in comments.
7912                 s/^#?/#/;
7913                 $comment .= $spacing . $_;
7914             }
7915             else # $prev_state == IN_VAR_DEF
7916             {
7917               $last_var_value .= ' '
7918                 unless $last_var_value =~ /\s$/;
7919               $last_var_value .= $_;
7921               if (!/\\$/)
7922                 {
7923                   append_comments ($cond || 'TRUE',
7924                                    $last_var_name, $spacing, $comment);
7925                   $comment = $spacing = '';
7926                   macro_define ($last_var_name, VAR_MAKEFILE,
7927                                 $last_var_type, $cond,
7928                                 $last_var_value, $here)
7929                     if $cond ne 'FALSE';
7930                   push (@var_list, $last_var_name);
7931                 }
7932             }
7933         }
7935         elsif (/$IF_PATTERN/o)
7936           {
7937             $cond = cond_stack_if ($1, $2, $here);
7938           }
7939         elsif (/$ELSE_PATTERN/o)
7940           {
7941             $cond = cond_stack_else ($1, $2, $here);
7942           }
7943         elsif (/$ENDIF_PATTERN/o)
7944           {
7945             $cond = cond_stack_endif ($1, $2, $here);
7946           }
7948         elsif (/$RULE_PATTERN/o)
7949         {
7950             # Found a rule.
7951             $prev_state = IN_RULE_DEF;
7953             # For now we have to output all definitions of user rules
7954             # and can't diagnose duplicates (see the comment in
7955             # rule_define). So we go on and ignore the return value.
7956             rule_define ($1, $amfile, TARGET_USER, $cond || 'TRUE', $here);
7958             check_variable_expansions ($_, $here);
7960             $output_trailer .= $comment . $spacing;
7961             $output_trailer .= &make_condition (@cond_stack);
7962             $output_trailer .= $_;
7963             $comment = $spacing = '';
7964         }
7965         elsif (/$ASSIGNMENT_PATTERN/o)
7966         {
7967             # Found a macro definition.
7968             $prev_state = IN_VAR_DEF;
7969             $last_var_name = $1;
7970             $last_var_type = $2;
7971             $last_var_value = $3;
7972             if ($3 ne '' && substr ($3, -1) eq "\\")
7973             {
7974                 # We preserve the `\' because otherwise the long lines
7975                 # that are generated will be truncated by broken
7976                 # `sed's.
7977                 $last_var_value = $3 . "\n";
7978             }
7980             if (!/\\$/)
7981               {
7982                 # Accumulating variables must not be output.
7983                 append_comments ($cond || 'TRUE',
7984                                  $last_var_name, $spacing, $comment);
7985                 $comment = $spacing = '';
7987                 macro_define ($last_var_name, VAR_MAKEFILE,
7988                               $last_var_type, $cond,
7989                               $last_var_value, $here)
7990                   if $cond ne 'FALSE';
7991                 push (@var_list, $last_var_name);
7992               }
7993         }
7994         elsif (/$INCLUDE_PATTERN/o)
7995         {
7996             my $path = $1;
7998             if ($path =~ s/^\$\(top_srcdir\)\///)
7999               {
8000                 push (@include_stack, "\$\(top_srcdir\)/$path");
8001                 # Distribute any included file.
8003                 # Always use the $(top_srcdir) prefix in DIST_COMMON,
8004                 # otherwise OSF make will implicitely copy the included
8005                 # file in the build tree during `make distdir' to satisfy
8006                 # the dependency.
8007                 # (subdircond2.test and subdircond3.test will fail.)
8008                 push_dist_common ("\$\(top_srcdir\)/$path");
8009               }
8010             else
8011               {
8012                 $path =~ s/\$\(srcdir\)\///;
8013                 push (@include_stack, "\$\(srcdir\)/$path");
8014                 # Always use the $(srcdir) prefix in DIST_COMMON,
8015                 # otherwise OSF make will implicitely copy the included
8016                 # file in the build tree during `make distdir' to satisfy
8017                 # the dependency.
8018                 # (subdircond2.test and subdircond3.test will fail.)
8019                 push_dist_common ("\$\(srcdir\)/$path");
8020                 $path = $relative_dir . "/" . $path;
8021               }
8022             &read_am_file ($path);
8023         }
8024         else
8025         {
8026             # This isn't an error; it is probably a continued rule.
8027             # In fact, this is what we assume.
8028             $prev_state = IN_RULE_DEF;
8029             check_variable_expansions ($_, $here);
8030             $output_trailer .= $comment . $spacing;
8031             $output_trailer .= &make_condition  (@cond_stack);
8032             $output_trailer .= $_;
8033             $comment = $spacing = '';
8034             error $here, "`#' comment at start of rule is unportable"
8035               if $_ =~ /^\t\s*\#/;
8036         }
8038         $saw_bk = $new_saw_bk;
8039         $_ = $am_file->getline;
8040     }
8042     $output_trailer .= $comment;
8044     err_am (@cond_stack ? "unterminated conditionals: @cond_stack"
8045             : "too many conditionals closed in include file")
8046       if "@saved_cond_stack" ne "@cond_stack";
8050 # define_standard_variables ()
8051 # ----------------------------
8052 # A helper for read_main_am_file which initializes configure variables
8053 # and variables from header-vars.am.
8054 sub define_standard_variables
8056     my $saved_output_vars = $output_vars;
8057     my ($comments, undef, $rules) =
8058       file_contents_internal (1, "$libdir/am/header-vars.am");
8060     # This will output the definitions in $output_vars, which we don't
8061     # want...
8062     foreach my $var (sort keys %configure_vars)
8063     {
8064         &define_configure_variable ($var);
8065         push (@var_list, $var);
8066     }
8068     # ... hence, we restore $output_vars.
8069     $output_vars = $saved_output_vars . $comments . $rules;
8072 # Read main am file.
8073 sub read_main_am_file
8075     my ($amfile) = @_;
8077     # This supports the strange variable tricks we are about to play.
8078     prog_error (macros_dump () . "variable defined before read_main_am_file")
8079       if (scalar keys %var_value > 0);
8081     # Generate copyright header for generated Makefile.in.
8082     # We do discard the output of predefined variables, handled below.
8083     $output_vars = ("# $in_file_name generated by automake "
8084                    . $VERSION . " from $am_file_name.\n");
8085     $output_vars .= '# ' . subst ('configure_input') . "\n";
8086     $output_vars .= $gen_copyright;
8088     # We want to predefine as many variables as possible.  This lets
8089     # the user set them with `+=' in Makefile.am.  However, we don't
8090     # want these initial definitions to end up in the output quite
8091     # yet.  So we just load them, but output them later.
8092     &define_standard_variables;
8094     # Read user file, which might override some of our values.
8095     &read_am_file ($amfile);
8097     # Output all the Automake variables.  If the user changed one,
8098     # then it is now marked as VAR_CONFIGURE or VAR_MAKEFILE.
8099     foreach my $var (uniq @var_list)
8100     {
8101       # Some variables, like AMDEPBACKSLASH are in @var_list
8102       # but don't have a owner.  This is good, because we don't want
8103       # to output them.
8104       foreach my $cond (keys %{$var_owner{$var}})
8105         {
8106           variable_output ($var, $cond)
8107             if $var_owner{$var}{$cond} == VAR_AUTOMAKE;
8108         }
8109     }
8111     # Now dump the user variables that were defined.  We do it in the same
8112     # order in which they were defined (skipping duplicates).
8113     foreach my $var (uniq @var_list)
8114     {
8115       foreach my $cond (keys %{$var_owner{$var}})
8116         {
8117           variable_output ($var, $cond)
8118             if $var_owner{$var}{$cond} != VAR_AUTOMAKE;
8119         }
8120     }
8123 ################################################################
8125 # $FLATTENED
8126 # &flatten ($STRING)
8127 # ------------------
8128 # Flatten the $STRING and return the result.
8129 sub flatten
8131   $_ = shift;
8133   s/\\\n//somg;
8134   s/\s+/ /g;
8135   s/^ //;
8136   s/ $//;
8138   return $_;
8142 # @PARAGRAPHS
8143 # &make_paragraphs ($MAKEFILE, [%TRANSFORM])
8144 # ------------------------------------------
8145 # Load a $MAKEFILE, apply the %TRANSFORM, and return it as a list of
8146 # paragraphs.
8147 sub make_paragraphs ($%)
8149     my ($file, %transform) = @_;
8151     # Complete %transform with global options and make it a Perl
8152     # $command.
8153     my $command =
8154       "s/$IGNORE_PATTERN//gm;"
8155         . transform (%transform,
8157                      'CYGNUS'          => $cygnus_mode,
8158                      'MAINTAINER-MODE'
8159                      => $seen_maint_mode ? subst ('MAINTAINER_MODE_TRUE') : '',
8161                      'SHAR'        => $options{'dist-shar'} || 0,
8162                      'BZIP2'       => $options{'dist-bzip2'} || 0,
8163                      'ZIP'         => $options{'dist-zip'} || 0,
8164                      'COMPRESS'    => $options{'dist-tarZ'} || 0,
8166                      'INSTALL-INFO' => !$options{'no-installinfo'},
8167                      'INSTALL-MAN'  => !$options{'no-installman'},
8168                      'CK-NEWS'      => $options{'check-news'} || 0,
8170                      'SUBDIRS'      => variable_defined ('SUBDIRS'),
8171                      'TOPDIR'       => backname ($relative_dir),
8172                      'TOPDIR_P'     => $relative_dir eq '.',
8173                      'CONFIGURE-AC' => $configure_ac,
8175                      'BUILD'    => $seen_canonical == AC_CANONICAL_SYSTEM,
8176                      'HOST'     => $seen_canonical,
8177                      'TARGET'   => $seen_canonical == AC_CANONICAL_SYSTEM,
8179                      'LIBTOOL'      => variable_defined ('LIBTOOL'))
8180           # We don't need more than two consecutive new-lines.
8181           . 's/\n{3,}/\n\n/g';
8183     # Swallow the file and apply the COMMAND.
8184     my $fc_file = new Automake::XFile "< $file";
8185     # Looks stupid?
8186     verb "reading $file";
8187     my $saved_dollar_slash = $/;
8188     undef $/;
8189     $_ = $fc_file->getline;
8190     $/ = $saved_dollar_slash;
8191     eval $command;
8192     $fc_file->close;
8193     my $content = $_;
8195     # Split at unescaped new lines.
8196     my @lines = split (/(?<!\\)\n/, $content);
8197     my @res;
8199     while (defined ($_ = shift @lines))
8200       {
8201         my $paragraph = "$_";
8202         # If we are a rule, eat as long as we start with a tab.
8203         if (/$RULE_PATTERN/smo)
8204           {
8205             while (defined ($_ = shift @lines) && $_ =~ /^\t/)
8206               {
8207                 $paragraph .= "\n$_";
8208               }
8209             unshift (@lines, $_);
8210           }
8212         # If we are a comments, eat as much comments as you can.
8213         elsif (/$COMMENT_PATTERN/smo)
8214           {
8215             while (defined ($_ = shift @lines)
8216                    && $_ =~ /$COMMENT_PATTERN/smo)
8217               {
8218                 $paragraph .= "\n$_";
8219               }
8220             unshift (@lines, $_);
8221           }
8223         push @res, $paragraph;
8224         $paragraph = '';
8225       }
8227     return @res;
8232 # ($COMMENT, $VARIABLES, $RULES)
8233 # &file_contents_internal ($IS_AM, $FILE, [%TRANSFORM])
8234 # -----------------------------------------------------
8235 # Return contents of a file from $libdir/am, automatically skipping
8236 # macros or rules which are already known. $IS_AM iff the caller is
8237 # reading an Automake file (as opposed to the user's Makefile.am).
8238 sub file_contents_internal ($$%)
8240     my ($is_am, $file, %transform) = @_;
8242     my $result_vars = '';
8243     my $result_rules = '';
8244     my $comment = '';
8245     my $spacing = '';
8247     # The following flags are used to track rules spanning across
8248     # multiple paragraphs.
8249     my $is_rule = 0;            # 1 if we are processing a rule.
8250     my $discard_rule = 0;       # 1 if the current rule should not be output.
8252     # We save the conditional stack on entry, and then check to make
8253     # sure it is the same on exit.  This lets us conditonally include
8254     # other files.
8255     my @saved_cond_stack = @cond_stack;
8256     my $cond = conditional_string (@cond_stack);
8258     foreach (make_paragraphs ($file, %transform))
8259     {
8260         # Sanity checks.
8261         error $file, "blank line following trailing backslash:\n$_"
8262           if /\\$/;
8263         error $file, "comment following trailing backslash:\n$_"
8264           if /\\#/;
8266         if (/^$/)
8267         {
8268             $is_rule = 0;
8269             # Stick empty line before the incoming macro or rule.
8270             $spacing = "\n";
8271         }
8272         elsif (/$COMMENT_PATTERN/mso)
8273         {
8274             $is_rule = 0;
8275             # Stick comments before the incoming macro or rule.
8276             $comment = "$_\n";
8277         }
8279         # Handle inclusion of other files.
8280         elsif (/$INCLUDE_PATTERN/o)
8281         {
8282             if ($cond ne 'FALSE')
8283               {
8284                 my $file = ($is_am ? "$libdir/am/" : '') . $1;
8285                 # N-ary `.=' fails.
8286                 my ($com, $vars, $rules)
8287                   = file_contents_internal ($is_am, $file, %transform);
8288                 $comment .= $com;
8289                 $result_vars .= $vars;
8290                 $result_rules .= $rules;
8291               }
8292         }
8294         # Handling the conditionals.
8295         elsif (/$IF_PATTERN/o)
8296           {
8297             $cond = cond_stack_if ($1, $2, $file);
8298           }
8299         elsif (/$ELSE_PATTERN/o)
8300           {
8301             $cond = cond_stack_else ($1, $2, $file);
8302           }
8303         elsif (/$ENDIF_PATTERN/o)
8304           {
8305             $cond = cond_stack_endif ($1, $2, $file);
8306           }
8308         # Handling rules.
8309         elsif (/$RULE_PATTERN/mso)
8310         {
8311           $is_rule = 1;
8312           $discard_rule = 0;
8313           # Separate relationship from optional actions: the first
8314           # `new-line tab" not preceded by backslash (continuation
8315           # line).
8316           my $paragraph = $_;
8317           /^(.*?)(?:(?<!\\)\n(\t.*))?$/s;
8318           my ($relationship, $actions) = ($1, $2 || '');
8320           # Separate targets from dependencies: the first colon.
8321           $relationship =~ /^([^:]+\S+) *: *(.*)$/som;
8322           my ($targets, $dependencies) = ($1, $2);
8323           # Remove the escaped new lines.
8324           # I don't know why, but I have to use a tmp $flat_deps.
8325           my $flat_deps = &flatten ($dependencies);
8326           my @deps = split (' ', $flat_deps);
8328           foreach (split (' ' , $targets))
8329             {
8330               # FIXME: 1. We are not robust to people defining several targets
8331               # at once, only some of them being in %dependencies.  The
8332               # actions from the targets in %dependencies are usually generated
8333               # from the content of %actions, but if some targets in $targets
8334               # are not in %dependencies the ELSE branch will output
8335               # a rule for all $targets (i.e. the targets which are both
8336               # in %dependencies and $targets will have two rules).
8338               # FIXME: 2. The logic here is not able to output a
8339               # multi-paragraph rule several time (e.g. for each conditional
8340               # it is defined for) because it only knows the first paragraph.
8342               # FIXME: 3. We are not robust to people defining a subset
8343               # of a previously defined "multiple-target" rule.  E.g.
8344               # `foo:' after `foo bar:'.
8346               # Output only if not in FALSE.
8347               if (defined $dependencies{$_} && $cond ne 'FALSE')
8348                 {
8349                   &depend ($_, @deps);
8350                   $actions{$_} .= $actions;
8351                 }
8352               else
8353                 {
8354                   # Free-lance dependency.  Output the rule for all the
8355                   # targets instead of one by one.
8356                   my @undefined_conds =
8357                     rule_define ($targets, $file,
8358                                  $is_am ? TARGET_AUTOMAKE : TARGET_USER,
8359                                  $cond || 'TRUE', $file);
8360                   for my $undefined_cond (@undefined_conds)
8361                     {
8362                       my $condparagraph = $paragraph;
8363                       $condparagraph =~ s/^/$undefined_cond/gm;
8364                       $result_rules .= "$spacing$comment$condparagraph\n";
8365                     }
8366                   if (scalar @undefined_conds == 0)
8367                     {
8368                       # Remember to discard next paragraphs
8369                       # if they belong to this rule.
8370                       # (but see also FIXME: #2 above.)
8371                       $discard_rule = 1;
8372                     }
8373                   $comment = $spacing = '';
8374                   last;
8375                 }
8376             }
8377         }
8379         elsif (/$ASSIGNMENT_PATTERN/mso)
8380         {
8381             my ($var, $type, $val) = ($1, $2, $3);
8382             error $file, "variable `$var' with trailing backslash"
8383               if /\\$/;
8385             $is_rule = 0;
8387             # Accumulating variables must not be output.
8388             append_comments ($cond || 'TRUE', $var, $spacing, $comment);
8389             macro_define ($var, $is_am ? VAR_AUTOMAKE : VAR_MAKEFILE,
8390                           $type, $cond, $val, $file)
8391               if $cond ne 'FALSE';
8392             push (@var_list, $var);
8394             # If the user has set some variables we were in charge
8395             # of (which is detected by the first reading of
8396             # `header-vars.am'), we must not output them.
8397             $result_vars .= "$spacing$comment$_\n"
8398               if ($cond ne 'FALSE' && $type ne '+'
8399                   && exists $var_owner{$var}{$cond || 'TRUE'}
8400                   && $var_owner{$var}{$cond || 'TRUE'} == VAR_AUTOMAKE);
8402             $comment = $spacing = '';
8403         }
8404         else
8405         {
8406             # This isn't an error; it is probably some tokens which
8407             # configure is supposed to replace, such as `@SET-MAKE@',
8408             # or some part of a rule cut by an if/endif.
8409             if ($cond ne 'FALSE' && ! ($is_rule && $discard_rule))
8410               {
8411                 s/^/make_condition (@cond_stack)/gme;
8412                 $result_rules .= "$spacing$comment$_\n";
8413               }
8414             $comment = $spacing = '';
8415         }
8416     }
8418     err_am (@cond_stack ?
8419             "unterminated conditionals: @cond_stack" :
8420             "too many conditionals closed in include file")
8421       if "@saved_cond_stack" ne "@cond_stack";
8423     return ($comment, $result_vars, $result_rules);
8427 # $CONTENTS
8428 # &file_contents ($BASENAME, [%TRANSFORM])
8429 # ----------------------------------------
8430 # Return contents of a file from $libdir/am, automatically skipping
8431 # macros or rules which are already known.
8432 sub file_contents ($%)
8434     my ($basename, %transform) = @_;
8435     my ($comments, $variables, $rules) =
8436       file_contents_internal (1, "$libdir/am/$basename.am", %transform);
8437     return "$comments$variables$rules";
8441 # $REGEXP
8442 # &transform (%PAIRS)
8443 # -------------------
8444 # Foreach ($TOKEN, $VAL) in %PAIRS produce a replacement expression suitable
8445 # for file_contents which:
8446 #   - replaces %$TOKEN% with $VAL,
8447 #   - enables/disables ?$TOKEN? and ?!$TOKEN?,
8448 #   - replaces %?$TOKEN% with TRUE or FALSE.
8449 sub transform (%)
8451     my (%pairs) = @_;
8452     my $result = '';
8454     while (my ($token, $val) = each %pairs)
8455     {
8456         $result .= "s/\Q%$token%\E/\Q$val\E/gm;";
8457         if ($val)
8458         {
8459             $result .= "s/\Q?$token?\E//gm;s/^.*\Q?!$token?\E.*\\n//gm;";
8460             $result .= "s/\Q%?$token%\E/TRUE/gm;";
8461         }
8462         else
8463         {
8464             $result .= "s/\Q?!$token?\E//gm;s/^.*\Q?$token?\E.*\\n//gm;";
8465             $result .= "s/\Q%?$token%\E/FALSE/gm;";
8466         }
8467     }
8469     return $result;
8473 # &append_exeext ($MACRO)
8474 # -----------------------
8475 # Macro is an Automake magic macro which primary is PROGRAMS, e.g.
8476 # bin_PROGRAMS.  Make sure these programs have $(EXEEXT) appended.
8477 sub append_exeext ($)
8479   my ($macro) = @_;
8481   prog_error "append_exeext ($macro)"
8482     unless $macro =~ /_PROGRAMS$/;
8484   my @conds = variable_conditions_recursive ($macro);
8486   my @condvals;
8487   foreach my $cond (@conds)
8488     {
8489       my @one_binlist = ();
8490       my @condval = variable_value_as_list_recursive ($macro, $cond);
8491       foreach my $rcurs (@condval)
8492         {
8493           # Skip autoconf substs.  Also skip if the user
8494           # already applied $(EXEEXT).
8495           if ($rcurs =~ /^\@.*\@$/ || $rcurs =~ /\$\(EXEEXT\)$/)
8496             {
8497               push (@one_binlist, $rcurs);
8498             }
8499           else
8500             {
8501               push (@one_binlist, $rcurs . '$(EXEEXT)');
8502             }
8503         }
8505       push (@condvals, $cond);
8506       push (@condvals, "@one_binlist");
8507     }
8509   macro_delete ($macro);
8510   while (@condvals)
8511     {
8512       my $cond = shift (@condvals);
8513       my @val = split (' ', shift (@condvals));
8514       define_pretty_variable ($macro, $cond, @val);
8515     }
8519 # @PREFIX
8520 # &am_primary_prefixes ($PRIMARY, $CAN_DIST, @PREFIXES)
8521 # -----------------------------------------------------
8522 # Find all variable prefixes that are used for install directories.  A
8523 # prefix `zar' qualifies iff:
8525 # * `zardir' is a variable.
8526 # * `zar_PRIMARY' is a variable.
8528 # As a side effect, it looks for misspellings.  It is an error to have
8529 # a variable ending in a "reserved" suffix whose prefix is unknown, eg
8530 # "bni_PROGRAMS".  However, unusual prefixes are allowed if a variable
8531 # of the same name (with "dir" appended) exists.  For instance, if the
8532 # variable "zardir" is defined, then "zar_PROGRAMS" becomes valid.
8533 # This is to provide a little extra flexibility in those cases which
8534 # need it.
8535 sub am_primary_prefixes ($$@)
8537   my ($primary, $can_dist, @prefixes) = @_;
8539   local $_;
8540   my %valid = map { $_ => 0 } @prefixes;
8541   $valid{'EXTRA'} = 0;
8542   foreach my $varname (keys %var_value)
8543     {
8544       # Automake is allowed to define variables that look like primaries
8545       # but which aren't.  E.g. INSTALL_sh_DATA.
8546       # Autoconf can also define variables like INSTALL_DATA, so
8547       # ignore all configure variables (at least those which are not
8548       # redefined in Makefile.am).
8549       # FIXME: We should make sure that these variables are not
8550       # conditionally defined (or else adjust the condition below).
8551       next
8552         if (exists $var_owner{$varname}
8553             && exists $var_owner{$varname}{'TRUE'}
8554             && $var_owner{$varname}{'TRUE'} != VAR_MAKEFILE);
8556       if ($varname =~ /^(nobase_)?(dist_|nodist_)?(.*)_$primary$/)
8557         {
8558           my ($base, $dist, $X) = ($1 || '', $2 || '', $3 || '');
8559           if ($dist ne '' && ! $can_dist)
8560             {
8561               err_var ($varname,
8562                        "invalid variable `$varname': `dist' is forbidden");
8563             }
8564           # Standard directories must be explicitely allowed.
8565           elsif (! defined $valid{$X} && exists $standard_prefix{$X})
8566             {
8567               err_var ($varname,
8568                        "`${X}dir' is not a legitimate directory " .
8569                        "for `$primary'");
8570             }
8571           # A not explicitely valid directory is allowed if Xdir is defined.
8572           elsif (! defined $valid{$X} &&
8573                  require_variables_for_macro ($varname, "`$varname' is used",
8574                                               "${X}dir"))
8575             {
8576               # Nothing to do.  Any error message has been output
8577               # by require_variables_for_macro.
8578             }
8579           else
8580             {
8581               # Ensure all extended prefixes are actually used.
8582               $valid{"$base$dist$X"} = 1;
8583             }
8584         }
8585     }
8587   # Return only those which are actually defined.
8588   return sort grep { variable_defined ($_ . '_' . $primary) } keys %valid;
8592 # Handle `where_HOW' variable magic.  Does all lookups, generates
8593 # install code, and possibly generates code to define the primary
8594 # variable.  The first argument is the name of the .am file to munge,
8595 # the second argument is the primary variable (eg HEADERS), and all
8596 # subsequent arguments are possible installation locations.  Returns
8597 # list of all values of all _HOW targets.
8599 # FIXME: this should be rewritten to be cleaner.  It should be broken
8600 # up into multiple functions.
8602 # Usage is: am_install_var (OPTION..., file, HOW, where...)
8603 sub am_install_var
8605     my (@args) = @_;
8607     my $do_require = 1;
8608     my $can_dist = 0;
8609     my $default_dist = 0;
8610     while (@args)
8611     {
8612         if ($args[0] eq '-noextra')
8613         {
8614             $do_require = 0;
8615         }
8616         elsif ($args[0] eq '-candist')
8617         {
8618             $can_dist = 1;
8619         }
8620         elsif ($args[0] eq '-defaultdist')
8621         {
8622             $default_dist = 1;
8623             $can_dist = 1;
8624         }
8625         elsif ($args[0] !~ /^-/)
8626         {
8627             last;
8628         }
8629         shift (@args);
8630     }
8632     my ($file, $primary, @prefix) = @args;
8634     # Now that configure substitutions are allowed in where_HOW
8635     # variables, it is an error to actually define the primary.  We
8636     # allow `JAVA', as it is customarily used to mean the Java
8637     # interpreter.  This is but one of several Java hacks.  Similarly,
8638     # `PYTHON' is customarily used to mean the Python interpreter.
8639     reject_var $primary, "`$primary' is an anachronism"
8640       unless $primary eq 'JAVA' || $primary eq 'PYTHON';
8642     # Get the prefixes which are valid and actually used.
8643     @prefix = am_primary_prefixes ($primary, $can_dist, @prefix);
8645     # If a primary includes a configure substitution, then the EXTRA_
8646     # form is required.  Otherwise we can't properly do our job.
8647     my $require_extra;
8649     my @used = ();
8650     my @result = ();
8652     # True if the iteration is the first one.  Used for instance to
8653     # output parts of the associated file only once.
8654     my $first = 1;
8655     foreach my $X (@prefix)
8656     {
8657         my $nodir_name = $X;
8658         my $one_name = $X . '_' . $primary;
8660         my $strip_subdir = 1;
8661         # If subdir prefix should be preserved, do so.
8662         if ($nodir_name =~ /^nobase_/)
8663           {
8664             $strip_subdir = 0;
8665             $nodir_name =~ s/^nobase_//;
8666           }
8668         # If files should be distributed, do so.
8669         my $dist_p = 0;
8670         if ($can_dist)
8671           {
8672             $dist_p = (($default_dist && $nodir_name !~ /^nodist_/)
8673                        || (! $default_dist && $nodir_name =~ /^dist_/));
8674             $nodir_name =~ s/^(dist|nodist)_//;
8675           }
8677         # Append actual contents of where_PRIMARY variable to
8678         # result.
8679         foreach my $rcurs (&variable_value_as_list_recursive ($one_name, 'all'))
8680           {
8681             # Skip configure substitutions.  Possibly bogus.
8682             if ($rcurs =~ /^\@.*\@$/)
8683               {
8684                 if ($nodir_name eq 'EXTRA')
8685                   {
8686                     err_var ($one_name,
8687                              "`$one_name' contains configure substitution, "
8688                              . "but shouldn't");
8689                   }
8690                 # Check here to make sure variables defined in
8691                 # configure.ac do not imply that EXTRA_PRIMARY
8692                 # must be defined.
8693                 elsif (! defined $configure_vars{$one_name})
8694                   {
8695                     $require_extra = $one_name
8696                       if $do_require;
8697                   }
8699                 next;
8700               }
8702             push (@result, $rcurs);
8703           }
8704         # A blatant hack: we rewrite each _PROGRAMS primary to include
8705         # EXEEXT.
8706         append_exeext ($one_name)
8707           if $primary eq 'PROGRAMS';
8708         # "EXTRA" shouldn't be used when generating clean targets,
8709         # all, or install targets.  We used to warn if EXTRA_FOO was
8710         # defined uselessly, but this was annoying.
8711         next
8712           if $nodir_name eq 'EXTRA';
8714         if ($nodir_name eq 'check')
8715           {
8716             push (@check, '$(' . $one_name . ')');
8717           }
8718         else
8719           {
8720             push (@used, '$(' . $one_name . ')');
8721           }
8723         # Is this to be installed?
8724         my $install_p = $nodir_name ne 'noinst' && $nodir_name ne 'check';
8726         # If so, with install-exec? (or install-data?).
8727         my $exec_p = ($nodir_name =~ /$EXEC_DIR_PATTERN/o);
8729         my $check_options_p = $install_p
8730                               && defined $options{'std-options'};
8732         # Singular form of $PRIMARY.
8733         (my $one_primary = $primary) =~ s/S$//;
8734         $output_rules .= &file_contents ($file,
8735                                          ('FIRST' => $first,
8737                                           'PRIMARY'     => $primary,
8738                                           'ONE_PRIMARY' => $one_primary,
8739                                           'DIR'         => $X,
8740                                           'NDIR'        => $nodir_name,
8741                                           'BASE'        => $strip_subdir,
8743                                           'EXEC'    => $exec_p,
8744                                           'INSTALL' => $install_p,
8745                                           'DIST'    => $dist_p,
8746                                           'CK-OPTS' => $check_options_p));
8748         $first = 0;
8749     }
8751     # The JAVA variable is used as the name of the Java interpreter.
8752     # The PYTHON variable is used as the name of the Python interpreter.
8753     if (@used && $primary ne 'JAVA' && $primary ne 'PYTHON')
8754     {
8755         # Define it.
8756         define_pretty_variable ($primary, '', @used);
8757         $output_vars .= "\n";
8758     }
8760     err_var ($require_extra,
8761              "`$require_extra' contains configure substitution,\n"
8762              . "but `EXTRA_$primary' not defined")
8763       if ($require_extra && ! variable_defined ('EXTRA_' . $primary));
8765     # Push here because PRIMARY might be configure time determined.
8766     push (@all, '$(' . $primary . ')')
8767         if @used && $primary ne 'JAVA' && $primary ne 'PYTHON';
8769     # Make the result unique.  This lets the user use conditionals in
8770     # a natural way, but still lets us program lazily -- we don't have
8771     # to worry about handling a particular object more than once.
8772     return uniq (sort @result);
8776 ################################################################
8778 # Each key in this hash is the name of a directory holding a
8779 # Makefile.in.  These variables are local to `is_make_dir'.
8780 my %make_dirs = ();
8781 my $make_dirs_set = 0;
8783 sub is_make_dir
8785     my ($dir) = @_;
8786     if (! $make_dirs_set)
8787     {
8788         foreach my $iter (@configure_input_files)
8789         {
8790             $make_dirs{dirname ($iter)} = 1;
8791         }
8792         # We also want to notice Makefile.in's.
8793         foreach my $iter (@other_input_files)
8794         {
8795             if ($iter =~ /Makefile\.in$/)
8796             {
8797                 $make_dirs{dirname ($iter)} = 1;
8798             }
8799         }
8800         $make_dirs_set = 1;
8801     }
8802     return defined $make_dirs{$dir};
8805 ################################################################
8807 # This variable is local to the "require file" set of functions.
8808 my @require_file_paths = ();
8811 # &maybe_push_required_file ($DIR, $FILE, $FULLFILE)
8812 # --------------------------------------------------
8813 # See if we want to push this file onto dist_common.  This function
8814 # encodes the rules for deciding when to do so.
8815 sub maybe_push_required_file
8817     my ($dir, $file, $fullfile) = @_;
8819     if ($dir eq $relative_dir)
8820     {
8821         push_dist_common ($file);
8822         return 1;
8823     }
8824     elsif ($relative_dir eq '.' && ! &is_make_dir ($dir))
8825     {
8826         # If we are doing the topmost directory, and the file is in a
8827         # subdir which does not have a Makefile, then we distribute it
8828         # here.
8829         push_dist_common ($fullfile);
8830         return 1;
8831     }
8832     return 0;
8836 # &require_file_internal ($WHERE, $MYSTRICT, @FILES)
8837 # --------------------------------------------------
8838 # Verify that the file must exist in the current directory.
8839 # $MYSTRICT is the strictness level at which this file becomes required.
8841 # Must set require_file_paths before calling this function.
8842 # require_file_paths is set to hold a single directory (the one in
8843 # which the first file was found) before return.
8844 sub require_file_internal ($$@)
8846     my ($where, $mystrict, @files) = @_;
8848     foreach my $file (@files)
8849     {
8850         my $fullfile;
8851         my $errdir;
8852         my $errfile;
8853         my $save_dir;
8855         my $found_it = 0;
8856         my $dangling_sym = 0;
8857         foreach my $dir (@require_file_paths)
8858         {
8859             $fullfile = $dir . "/" . $file;
8860             $errdir = $dir unless $errdir;
8862             # Use different name for "error filename".  Otherwise on
8863             # an error the bad file will be reported as eg
8864             # `../../install-sh' when using the default
8865             # config_aux_path.
8866             $errfile = $errdir . '/' . $file;
8868             if (-l $fullfile && ! -f $fullfile)
8869             {
8870                 $dangling_sym = 1;
8871                 last;
8872             }
8873             elsif (-f $fullfile)
8874             {
8875                 $found_it = 1;
8876                 maybe_push_required_file ($dir, $file, $fullfile);
8877                 $save_dir = $dir;
8878                 last;
8879             }
8880         }
8882         # `--force-missing' only has an effect if `--add-missing' is
8883         # specified.
8884         if ($found_it && (! $add_missing || ! $force_missing))
8885         {
8886             # Prune the path list.
8887             @require_file_paths = $save_dir;
8888         }
8889         else
8890         {
8891             # If we've already looked for it, we're done.  You might
8892             # wonder why we don't do this before searching for the
8893             # file.  If we do that, then something like
8894             # AC_OUTPUT(subdir/foo foo) will fail to put foo.in into
8895             # DIST_COMMON.
8896             if (! $found_it)
8897             {
8898                 next if defined $require_file_found{$fullfile};
8899                 $require_file_found{$fullfile} = 1;
8900             }
8902             if ($strictness >= $mystrict)
8903             {
8904                 if ($dangling_sym && $add_missing)
8905                 {
8906                     unlink ($fullfile);
8907                 }
8909                 my $trailer = '';
8910                 my $suppress = 0;
8912                 # Only install missing files according to our desired
8913                 # strictness level.
8914                 my $message = "required file `$errfile' not found";
8915                 if ($add_missing)
8916                 {
8917                     if (-f ("$libdir/$file"))
8918                     {
8919                         $suppress = 1;
8921                         # Install the missing file.  Symlink if we
8922                         # can, copy if we must.  Note: delete the file
8923                         # first, in case it is a dangling symlink.
8924                         $message = "installing `$errfile'";
8925                         # Windows Perl will hang if we try to delete a
8926                         # file that doesn't exist.
8927                         unlink ($errfile) if -f $errfile;
8928                         if ($symlink_exists && ! $copy_missing)
8929                         {
8930                             if (! symlink ("$libdir/$file", $errfile))
8931                             {
8932                                 $suppress = 0;
8933                                 $trailer = "; error while making link: $!";
8934                             }
8935                         }
8936                         elsif (system ('cp', "$libdir/$file", $errfile))
8937                         {
8938                             $suppress = 0;
8939                             $trailer = "\n    error while copying";
8940                         }
8941                     }
8943                     if (! maybe_push_required_file (dirname ($errfile),
8944                                                     $file, $errfile))
8945                     {
8946                         if (! $found_it)
8947                         {
8948                             # We have added the file but could not push it
8949                             # into DIST_COMMON (probably because this is
8950                             # an auxiliary file and we are not processing
8951                             # the top level Makefile). This is unfortunate,
8952                             # since it means we are using a file which is not
8953                             # distributed!
8955                             # Get Automake to be run again: on the second
8956                             # run the file will be found, and pushed into
8957                             # the toplevel DIST_COMMON automatically.
8958                             $automake_needs_to_reprocess_all_files = 1;
8959                         }
8960                     }
8962                     # Prune the path list.
8963                     @require_file_paths = &dirname ($errfile);
8964                 }
8966                 # If --force-missing was specified, and we have
8967                 # actually found the file, then do nothing.
8968                 next
8969                     if $found_it && $force_missing;
8971                 # If we couldn' install the file, but it is a target in
8972                 # the Makefile, don't print anything.  This allows files
8973                 # like README, AUTHORS, or THANKS to be generated.
8974                 next
8975                   if !$suppress && target_defined ($file);
8977                 msg ($suppress ? 'note' : 'error', $where, "$message$trailer");
8978             }
8979         }
8980     }
8983 # &require_file ($WHERE, $MYSTRICT, @FILES)
8984 # -----------------------------------------
8985 sub require_file ($$@)
8987     my ($where, $mystrict, @files) = @_;
8988     @require_file_paths = $relative_dir;
8989     require_file_internal ($where, $mystrict, @files);
8992 # &require_file_with_macro ($COND, $MACRO, $MYSTRICT, @FILES)
8993 # -----------------------------------------------------------
8994 sub require_file_with_macro ($$$@)
8996     my ($cond, $macro, $mystrict, @files) = @_;
8997     require_file ($var_location{$macro}{$cond}, $mystrict, @files);
9001 # &require_conf_file ($WHERE, $MYSTRICT, @FILES)
9002 # ----------------------------------------------
9003 # Looks in configuration path, as specified by AC_CONFIG_AUX_DIR.
9004 sub require_conf_file ($$@)
9006     my ($where, $mystrict, @files) = @_;
9007     @require_file_paths = @config_aux_path;
9008     require_file_internal ($where, $mystrict, @files);
9009     my $dir = $require_file_paths[0];
9010     @config_aux_path = @require_file_paths;
9011      # Avoid unsightly '/.'s.
9012     $config_aux_dir = '$(top_srcdir)' . ($dir eq '.' ? "" : "/$dir");
9016 # &require_conf_file_with_macro ($COND, $MACRO, $MYSTRICT, @FILES)
9017 # ----------------------------------------------------------------
9018 sub require_conf_file_with_macro ($$$@)
9020     my ($cond, $macro, $mystrict, @files) = @_;
9021     require_conf_file ($var_location{$macro}{$cond}, $mystrict, @files);
9024 ################################################################
9026 # &require_build_directory ($DIRECTORY)
9027 # ------------------------------------
9028 # Emit rules to create $DIRECTORY if needed, and return
9029 # the file that any target requiring this directory should be made
9030 # dependent upon.
9031 sub require_build_directory ($)
9033   my $directory = shift;
9034   my $dirstamp = "$directory/\$(am__dirstamp)";
9036   # Don't emit the rule twice.
9037   if (! defined $directory_map{$directory})
9038     {
9039       $directory_map{$directory} = 1;
9041       # Set a variable for the dirstamp basename.
9042       define_pretty_variable ('am__dirstamp', 'TRUE',
9043                               '$(am__leading_dot)dirstamp')
9044         unless variable_defined ('am__dirstamp');
9046       # Directory must be removed by `make distclean'.
9047       $clean_files{$dirstamp} = DIST_CLEAN;
9049       $output_rules .= ("$dirstamp:\n"
9050                         . "\t\@\$(mkinstalldirs) $directory\n"
9051                         . "\t\@: > $dirstamp\n");
9052     }
9054   return $dirstamp;
9057 # &require_build_directory_maybe ($FILE)
9058 # --------------------------------------
9059 # If $FILE lies in a subdirectory, emit a rule to create this
9060 # directory and return the file that $FILE should be made
9061 # dependent upon.  Otherwise, just return the empty string.
9062 sub require_build_directory_maybe ($)
9064     my $file = shift;
9065     my $directory = dirname ($file);
9067     if ($directory ne '.')
9068     {
9069         return require_build_directory ($directory);
9070     }
9071     else
9072     {
9073         return '';
9074     }
9077 ################################################################
9079 # Push a list of files onto dist_common.
9080 sub push_dist_common
9082   prog_error "push_dist_common run after handle_dist"
9083     if $handle_dist_run;
9084   macro_define ('DIST_COMMON', VAR_AUTOMAKE, '+', '', "@_", '');
9088 # Set strictness.
9089 sub set_strictness
9091   $strictness_name = $_[0];
9093   # FIXME: 'portability' warnings are currently disabled by default.
9094   # Eventually we want to turn them on in GNU and GNITS modes, but
9095   # we don't do this yet in Automake 1.7 to help the 1.6/1.7 transition.
9096   #
9097   # Indeed there would be only two ways to get rid of these new warnings:
9098   #  1. adjusting Makefile.am
9099   #     This is not always easy (or wanted).  Consider %-rules or
9100   #     $(function args) variables.
9101   #  2. using -Wno-portability
9102   #     This means there is no way to have the same Makefile.am
9103   #     working both with Automake 1.6 and 1.7 (since 1.6 does not
9104   #     understand -Wno-portability).
9105   #
9106   # In Automake 1.8 (or whatever it is called) we can turn these
9107   # warnings on, since -Wno-portability will not be an issue for
9108   # the 1.7/1.8 transition.
9109   if ($strictness_name eq 'gnu')
9110     {
9111       $strictness = GNU;
9112       setup_channel 'error-gnu', silent => 0;
9113       setup_channel 'error-gnu/warn', silent => 0, type => 'error';
9114       setup_channel 'error-gnits', silent => 1;
9115       # setup_channel 'portability', silent => 0;
9116       setup_channel 'gnu', silent => 0;
9117     }
9118   elsif ($strictness_name eq 'gnits')
9119     {
9120       $strictness = GNITS;
9121       setup_channel 'error-gnu', silent => 0;
9122       setup_channel 'error-gnu/warn', silent => 0, type => 'error';
9123       setup_channel 'error-gnits', silent => 0;
9124       # setup_channel 'portability', silent => 0;
9125       setup_channel 'gnu', silent => 0;
9126     }
9127   elsif ($strictness_name eq 'foreign')
9128     {
9129       $strictness = FOREIGN;
9130       setup_channel 'error-gnu', silent => 1;
9131       setup_channel 'error-gnu/warn', silent => 0, type => 'warning';
9132       setup_channel 'error-gnits', silent => 1;
9133       # setup_channel 'portability', silent => 1;
9134       setup_channel 'gnu', silent => 1;
9135     }
9136   else
9137     {
9138       prog_error "level `$strictness_name' not recognized\n";
9139     }
9143 ################################################################
9145 # Glob something.  Do this to avoid indentation screwups everywhere we
9146 # want to glob.  Gross!
9147 sub my_glob
9149     my ($pat) = @_;
9150     return <${pat}>;
9153 ################################################################
9155 # INTEGER
9156 # require_variables ($WHERE, $REASON, $COND, @VARIABLES)
9157 # ------------------------------------------------------
9158 # Make sure that each supplied variable is defined in $COND.
9159 # Otherwise, issue a warning.  If we know which macro can
9160 # define this variable, hint the user.
9161 # Return the number of undefined variables.
9162 sub require_variables ($$$@)
9164   my ($where, $reason, $cond, @vars) = @_;
9165   my $res = 0;
9166   $reason .= ' but ' unless $reason eq '';
9168  VARIABLE:
9169   foreach my $var (@vars)
9170     {
9171       # Nothing to do if the variable exists.  The $configure_vars test
9172       # needed for strange variables like AMDEPBACKSLASH or ANSI2KNR
9173       # that are AC_SUBST'ed but never macro_define'd.
9174       next VARIABLE
9175         if ((exists $var_value{$var} && exists $var_value{$var}{$cond})
9176             || exists $configure_vars{$var});
9178       my @undef_cond = variable_not_always_defined_in_cond $var, $cond;
9179       next VARIABLE
9180         unless @undef_cond;
9182       my $text = "$reason`$var' is undefined\n";
9183       if (@undef_cond && $undef_cond[0] ne 'TRUE')
9184         {
9185           $text .= ("in the following conditions:\n  "
9186                     . join ("\n  ", @undef_cond));
9187         }
9189       ++$res;
9191       if (exists $am_macro_for_var{$var})
9192         {
9193           $text .= "\nThe usual way to define `$var' is to add "
9194             . "`$am_macro_for_var{$var}'\nto `$configure_ac' and run "
9195             . "`aclocal' and `autoconf' again.";
9196         }
9197       elsif (exists $ac_macro_for_var{$var})
9198         {
9199           $text .= "\nThe usual way to define `$var' is to add "
9200             . "`$ac_macro_for_var{$var}'\nto `$configure_ac' and run "
9201             . "`autoconf' again.";
9202         }
9204       error $where, $text, uniq_scope => US_GLOBAL;
9205     }
9206   return $res;
9209 # INTEGER
9210 # require_variables_for_macro ($MACRO, $REASON, @VARIABLES)
9211 # ---------------------------------------------------------
9212 # Same as require_variables, but take a macro mame as first argument.
9213 sub require_variables_for_macro ($$@)
9215   my ($macro, $reason, @args) = @_;
9216   for my $cond (keys %{$var_value{$macro}})
9217     {
9218       return require_variables ($var_location{$macro}{$cond}, $reason,
9219                                 $cond, @args);
9220     }
9223 # Print usage information.
9224 sub usage ()
9226     print "Usage: $0 [OPTION] ... [Makefile]...
9228 Generate Makefile.in for configure from Makefile.am.
9230 Operation modes:
9231       --help               print this help, then exit
9232       --version            print version number, then exit
9233   -v, --verbose            verbosely list files processed
9234       --no-force           only update Makefile.in's that are out of date
9235   -W, --warnings=CATEGORY  report the warnings falling in CATEGORY
9237 Dependency tracking:
9238   -i, --ignore-deps      disable dependency tracking code
9239       --include-deps     enable dependency tracking code
9241 Flavors:
9242       --cygnus           assume program is part of Cygnus-style tree
9243       --foreign          set strictness to foreign
9244       --gnits            set strictness to gnits
9245       --gnu              set strictness to gnu
9247 Library files:
9248   -a, --add-missing      add missing standard files to package
9249       --libdir=DIR       directory storing library files
9250   -c, --copy             with -a, copy missing files (default is symlink)
9251   -f, --force-missing    force update of standard files
9253 Warning categories include:
9254   `gnu'           GNU coding standards (default in gnu and gnits modes)
9255   `obsolete'      obsolete features or constructions
9256   `portability'   portability issues
9257   `syntax'        dubious syntactic constructs (default)
9258   `unsupported'   unsupported or incomplete features (default)
9259   `all'           all the warnings
9260   `no-CATEGORY'   turn off warnings in CATEGORY
9261   `none'          turn off all the warnings
9262   `error'         treat warnings as errors
9265     my ($last, @lcomm);
9266     $last = '';
9267     foreach my $iter (sort ((@common_files, @common_sometimes)))
9268     {
9269         push (@lcomm, $iter) unless $iter eq $last;
9270         $last = $iter;
9271     }
9273     my @four;
9274     print "\nFiles which are automatically distributed, if found:\n";
9275     format USAGE_FORMAT =
9276   @<<<<<<<<<<<<<<<<   @<<<<<<<<<<<<<<<<   @<<<<<<<<<<<<<<<<   @<<<<<<<<<<<<<<<<
9277   $four[0],           $four[1],           $four[2],           $four[3]
9279     $~ = "USAGE_FORMAT";
9281     my $cols = 4;
9282     my $rows = int(@lcomm / $cols);
9283     my $rest = @lcomm % $cols;
9285     if ($rest)
9286     {
9287         $rows++;
9288     }
9289     else
9290     {
9291         $rest = $cols;
9292     }
9294     for (my $y = 0; $y < $rows; $y++)
9295     {
9296         @four = ("", "", "", "");
9297         for (my $x = 0; $x < $cols; $x++)
9298         {
9299             last if $y + 1 == $rows && $x == $rest;
9301             my $idx = (($x > $rest)
9302                        ?  ($rows * $rest + ($rows - 1) * ($x - $rest))
9303                        : ($rows * $x));
9305             $idx += $y;
9306             $four[$x] = $lcomm[$idx];
9307         }
9308         write;
9309     }
9311     print "\nReport bugs to <bug-automake\@gnu.org>.\n";
9313     # --help always returns 0 per GNU standards.
9314     exit 0;
9318 # &version ()
9319 # -----------
9320 # Print version information
9321 sub version ()
9323   print <<EOF;
9324 automake (GNU $PACKAGE) $VERSION
9325 Written by Tom Tromey <tromey\@redhat.com>.
9327 Copyright 2003 Free Software Foundation, Inc.
9328 This is free software; see the source for copying conditions.  There is NO
9329 warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
9331   # --version always returns 0 per GNU standards.
9332   exit 0;
9335 ### Setup "GNU" style for perl-mode and cperl-mode.
9336 ## Local Variables:
9337 ## perl-indent-level: 2
9338 ## perl-continued-statement-offset: 2
9339 ## perl-continued-brace-offset: 0
9340 ## perl-brace-offset: 0
9341 ## perl-brace-imaginary-offset: 0
9342 ## perl-label-offset: -2
9343 ## cperl-indent-level: 2
9344 ## cperl-brace-offset: 0
9345 ## cperl-continued-brace-offset: 0
9346 ## cperl-label-offset: -2
9347 ## cperl-extra-newline-before-brace: t
9348 ## cperl-merge-trailing-else: nil
9349 ## cperl-continued-statement-offset: 2
9350 ## End: