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