* lib/mdate-sh: Find out which column of the ls -l output contains
[automake.git] / automake.in
blob624c6cde0bc229eb9354d101f2de060999f57713
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   # Do not depend on the build rules if ELCFILES is empty.
5103   # This is necessary because overriding ELCFILES= is a documented
5104   # idiom to disable byte-compilation.
5105   if (variable_value ('ELCFILES'))
5106     {
5107       # It's important that all depends on elc-stamp so that
5108       # all .elc files get recompiled whenever a .el changes.
5109       # It's important that all depends on $(ELCFILES) so that
5110       # we can recover if any of them is deleted.
5111       push (@all, 'elc-stamp', '$(ELCFILES)');
5112     }
5114   require_variables ("$am_file.am", "Emacs Lisp sources seen", 'TRUE',
5115                      'EMACS', 'lispdir');
5116   require_conf_file ("$am_file.am", FOREIGN, 'elisp-comp');
5117   &define_variable ('elisp_comp', $config_aux_dir . '/elisp-comp');
5120 # Handle Python
5121 sub handle_python
5123   my @pyfiles = &am_install_var ('-defaultdist', 'python', 'PYTHON',
5124                                  'noinst');
5125   return if ! @pyfiles;
5127   require_variables ("$am_file.am", "Python sources seen", 'TRUE',
5128                      'PYTHON');
5129   require_conf_file ("$am_file.am", FOREIGN, 'py-compile');
5130   &define_variable ('py_compile', $config_aux_dir . '/py-compile');
5133 # Handle Java.
5134 sub handle_java
5136     my @sourcelist = &am_install_var ('-candist',
5137                                       'java', 'JAVA',
5138                                       'java', 'noinst', 'check');
5139     return if ! @sourcelist;
5141     my @prefix = am_primary_prefixes ('JAVA', 1,
5142                                       'java', 'noinst', 'check');
5144     my $dir;
5145     foreach my $curs (@prefix)
5146       {
5147         next
5148           if $curs eq 'EXTRA';
5150         err_var "${curs}_JAVA", "multiple _JAVA primaries in use"
5151           if defined $dir;
5152         $dir = $curs;
5153       }
5156     push (@all, 'class' . $dir . '.stamp');
5160 # Handle some of the minor options.
5161 sub handle_minor_options
5163   if (defined $options{'readme-alpha'})
5164     {
5165       if ($relative_dir eq '.')
5166         {
5167           if ($package_version !~ /^$GNITS_VERSION_PATTERN$/)
5168             {
5169               msg ('error-gnits', $package_version_location,
5170                    "version `$package_version' doesn't follow " .
5171                    "Gnits standards");
5172             }
5173           if (defined $1 && -f 'README-alpha')
5174             {
5175               # This means we have an alpha release.  See
5176               # GNITS_VERSION_PATTERN for details.
5177               require_file_with_macro ('TRUE', 'AUTOMAKE_OPTIONS',
5178                                        FOREIGN, 'README-alpha');
5179             }
5180         }
5181     }
5184 ################################################################
5186 # ($OUTPUT, @INPUTS)
5187 # &split_config_file_spec ($SPEC)
5188 # -------------------------------
5189 # Decode the Autoconf syntax for config files (files, headers, links
5190 # etc.).
5191 sub split_config_file_spec ($)
5193   my ($spec) = @_;
5194   my ($output, @inputs) = split (/:/, $spec);
5196   push @inputs, "$output.in"
5197     unless @inputs;
5199   return ($output, @inputs);
5203 my %make_list;
5205 # &scan_autoconf_config_files ($CONFIG-FILES)
5206 # -------------------------------------------
5207 # Study $CONFIG-FILES which is the first argument to AC_CONFIG_FILES
5208 # (or AC_OUTPUT).
5209 sub scan_autoconf_config_files
5211     my ($config_files) = @_;
5212     # Look at potential Makefile.am's.
5213     foreach (split ' ', $config_files)
5214     {
5215         # Must skip empty string for Perl 4.
5216         next if $_ eq "\\" || $_ eq '';
5218         # Handle $local:$input syntax.  Note that we ignore
5219         # every input file past the first, though we keep
5220         # those around for later.
5221         my ($local, $input, @rest) = split (/:/);
5222         if (! $input)
5223         {
5224             $input = $local;
5225         }
5226         else
5227         {
5228             # FIXME: should be error if .in is missing.
5229             $input =~ s/\.in$//;
5230         }
5232         if (-f $input . '.am')
5233         {
5234             # We have a file that automake should generate.
5235             $make_list{$input} = join (':', ($local, @rest));
5236         }
5237         else
5238         {
5239             # We have a file that automake should cause to be
5240             # rebuilt, but shouldn't generate itself.
5241             push (@other_input_files, $_);
5242         }
5243     }
5247 # &scan_autoconf_traces ($FILENAME)
5248 # ---------------------------------
5249 sub scan_autoconf_traces ($)
5251   my ($filename) = @_;
5253   my @traced = qw(AC_CANONICAL_HOST
5254                   AC_CANONICAL_SYSTEM
5255                   AC_CONFIG_AUX_DIR
5256                   AC_CONFIG_FILES
5257                   AC_CONFIG_HEADERS
5258                   AC_INIT
5259                   AC_LIBSOURCE
5260                   AC_SUBST
5261                   AM_AUTOMAKE_VERSION
5262                   AM_CONDITIONAL
5263                   AM_GNU_GETTEXT
5264                   AM_INIT_AUTOMAKE
5265                   AM_MAINTAINER_MODE
5266                   AM_PROG_CC_C_O);
5268   my $traces = ($ENV{AUTOCONF} || 'autoconf') . " ";
5270   # Use a separator unlikely to be used, not `:', the default, which
5271   # has a precise meaning for AC_CONFIG_FILES and so on.
5272   $traces .= join (' ',
5273                    map { "--trace=$_" . ':\$f:\$l::\$n::\${::}%' } @traced);
5275   my $tracefh = new Automake::XFile ("$traces $filename |");
5276   verb "reading $traces";
5278   while ($_ = $tracefh->getline)
5279     {
5280       chomp;
5281       my ($here, @args) = split /::/;
5282       my $macro = $args[0];
5284       # Alphabetical ordering please.
5285       if ($macro eq 'AC_CANONICAL_HOST')
5286         {
5287           if (! $seen_canonical)
5288             {
5289               $seen_canonical = AC_CANONICAL_HOST;
5290               $canonical_location = $here;
5291             };
5292         }
5293       elsif ($macro eq 'AC_CANONICAL_SYSTEM')
5294         {
5295           $seen_canonical = AC_CANONICAL_SYSTEM;
5296           $canonical_location = $here;
5297         }
5298       elsif ($macro eq 'AC_CONFIG_AUX_DIR')
5299         {
5300           @config_aux_path = $args[1];
5301           $config_aux_dir_set_in_configure_in = 1;
5302         }
5303       elsif ($macro eq 'AC_CONFIG_FILES')
5304         {
5305           # Look at potential Makefile.am's.
5306           $ac_config_files_location = $here;
5307           &scan_autoconf_config_files ($args[1]);
5308         }
5309       elsif ($macro eq 'AC_CONFIG_HEADERS')
5310         {
5311           $config_header_location = $here;
5312           push @config_headers, split (' ', $args[1]);
5313         }
5314       elsif ($macro eq 'AC_INIT')
5315         {
5316           if (defined $args[2])
5317             {
5318               $package_version = $args[2];
5319               $package_version_location = $here;
5320             }
5321         }
5322       elsif ($macro eq 'AC_LIBSOURCE')
5323         {
5324           $libsources{$args[1]} = $here;
5325         }
5326       elsif ($macro eq 'AC_SUBST')
5327         {
5328           # Just check for alphanumeric in AC_SUBST.  If you do
5329           # AC_SUBST(5), then too bad.
5330           $configure_vars{$args[1]} = $here
5331             if $args[1] =~ /^\w+$/;
5332         }
5333       elsif ($macro eq 'AM_AUTOMAKE_VERSION')
5334         {
5335           error ($here,
5336                  "version mismatch.  This is Automake $VERSION,\n" .
5337                  "but the definition used by this AM_INIT_AUTOMAKE\n" .
5338                  "comes from Automake $args[1].  You should recreate\n" .
5339                  "aclocal.m4 with aclocal and run automake again.\n")
5340             if $VERSION ne $args[1];
5342           $seen_automake_version = 1;
5343         }
5344       elsif ($macro eq 'AM_CONDITIONAL')
5345         {
5346           $configure_cond{$args[1]} = $here;
5347         }
5348       elsif ($macro eq 'AM_GNU_GETTEXT')
5349         {
5350           $seen_gettext = $here;
5351           $ac_gettext_location = $here;
5352           $seen_gettext_external = grep ($_ eq 'external', @args);
5353         }
5354       elsif ($macro eq 'AM_INIT_AUTOMAKE')
5355         {
5356           $seen_init_automake = $here;
5357           if (defined $args[2])
5358             {
5359               $package_version = $args[2];
5360               $package_version_location = $here;
5361             }
5362           elsif (defined $args[1])
5363             {
5364               $global_options = $args[1];
5365             }
5366         }
5367       elsif ($macro eq 'AM_MAINTAINER_MODE')
5368         {
5369           $seen_maint_mode = $here;
5370         }
5371       elsif ($macro eq 'AM_PROG_CC_C_O')
5372         {
5373           $seen_cc_c_o = $here;
5374         }
5375    }
5379 # &scan_autoconf_files ()
5380 # -----------------------
5381 # Check whether we use `configure.ac' or `configure.in'.
5382 # Scan it (and possibly `aclocal.m4') for interesting things.
5383 # We must scan aclocal.m4 because there might be AC_SUBSTs and such there.
5384 sub scan_autoconf_files
5386     # Reinitialize libsources here.  This isn't really necessary,
5387     # since we currently assume there is only one configure.ac.  But
5388     # that won't always be the case.
5389     %libsources = ();
5391     $configure_ac = find_configure_ac;
5392     fatal "`configure.ac' or `configure.in' is required\n"
5393         if !$configure_ac;
5395     scan_autoconf_traces ($configure_ac);
5397     # Set input and output files if not specified by user.
5398     if (! @input_files)
5399     {
5400         @input_files = sort keys %make_list;
5401         %output_files = %make_list;
5402     }
5404     @configure_input_files = sort keys %make_list;
5406     if (! $seen_init_automake)
5407       {
5408         err_ac "`AM_INIT_AUTOMAKE' must be used";
5409       }
5410     else
5411       {
5412         if (! $seen_automake_version)
5413           {
5414             if (-f 'aclocal.m4')
5415               {
5416                 error ($seen_init_automake,
5417                        "your implementation of AM_INIT_AUTOMAKE comes from " .
5418                        "an\nold Automake version.  You should recreate " .
5419                        "aclocal.m4\nwith aclocal and run automake again.\n");
5420               }
5421             else
5422               {
5423                 error ($seen_init_automake,
5424                        "no proper implementation of AM_INIT_AUTOMAKE was " .
5425                        "found,\nprobably because aclocal.m4 is missing...\n" .
5426                        "You should run aclocal to create this file, then\n" .
5427                        "run automake again.\n");
5428               }
5429           }
5430       }
5432     # Look for some files we need.  Always check for these.  This
5433     # check must be done for every run, even those where we are only
5434     # looking at a subdir Makefile.  We must set relative_dir so that
5435     # the file-finding machinery works.
5436     # FIXME: Is this broken because it needs dynamic scopes.
5437     # My tests seems to show it's not the case.
5438     $relative_dir = '.';
5439     require_conf_file ($configure_ac, FOREIGN,
5440                        'install-sh', 'mkinstalldirs', 'missing');
5441     err_am "`install.sh' is an anachronism; use `install-sh' instead"
5442       if -f $config_aux_path[0] . '/install.sh';
5444     # Preserve dist_common for later.
5445     $configure_dist_common = variable_value ('DIST_COMMON', 'TRUE') || '';
5448 ################################################################
5450 # Set up for Cygnus mode.
5451 sub check_cygnus
5453   return unless $cygnus_mode;
5455   &set_strictness ('foreign');
5456   $options{'no-installinfo'} = 1;
5457   $options{'no-dependencies'} = 1;
5458   $use_dependencies = 0;
5460   err_ac "`AM_MAINTAINER_MODE' required when --cygnus specified"
5461     if !$seen_maint_mode;
5464 # Do any extra checking for GNU standards.
5465 sub check_gnu_standards
5467   if ($relative_dir eq '.')
5468     {
5469       # In top level (or only) directory.
5471       # Accept one of these three licenses; default to COPYING.
5472       my $license = 'COPYING';
5473       foreach (qw /COPYING.LIB COPYING.LESSER/)
5474         {
5475           $license = $_ if -f $_;
5476         }
5477       require_file ("$am_file.am", GNU, $license,
5478                     qw/INSTALL NEWS README AUTHORS ChangeLog/);
5479     }
5481   for my $opt ('no-installman', 'no-installinfo')
5482     {
5483       msg_var ('error-gnu', 'AUTOMAKE_OPTIONS',
5484                "option `$opt' disallowed by GNU standards")
5485         if (defined $options{$opt});
5486     }
5489 # Do any extra checking for GNITS standards.
5490 sub check_gnits_standards
5492   if ($relative_dir eq '.')
5493     {
5494       # In top level (or only) directory.
5495       require_file ("$am_file.am", GNITS, 'THANKS');
5496     }
5499 ################################################################
5501 # Functions to handle files of each language.
5503 # Each `lang_X_rewrite($DIRECTORY, $BASE, $EXT)' function follows a
5504 # simple formula: Return value is LANG_SUBDIR if the resulting object
5505 # file should be in a subdir if the source file is, LANG_PROCESS if
5506 # file is to be dealt with, LANG_IGNORE otherwise.
5508 # Much of the actual processing is handled in
5509 # handle_single_transform_list.  These functions exist so that
5510 # auxiliary information can be recorded for a later cleanup pass.
5511 # Note that the calls to these functions are computed, so don't bother
5512 # searching for their precise names in the source.
5514 # This is just a convenience function that can be used to determine
5515 # when a subdir object should be used.
5516 sub lang_sub_obj
5518     return defined $options{'subdir-objects'} ? LANG_SUBDIR : LANG_PROCESS;
5521 # Rewrite a single C source file.
5522 sub lang_c_rewrite
5524   my ($directory, $base, $ext) = @_;
5526   if (defined $options{'ansi2knr'} && $base =~ /_$/)
5527     {
5528       # FIXME: include line number in error.
5529       err_am "C source file `$base.c' would be deleted by ansi2knr rules";
5530     }
5532   my $r = LANG_PROCESS;
5533   if (defined $options{'subdir-objects'})
5534     {
5535       $r = LANG_SUBDIR;
5536       $base = $directory . '/' . $base
5537         unless $directory eq '.' || $directory eq '';
5539       err_am ("C objects in subdir but `AM_PROG_CC_C_O' "
5540               . "not in `$configure_ac'",
5541               uniq_scope => US_GLOBAL)
5542         unless $seen_cc_c_o;
5544       require_conf_file ("$am_file.am", FOREIGN, 'compile');
5546       # In this case we already have the directory information, so
5547       # don't add it again.
5548       $de_ansi_files{$base} = '';
5549     }
5550   else
5551     {
5552       $de_ansi_files{$base} = (($directory eq '.' || $directory eq '')
5553                                ? ''
5554                                : "$directory/");
5555     }
5557     return $r;
5560 # Rewrite a single C++ source file.
5561 sub lang_cxx_rewrite
5563     return &lang_sub_obj;
5566 # Rewrite a single header file.
5567 sub lang_header_rewrite
5569     # Header files are simply ignored.
5570     return LANG_IGNORE;
5573 # Rewrite a single yacc file.
5574 sub lang_yacc_rewrite
5576     my ($directory, $base, $ext) = @_;
5578     my $r = &lang_sub_obj;
5579     (my $newext = $ext) =~ tr/y/c/;
5580     return ($r, $newext);
5583 # Rewrite a single yacc++ file.
5584 sub lang_yaccxx_rewrite
5586     my ($directory, $base, $ext) = @_;
5588     my $r = &lang_sub_obj;
5589     (my $newext = $ext) =~ tr/y/c/;
5590     return ($r, $newext);
5593 # Rewrite a single lex file.
5594 sub lang_lex_rewrite
5596     my ($directory, $base, $ext) = @_;
5598     my $r = &lang_sub_obj;
5599     (my $newext = $ext) =~ tr/l/c/;
5600     return ($r, $newext);
5603 # Rewrite a single lex++ file.
5604 sub lang_lexxx_rewrite
5606     my ($directory, $base, $ext) = @_;
5608     my $r = &lang_sub_obj;
5609     (my $newext = $ext) =~ tr/l/c/;
5610     return ($r, $newext);
5613 # Rewrite a single assembly file.
5614 sub lang_asm_rewrite
5616     return &lang_sub_obj;
5619 # Rewrite a single Fortran 77 file.
5620 sub lang_f77_rewrite
5622     return LANG_PROCESS;
5625 # Rewrite a single preprocessed Fortran 77 file.
5626 sub lang_ppf77_rewrite
5628     return LANG_PROCESS;
5631 # Rewrite a single ratfor file.
5632 sub lang_ratfor_rewrite
5634     return LANG_PROCESS;
5637 # Rewrite a single Objective C file.
5638 sub lang_objc_rewrite
5640     return &lang_sub_obj;
5643 # Rewrite a single Java file.
5644 sub lang_java_rewrite
5646     return LANG_SUBDIR;
5649 # The lang_X_finish functions are called after all source file
5650 # processing is done.  Each should handle defining rules for the
5651 # language, etc.  A finish function is only called if a source file of
5652 # the appropriate type has been seen.
5654 sub lang_c_finish
5656     # Push all libobjs files onto de_ansi_files.  We actually only
5657     # push files which exist in the current directory, and which are
5658     # genuine source files.
5659     foreach my $file (keys %libsources)
5660     {
5661         if ($file =~ /^(.*)\.[cly]$/ && -f "$relative_dir/$file")
5662         {
5663             $de_ansi_files{$1} = ''
5664         }
5665     }
5667     if (defined $options{'ansi2knr'} && keys %de_ansi_files)
5668     {
5669         # Make all _.c files depend on their corresponding .c files.
5670         my @objects;
5671         foreach my $base (sort keys %de_ansi_files)
5672         {
5673             # Each _.c file must depend on ansi2knr; otherwise it
5674             # might be used in a parallel build before it is built.
5675             # We need to support files in the srcdir and in the build
5676             # dir (because these files might be auto-generated.  But
5677             # we can't use $< -- some makes only define $< during a
5678             # suffix rule.
5679             my $ansfile = $de_ansi_files{$base} . $base . '.c';
5680             $output_rules .= ($base . "_.c: $ansfile \$(ANSI2KNR)\n\t"
5681                               . '$(CPP) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) '
5682                               . '`if test -f $(srcdir)/' . $ansfile
5683                               . '; then echo $(srcdir)/' . $ansfile
5684                               . '; else echo ' . $ansfile . '; fi` '
5685                               . "| sed 's/^# \\([0-9]\\)/#line \\1/' "
5686                               . '| $(ANSI2KNR) > $@'
5687                               # If ansi2knr fails then we shouldn't
5688                               # create the _.c file
5689                               . " || rm -f \$\@\n");
5690             push (@objects, $base . '_.$(OBJEXT)');
5691             push (@objects, $base . '_.lo')
5692               if variable_defined ('LIBTOOL');
5693         }
5695         # Make all _.o (and _.lo) files depend on ansi2knr.
5696         # Use a sneaky little hack to make it print nicely.
5697         &pretty_print_rule ('', '', @objects, ':', '$(ANSI2KNR)');
5698     }
5701 # This is a yacc helper which is called whenever we have decided to
5702 # compile a yacc file.
5703 sub lang_yacc_target_hook
5705     my ($self, $aggregate, $output, $input) = @_;
5707     my $flag = $aggregate . "_YFLAGS";
5708     if ((variable_defined ($flag)
5709          && &variable_value ($flag) =~ /$DASH_D_PATTERN/o)
5710         || (variable_defined ('YFLAGS')
5711             && &variable_value ('YFLAGS') =~ /$DASH_D_PATTERN/o))
5712     {
5713         (my $output_base = $output) =~ s/$KNOWN_EXTENSIONS_PATTERN$//;
5714         my $header = $output_base . '.h';
5716         # Found a `-d' that applies to the compilation of this file.
5717         # Add a dependency for the generated header file, and arrange
5718         # for that file to be included in the distribution.
5719         # FIXME: this fails for `nodist_*_SOURCES'.
5720         $output_rules .= ("${header}: $output\n"
5721                           # Recover from removal of $header
5722                           . "\t\@if test ! -f \$@; then \\\n"
5723                           . "\t  rm -f $output; \\\n"
5724                           . "\t  \$(MAKE) $output; \\\n"
5725                           . "\telse :; fi\n");
5726         &push_dist_common ($header);
5727         # If the files are built in the build directory, then we want
5728         # to remove them with `make clean'.  If they are in srcdir
5729         # they shouldn't be touched.  However, we can't determine this
5730         # statically, and the GNU rules say that yacc/lex output files
5731         # should be removed by maintainer-clean.  So that's what we
5732         # do.
5733         $clean_files{$header} = MAINTAINER_CLEAN;
5734     }
5735     # Erase $OUTPUT on `make maintainer-clean' (by GNU standards).
5736     # See the comment above for $HEADER.
5737     $clean_files{$output} = MAINTAINER_CLEAN;
5740 # This is a lex helper which is called whenever we have decided to
5741 # compile a lex file.
5742 sub lang_lex_target_hook
5744     my ($self, $aggregate, $output, $input) = @_;
5745     # If the files are built in the build directory, then we want to
5746     # remove them with `make clean'.  If they are in srcdir they
5747     # shouldn't be touched.  However, we can't determine this
5748     # statically, and the GNU rules say that yacc/lex output files
5749     # should be removed by maintainer-clean.  So that's what we do.
5750     $clean_files{$output} = MAINTAINER_CLEAN;
5753 # This is a helper for both lex and yacc.
5754 sub yacc_lex_finish_helper
5756     return if defined $language_scratch{'lex-yacc-done'};
5757     $language_scratch{'lex-yacc-done'} = 1;
5759     # If there is more than one distinct yacc (resp lex) source file
5760     # in a given directory, then the `ylwrap' program is required to
5761     # allow parallel builds to work correctly.  FIXME: for now, no
5762     # line number.
5763     require_conf_file ($configure_ac, FOREIGN, 'ylwrap');
5764     if ($config_aux_dir_set_in_configure_in)
5765     {
5766         &define_variable ('YLWRAP', $config_aux_dir . "/ylwrap");
5767     }
5768     else
5769     {
5770         &define_variable ('YLWRAP', '$(top_srcdir)/ylwrap');
5771     }
5774 sub lang_yacc_finish
5776   return if defined $language_scratch{'yacc-done'};
5777   $language_scratch{'yacc-done'} = 1;
5779   reject_var 'YACCFLAGS', "`YACCFLAGS' obsolete; use `YFLAGS' instead";
5781   &yacc_lex_finish_helper
5782     if count_files_for_language ('yacc') > 1;
5786 sub lang_lex_finish
5788   return if defined $language_scratch{'lex-done'};
5789   $language_scratch{'lex-done'} = 1;
5791   &yacc_lex_finish_helper
5792     if count_files_for_language ('lex') > 1;
5796 # Given a hash table of linker names, pick the name that has the most
5797 # precedence.  This is lame, but something has to have global
5798 # knowledge in order to eliminate the conflict.  Add more linkers as
5799 # required.
5800 sub resolve_linker
5802     my (%linkers) = @_;
5804     foreach my $l (qw(GCJLINK CXXLINK F77LINK OBJCLINK))
5805     {
5806         return $l if defined $linkers{$l};
5807     }
5808     return 'LINK';
5811 # Called to indicate that an extension was used.
5812 sub saw_extension
5814     my ($ext) = @_;
5815     if (! defined $extension_seen{$ext})
5816     {
5817         $extension_seen{$ext} = 1;
5818     }
5819     else
5820     {
5821         ++$extension_seen{$ext};
5822     }
5825 # Return the number of files seen for a given language.  Knows about
5826 # special cases we care about.  FIXME: this is hideous.  We need
5827 # something that involves real language objects.  For instance yacc
5828 # and yaccxx could both derive from a common yacc class which would
5829 # know about the strange ylwrap requirement.  (Or better yet we could
5830 # just not support legacy yacc!)
5831 sub count_files_for_language
5833     my ($name) = @_;
5835     my @names;
5836     if ($name eq 'yacc' || $name eq 'yaccxx')
5837     {
5838         @names = ('yacc', 'yaccxx');
5839     }
5840     elsif ($name eq 'lex' || $name eq 'lexxx')
5841     {
5842         @names = ('lex', 'lexxx');
5843     }
5844     else
5845     {
5846         @names = ($name);
5847     }
5849     my $r = 0;
5850     foreach $name (@names)
5851     {
5852         my $lang = $languages{$name};
5853         foreach my $ext (@{$lang->extensions})
5854         {
5855             $r += $extension_seen{$ext}
5856                 if defined $extension_seen{$ext};
5857         }
5858     }
5860     return $r
5863 # Called to ask whether source files have been seen . If HEADERS is 1,
5864 # headers can be included.
5865 sub saw_sources_p
5867     my ($headers) = @_;
5869     # count all the sources
5870     my $count = 0;
5871     foreach my $val (values %extension_seen)
5872     {
5873         $count += $val;
5874     }
5876     if (!$headers)
5877     {
5878         $count -= count_files_for_language ('header');
5879     }
5881     return $count > 0;
5885 # register_language (%ATTRIBUTE)
5886 # ------------------------------
5887 # Register a single language.
5888 # Each %ATTRIBUTE is of the form ATTRIBUTE => VALUE.
5889 sub register_language (%)
5891   my (%option) = @_;
5893   # Set the defaults.
5894   $option{'ansi'} = 0
5895     unless defined $option{'ansi'};
5896   $option{'autodep'} = 'no'
5897     unless defined $option{'autodep'};
5898   $option{'linker'} = ''
5899     unless defined $option{'linker'};
5900   $option{'flags'} = []
5901     unless defined $option{'flags'};
5902   $option{'output_extensions'} = sub { return ( '.$(OBJEXT)', '.lo' ) }
5903     unless defined $option{'output_extensions'};
5905   my $lang = new Language (%option);
5907   # Fill indexes.
5908   grep ($extension_map{$_} = $lang->name, @{$lang->extensions});
5909   $languages{$lang->name} = $lang;
5911   # Update the pattern of known extensions.
5912   accept_extensions (@{$lang->extensions});
5914   # Upate the $suffix_rule map.
5915   foreach my $suffix (@{$lang->extensions})
5916     {
5917       foreach my $dest (&{$lang->output_extensions} ($suffix))
5918         {
5919           &register_suffix_rule ('internal', $suffix, $dest);
5920         }
5921     }
5924 # derive_suffix ($EXT, $OBJ)
5925 # --------------------------
5926 # This function is used to find a path from a user-specified suffix $EXT
5927 # to $OBJ or to some other suffix we recognize internally, eg `cc'.
5928 sub derive_suffix ($$)
5930   my ($source_ext, $obj) = @_;
5932   while (! $extension_map{$source_ext}
5933          && $source_ext ne $obj
5934          && exists $suffix_rules->{$source_ext}
5935          && exists $suffix_rules->{$source_ext}{$obj})
5936     {
5937       $source_ext = $suffix_rules->{$source_ext}{$obj}[0];
5938     }
5940   return $source_ext;
5944 ################################################################
5946 # Pretty-print something.  HEAD is what should be printed at the
5947 # beginning of the first line, FILL is what should be printed at the
5948 # beginning of every subsequent line.
5949 sub pretty_print_internal
5951     my ($head, $fill, @values) = @_;
5953     my $column = length ($head);
5954     my $result = $head;
5956     # Fill length is number of characters.  However, each Tab
5957     # character counts for eight.  So we count the number of Tabs and
5958     # multiply by 7.
5959     my $fill_length = length ($fill);
5960     $fill_length += 7 * ($fill =~ tr/\t/\t/d);
5962     foreach (@values)
5963     {
5964         # "71" because we also print a space.
5965         if ($column + length ($_) > 71)
5966         {
5967             $result .= " \\\n" . $fill;
5968             $column = $fill_length;
5969         }
5970         $result .= ' ' if $result =~ /\S\z/;
5971         $result .= $_;
5972         $column += length ($_) + 1;
5973     }
5975     $result .= "\n";
5976     return $result;
5979 # Pretty-print something and append to output_vars.
5980 sub pretty_print
5982     $output_vars .= &pretty_print_internal (@_);
5985 # Pretty-print something and append to output_rules.
5986 sub pretty_print_rule
5988     $output_rules .= &pretty_print_internal (@_);
5992 ################################################################
5995 # $STRING
5996 # &conditional_string(@COND-STACK)
5997 # --------------------------------
5998 # Build a string which denotes the conditional in @COND-STACK.  Some
5999 # simplifications are done: `TRUE' entries are elided, and any `FALSE'
6000 # entry results in a return of `FALSE'.
6001 sub conditional_string
6003   my (@stack) = @_;
6005   if (grep (/^FALSE$/, @stack))
6006     {
6007       return 'FALSE';
6008     }
6009   else
6010     {
6011       return join (' ', uniq sort grep (!/^TRUE$/, @stack));
6012     }
6016 # $BOOLEAN
6017 # &conditional_true_when ($COND, $WHEN)
6018 # -------------------------------------
6019 # See if a conditional is true.  Both arguments are conditional
6020 # strings.  This returns true if the first conditional is true when
6021 # the second conditional is true.
6022 # For instance with $COND = `BAR FOO', and $WHEN = `BAR BAZ FOO',
6023 # obviously return 1, and 0 when, for instance, $WHEN = `FOO'.
6024 sub conditional_true_when ($$)
6026     my ($cond, $when) = @_;
6028     # Make a hash holding all the values from $WHEN.
6029     my %cond_vals = map { $_ => 1 } split (' ', $when);
6031     # Nothing is true when FALSE (not even FALSE itself, but it
6032     # shouldn't hurt if you decide to change that).
6033     return 0 if exists $cond_vals{'FALSE'};
6035     # Check each component of $cond, which looks `COND1 COND2'.
6036     foreach my $comp (split (' ', $cond))
6037     {
6038         # TRUE is always true.
6039         next if $comp eq 'TRUE';
6040         return 0 if ! defined $cond_vals{$comp};
6041     }
6043     return 1;
6047 # $BOOLEAN
6048 # &conditional_is_redundant ($COND, @WHENS)
6049 # ----------------------------------------
6050 # Determine whether $COND is redundant with respect to @WHENS.
6052 # Returns true if $COND is true for any of the conditions in @WHENS.
6054 # If there are no @WHENS, then behave as if @WHENS contained a single empty
6055 # condition.
6056 sub conditional_is_redundant ($@)
6058     my ($cond, @whens) = @_;
6060     @whens = ("") if @whens == 0;
6062     foreach my $when (@whens)
6063     {
6064         return 1 if conditional_true_when ($cond, $when);
6065     }
6066     return 0;
6070 # $BOOLEAN
6071 # &conditional_implies_any ($COND, @CONDS)
6072 # ----------------------------------------
6073 # Returns true iff $COND implies any of the conditions in @CONDS.
6074 sub conditional_implies_any ($@)
6076     my ($cond, @conds) = @_;
6078     @conds = ("") if @conds == 0;
6080     foreach my $c (@conds)
6081     {
6082         return 1 if conditional_true_when ($c, $cond);
6083     }
6084     return 0;
6088 # $NEGATION
6089 # condition_negate ($COND)
6090 # ------------------------
6091 sub condition_negate ($)
6093     my ($cond) = @_;
6095     $cond =~ s/TRUE$/TRUEO/;
6096     $cond =~ s/FALSE$/TRUE/;
6097     $cond =~ s/TRUEO$/FALSE/;
6099     return $cond;
6103 # Compare condition names.
6104 # Issue them in alphabetical order, foo_TRUE before foo_FALSE.
6105 sub by_condition
6107     # Be careful we might be comparing `' or `#'.
6108     $a =~ /^(.*)_(TRUE|FALSE)$/;
6109     my ($aname, $abool) = ($1 || '', $2 || '');
6110     $b =~ /^(.*)_(TRUE|FALSE)$/;
6111     my ($bname, $bbool) = ($1 || '', $2 || '');
6112     return ($aname cmp $bname
6113             # Don't bother with IFs, given that TRUE is after FALSE
6114             # just cmp in the reverse order.
6115             || $bbool cmp $abool
6116             # Just in case...
6117             || $a cmp $b);
6121 # &make_condition (@CONDITIONS)
6122 # -----------------------------
6123 # Transform a list of conditions (themselves can be an internal list
6124 # of conditions, e.g., @CONDITIONS = ('cond1 cond2', 'cond3')) into a
6125 # Make conditional (a pattern for AC_SUBST).
6126 # Correctly returns the empty string when there are no conditions.
6127 sub make_condition
6129     my $res = conditional_string (@_);
6131     # There are no conditions.
6132     if ($res eq '')
6133       {
6134         # Nothing to do.
6135       }
6136     # It's impossible.
6137     elsif ($res eq 'FALSE')
6138       {
6139         $res = '#';
6140       }
6141     # Build it.
6142     else
6143       {
6144         $res = '@' . $res . '@';
6145         $res =~ s/ /@@/g;
6146       }
6148     return $res;
6153 ## ------------------------------ ##
6154 ## Handling the condition stack.  ##
6155 ## ------------------------------ ##
6158 # $COND_STRING
6159 # cond_stack_if ($NEGATE, $COND, $WHERE)
6160 # --------------------------------------
6161 sub cond_stack_if ($$$)
6163   my ($negate, $cond, $where) = @_;
6165   error $where, "$cond does not appear in AM_CONDITIONAL"
6166     if ! $configure_cond{$cond} && $cond !~ /^TRUE|FALSE$/;
6168   $cond = "${cond}_TRUE"
6169     unless $cond =~ /^TRUE|FALSE$/;
6170   $cond = condition_negate ($cond)
6171     if $negate;
6173   push (@cond_stack, $cond);
6175   return conditional_string (@cond_stack);
6179 # $COND_STRING
6180 # cond_stack_else ($NEGATE, $COND, $WHERE)
6181 # ----------------------------------------
6182 sub cond_stack_else ($$$)
6184   my ($negate, $cond, $where) = @_;
6186   if (! @cond_stack)
6187     {
6188       error $where, "else without if";
6189       return;
6190     }
6192   $cond_stack[$#cond_stack] = condition_negate ($cond_stack[$#cond_stack]);
6194   # If $COND is given, check against it.
6195   if (defined $cond)
6196     {
6197       $cond = "${cond}_TRUE"
6198         unless $cond =~ /^TRUE|FALSE$/;
6199       $cond = condition_negate ($cond)
6200         if $negate;
6202       error ($where, "else reminder ($negate$cond) incompatible with "
6203              . "current conditional: $cond_stack[$#cond_stack]")
6204         if $cond_stack[$#cond_stack] ne $cond;
6205     }
6207   return conditional_string (@cond_stack);
6211 # $COND_STRING
6212 # cond_stack_endif ($NEGATE, $COND, $WHERE)
6213 # -----------------------------------------
6214 sub cond_stack_endif ($$$)
6216   my ($negate, $cond, $where) = @_;
6217   my $old_cond;
6219   if (! @cond_stack)
6220     {
6221       error $where, "endif without if: $negate$cond";
6222       return;
6223     }
6226   # If $COND is given, check against it.
6227   if (defined $cond)
6228     {
6229       $cond = "${cond}_TRUE"
6230         unless $cond =~ /^TRUE|FALSE$/;
6231       $cond = condition_negate ($cond)
6232         if $negate;
6234       error ($where, "endif reminder ($negate$cond) incompatible with "
6235              . "current conditional: $cond_stack[$#cond_stack]")
6236         if $cond_stack[$#cond_stack] ne $cond;
6237     }
6239   pop @cond_stack;
6241   return conditional_string (@cond_stack);
6248 ## ------------------------ ##
6249 ## Handling the variables.  ##
6250 ## ------------------------ ##
6253 # check_ambiguous_conditional ($VAR, $COND, $WHERE)
6254 # -------------------------------------------------
6255 # Check for an ambiguous conditional.  This is called when a variable
6256 # is being defined conditionally.  If we already know about a
6257 # definition that is true under the same conditions, then we have an
6258 # ambiguity.
6259 sub check_ambiguous_conditional ($$$)
6261   my ($var, $cond, $where) = @_;
6262   my ($message, $ambig_cond) =
6263     conditional_ambiguous_p ($var, $cond, keys %{$var_value{$var}});
6264   if ($message)
6265     {
6266       msg 'syntax', $where, "$message ...";
6267       msg_var ('syntax', $var, "... `$var' previously defined here.");
6268       verb (macro_dump ($var));
6269     }
6272 # $STRING, $AMBIG_COND
6273 # conditional_ambiguous_p ($WHAT, $COND, @CONDS)
6274 # ----------------------------------------------
6275 # Check for an ambiguous conditional.  Return an error message and
6276 # the other condition involved if we have one, two empty strings otherwise.
6277 #   WHAT:  the thing being defined
6278 #   COND:  the condition under which is is being defined
6279 #   CONDS: the conditons under which is had already been defined
6280 sub conditional_ambiguous_p ($$@)
6282   my ($var, $cond, @conds) = @_;
6283   foreach my $vcond (@conds)
6284     {
6285       # Note that these rules doesn't consider the following
6286       # example as ambiguous.
6287       #
6288       #   if COND1
6289       #     FOO = foo
6290       #   endif
6291       #   if COND2
6292       #     FOO = bar
6293       #   endif
6294       #
6295       # It's up to the user to not define COND1 and COND2
6296       # simultaneously.
6297       my $message;
6298       if ($vcond eq $cond)
6299         {
6300           return ("$var multiply defined in condition $cond", $vcond);
6301         }
6302       elsif (&conditional_true_when ($vcond, $cond))
6303         {
6304           return ("$var was already defined in condition $vcond, "
6305                   . "which implies condition $cond", $vcond);
6306         }
6307       elsif (&conditional_true_when ($cond, $vcond))
6308         {
6309           return ("$var was already defined in condition $vcond, "
6310                    . "which is implied by condition $cond", $vcond);
6311         }
6312     }
6313   return ('', '');
6316 # @MISSING_CONDS
6317 # variable_not_always_defined_in_cond ($VAR, $COND)
6318 # ---------------------------------------------
6319 # Check whether $VAR is always defined for condition $COND.
6320 # Return a list of conditions where the definition is missing.
6322 # For instance, given
6324 #   if COND1
6325 #     if COND2
6326 #       A = foo
6327 #       D = d1
6328 #     else
6329 #       A = bar
6330 #       D = d2
6331 #     endif
6332 #   else
6333 #     D = d3
6334 #   endif
6335 #   if COND3
6336 #     A = baz
6337 #     B = mumble
6338 #   endif
6339 #   C = mumble
6341 # we should have:
6342 #   variable_not_always_defined_in_cond ('A', 'COND1_TRUE COND2_TRUE')
6343 #     => ()
6344 #   variable_not_always_defined_in_cond ('A', 'COND1_TRUE')
6345 #     => ()
6346 #   variable_not_always_defined_in_cond ('A', 'TRUE')
6347 #     => ("COND1_FALSE COND2_FALSE COND3_FALSE",
6348 #         "COND1_FALSE COND2_TRUE COND3_FALSE",
6349 #         "COND1_TRUE COND2_FALSE COND3_FALSE",
6350 #         "COND1_TRUE COND2_TRUE COND3_FALSE")
6351 #   variable_not_always_defined_in_cond ('B', 'COND1_TRUE')
6352 #     => ("COND3_FALSE")
6353 #   variable_not_always_defined_in_cond ('C', 'COND1_TRUE')
6354 #     => ()
6355 #   variable_not_always_defined_in_cond ('D', 'TRUE')
6356 #     => ()
6357 #   variable_not_always_defined_in_cond ('Z', 'TRUE')
6358 #     => ("TRUE")
6360 sub variable_not_always_defined_in_cond ($$)
6362   my ($var, $cond) = @_;
6364   # It's easy to answer if the variable is not defined.
6365   return ("TRUE",) unless exists $var_value{$var};
6367   # How does it work?  Let's take the second example:
6368   #
6369   #   variable_not_always_defined_in_cond ('A', 'COND1_TRUE')
6370   #
6371   # (1) First, we get the list of conditions where A is defined:
6372   #
6373   #   ("COND1_TRUE COND2_TRUE", "COND1_TRUE COND2_FALSE", "COND3_TRUE")
6374   #
6375   # (2) Then we generate the set of inverted conditions:
6376   #
6377   #   ("COND1_FALSE COND2_TRUE COND3_FALSE",
6378   #    "COND1_FALSE COND2_FALSE COND3_FALSE")
6379   #
6380   # (3) Finally we remove these conditions which are not implied by
6381   #     COND1_TRUE.  This yields an empty list and we are done.
6383   my @res = ();
6384   my @cond_defs = keys %{$var_value{$var}}; # (1)
6385   foreach my $icond (invert_conditions (@cond_defs)) # (2)
6386     {
6387       prog_error "invert_conditions returned an input condition"
6388         if exists $var_value{$var}{$icond};
6390       push @res, $icond
6391         if (conditional_true_when ($cond, $icond)); # (3)
6392     }
6393   return @res;
6396 # &macro_define($VAR, $OWNER, $TYPE, $COND, $VALUE, $WHERE)
6397 # -------------------------------------------------------------
6398 # The $VAR can go from Automake to user, but not the converse.
6399 sub macro_define ($$$$$$)
6401   my ($var, $owner, $type, $cond, $value, $where) = @_;
6403   # We will adjust the owener of this variable unless told otherwise.
6404   my $adjust_owner = 1;
6406   error $where, "bad characters in variable name `$var'"
6407     if $var !~ /$MACRO_PATTERN/o;
6409   # NEWS-OS 4.2R complains if a Makefile variable begins with `_'.
6410   msg ('portability', $where,
6411        "$var: variable names starting with `_' are not portable")
6412     if $var =~ /^_/;
6414   # `:='-style assignments are not acknowledged by POSIX.  Moreover it
6415   # has multiple meanings.  In GNU make or BSD make it means "assign
6416   # with immediate expansion", while in OSF make it is used for
6417   # conditional assignments.
6418   msg ('portability', $where, "`:='-style assignments are not portable")
6419     if $type eq ':';
6421   check_variable_expansions ($value, $where);
6423   $cond ||= 'TRUE';
6425   # An Automake variable must be consistently defined with the same
6426   # sign by Automake.  A user variable must be set by either `=' or
6427   # `:=', and later promoted to `+='.
6428   if ($owner == VAR_AUTOMAKE)
6429     {
6430       if (exists $var_type{$var}
6431           && exists $var_type{$var}{$cond}
6432           && $var_type{$var}{$cond} ne $type)
6433         {
6434           error ($where, "$var was set with `$var_type{$var}=' "
6435                  . "and is now set with `$type='");
6436         }
6437     }
6438   else
6439     {
6440       if (!exists $var_type{$var} && $type eq '+')
6441         {
6442           error $where, "$var must be set with `=' before using `+='";
6443         }
6444     }
6445   $var_type{$var}{$cond} = $type;
6447   # Differentiate assignment types.
6449   # 1. append (+=) to a variable defined for current condition
6450   if ($type eq '+' && exists $var_value{$var}{$cond})
6451     {
6452       if (chomp $var_value{$var}{$cond})
6453         {
6454           # Insert a backslash before a trailing newline.
6455           $var_value{$var}{$cond} .= "\\\n";
6456         }
6457       elsif ($var_value{$var}{$cond})
6458         {
6459           # Insert a separator.
6460           $var_value{$var}{$cond} .= ' ';
6461         }
6462        $var_value{$var}{$cond} .= $value;
6463     }
6464   # 2. append (+=) to a variable defined for *another* condition
6465   elsif ($type eq '+' && keys %{$var_value{$var}})
6466     {
6467       # * Generally, $cond is not TRUE.  For instance:
6468       #     FOO = foo
6469       #     if COND
6470       #       FOO += bar
6471       #     endif
6472       #   In this case, we declare an helper variable conditionally,
6473       #   and append it to FOO:
6474       #     FOO = foo $(am__append_1)
6475       #     @COND_TRUE@am__append_1 = bar
6476       #   Of course if FOO is defined under several conditions, we add
6477       #   $(am__append_1) to each definitions.
6478       #
6479       # * If $cond is TRUE, we don't need the helper variable.  E.g., in
6480       #     if COND1
6481       #       FOO = foo1
6482       #     else
6483       #       FOO = foo2
6484       #     endif
6485       #     FOO += bar
6486       #   we can add bar directly to all definition of FOO, and output
6487       #     @COND_TRUE@FOO = foo1 bar
6488       #     @COND_FALSE@FOO = foo2 bar
6490       # Do we need an helper variable?
6491       if ($cond ne 'TRUE')
6492         {
6493             # Does the helper variable already exists?
6494             my $key = "$var:$cond";
6495             if (exists $appendvar{$key})
6496               {
6497                 # Yes, let's simply append to it.
6498                 $var = $appendvar{$key};
6499                 $owner = VAR_AUTOMAKE;
6500               }
6501             else
6502               {
6503                 # No, create it.
6504                 my $num = 1 + keys (%appendvar);
6505                 my $hvar = "am__append_$num";
6506                 $appendvar{$key} = $hvar;
6507                 &macro_define ($hvar, VAR_AUTOMAKE, '+',
6508                                $cond, $value, $where);
6509                 push @var_list, $hvar;
6510                 # Now HVAR is to be added to VAR.
6511                 $value = "\$($hvar)";
6512               }
6513         }
6515       # Add VALUE to all definitions of VAR.
6516       foreach my $vcond (keys %{$var_value{$var}})
6517         {
6518           # We have a bit of error detection to do here.
6519           # This:
6520           #   if COND1
6521           #     X = Y
6522           #   endif
6523           #   X += Z
6524           # should be rejected because X is not defined for all conditions
6525           # where `+=' applies.
6526           my @undef_cond = variable_not_always_defined_in_cond $var, $cond;
6527           if (@undef_cond != 0)
6528             {
6529               error ($where,
6530                      "Cannot apply `+=' because `$var' is not defined "
6531                      . "in\nthe following conditions:\n  "
6532                      . join ("\n  ", @undef_cond)
6533                      . "\nEither define `$var' in these conditions,"
6534                      . " or use\n`+=' in the same conditions as"
6535                      . " the definitions.");
6536             }
6537           else
6538             {
6539               &macro_define ($var, $owner, '+', $vcond, $value, $where);
6540             }
6541         }
6542       # Don't adjust the owner.  The above &macro_define did it in the
6543       # right conditions.
6544       $adjust_owner = 0;
6545     }
6546   # 3. first assignment (=, :=, or +=)
6547   else
6548     {
6549       # If Automake tries to override a value specified by the user,
6550       # just don't let it do.
6551       if (exists $var_value{$var}{$cond}
6552           && $var_owner{$var}{$cond} != VAR_AUTOMAKE
6553           && $owner == VAR_AUTOMAKE)
6554         {
6555           verb ("refusing to override the user definition of:\n"
6556                 . macro_dump ($var)
6557                 ."with `$cond' => `$value'");
6558         }
6559       else
6560         {
6561           # There must be no previous value unless the user is redefining
6562           # an Automake variable or an AC_SUBST variable for an existing
6563           # condition.
6564           check_ambiguous_conditional ($var, $cond, $where)
6565             unless (exists $var_owner{$var}{$cond}
6566                     && (($var_owner{$var}{$cond} == VAR_AUTOMAKE
6567                          && $owner != VAR_AUTOMAKE)
6568                         || $var_owner{$var}{$cond} == VAR_CONFIGURE));
6570           $var_value{$var}{$cond} = $value;
6571           # Assignments to a macro set its location.  We don't adjust
6572           # locations for `+='.  Ideally I suppose we would associate
6573           # line numbers with random bits of text.
6574           $var_location{$var}{$cond} = $where;
6575         }
6576     }
6578   # The owner of a variable can only increase, because an Automake
6579   # variable can be given to the user, but not the converse.
6580   if ($adjust_owner &&
6581       (! exists $var_owner{$var}{$cond}
6582        || $owner > $var_owner{$var}{$cond}))
6583     {
6584       $var_owner{$var}{$cond} = $owner;
6585       # Always adjust the location when the owner changes (even for
6586       # `+=' statements).  The risk otherwise is to warn about
6587       # a VAR_MAKEFILE variable and locate it in configure.ac...
6588       $var_location{$var}{$cond} = $where;
6589     }
6591   # Call var_VAR_trigger if it's defined.
6592   # This hook helps to update some internal state *while*
6593   # parsing the file.  For instance the handling of SUFFIXES
6594   # requires this (see var_SUFFIXES_trigger).
6595   my $var_trigger = "var_${var}_trigger";
6596   &$var_trigger($type, $value) if defined &$var_trigger;
6600 # &macro_delete ($VAR, [@CONDS])
6601 # ------------------------------
6602 # Forget about $VAR under the conditions @CONDS, or completely if
6603 # @CONDS is empty.
6604 sub macro_delete ($@)
6606   my ($var, @conds) = @_;
6608   if (!@conds)
6609     {
6610       delete $var_value{$var};
6611       delete $var_location{$var};
6612       delete $var_owner{$var};
6613       delete $var_comment{$var};
6614       delete $var_type{$var};
6615     }
6616   else
6617     {
6618       foreach my $cond (@conds)
6619         {
6620           delete $var_value{$var}{$cond};
6621           delete $var_location{$var}{$cond};
6622           delete $var_owner{$var}{$cond};
6623           delete $var_comment{$var}{$cond};
6624           delete $var_type{$var}{$cond};
6625         }
6626     }
6630 # &macro_dump ($VAR)
6631 # ------------------
6632 sub macro_dump ($)
6634   my ($var) = @_;
6635   my $text = '';
6637   if (!exists $var_value{$var})
6638     {
6639       $text = "  $var does not exist\n";
6640     }
6641   else
6642     {
6643       $text .= "  $var $var_type{$var}=\n  {\n";
6644       foreach my $vcond (sort by_condition keys %{$var_value{$var}})
6645         {
6646           prog_error ("`$var' is a key in \$var_value, "
6647                       . "but not in \$var_owner\n")
6648             unless exists $var_owner{$var}{$vcond};
6650           my $var_owner;
6651           if ($var_owner{$var}{$vcond} == VAR_AUTOMAKE)
6652             {
6653               $var_owner = 'Automake';
6654             }
6655           elsif ($var_owner{$var}{$vcond} == VAR_CONFIGURE)
6656             {
6657               $var_owner = 'Configure';
6658             }
6659           elsif ($var_owner{$var}{$vcond} == VAR_MAKEFILE)
6660             {
6661               $var_owner = 'Makefile';
6662             }
6663           else
6664             {
6665               prog_error ("unexpected value for `\$var_owner{$var}{$vcond}': "
6666                           . $var_owner{$var}{$vcond})
6667                 unless defined $var_owner;
6668             }
6670           my $where = (defined $var_location{$var}{$vcond}
6671                        ? $var_location{$var}{$vcond} : "undefined");
6672           $text .= "$var_comment{$var}{$vcond}"
6673             if exists $var_comment{$var}{$vcond};
6674           $text .= "    $vcond => $var_value{$var}{$vcond}\n";
6675         }
6676       $text .= "  }\n";
6677     }
6678   return $text;
6682 # &macros_dump ()
6683 # ---------------
6684 sub macros_dump ()
6686   my ($var) = @_;
6688   my $text = "%var_value =\n{\n";
6689   foreach my $var (sort (keys %var_value))
6690     {
6691       $text .= macro_dump ($var);
6692     }
6693   $text .= "}\n";
6694   return $text;
6698 # $BOOLEAN
6699 # variable_defined ($VAR, [$COND])
6700 # ---------------------------------
6701 # See if a variable exists.  $VAR is the variable name, and $COND is
6702 # the condition which we should check.  If no condition is given, we
6703 # currently return true if the variable is defined under any
6704 # condition.
6705 sub variable_defined ($;$)
6707     my ($var, $cond) = @_;
6709     if (! exists $var_value{$var}
6710         || (defined $cond && ! exists $var_value{$var}{$cond}))
6711       {
6712         # VAR is not defined.
6714         # Check there is no target defined with the name of the
6715         # variable we check.
6717         # adl> I'm wondering if this error still makes any sense today. I
6718         # adl> guess it was because targets and variables used to share
6719         # adl> the same namespace in older versions of Automake?
6720         # tom> While what you say is definitely part of it, I think it
6721         # tom> might also have been due to someone making a "spelling error"
6722         # tom> -- writing "foo:..." instead of "foo = ...".
6723         # tom> I'm not sure whether it is really worth diagnosing
6724         # tom> this sort of problem.  In the old days I used to add warnings
6725         # tom> and errors like this pretty randomly, based on bug reports I
6726         # tom> got.  But there's a plausible argument that I was trying
6727         # tom> too hard to prevent people from making mistakes.
6728         if (exists $targets{$var}
6729             && (! defined $cond || exists $targets{$var}{$cond}))
6730           {
6731             for my $tcond ($cond || keys %{$targets{$var}})
6732               {
6733                 prog_error ("\$targets{$var}{$tcond} exists but "
6734                             . "\$target_owner doesn't")
6735                   unless exists $target_owner{$var}{$tcond};
6736                 # Diagnose the first user target encountered, if any.
6737                 # Restricting this test to user targets allows Automake
6738                 # to create rules for things like `bin_PROGRAMS = LDADD'.
6739                 if ($target_owner{$var}{$tcond} == TARGET_USER)
6740                   {
6741                     msg_cond_target ('syntax', $tcond, $var,
6742                                      "`$var' is a target; "
6743                                      . "expected a variable");
6744                     return 0;
6745                   }
6746               }
6747           }
6748         return 0;
6749       }
6751     # Even a var_value examination is good enough for us.  FIXME:
6752     # really should maintain examined status on a per-condition basis.
6753     $content_seen{$var} = 1;
6754     return 1;
6758 # $BOOLEAN
6759 # variable_assert ($VAR, $WHERE)
6760 # ------------------------------
6761 # Make sure a variable exists.  $VAR is the variable name, and $WHERE
6762 # is the name of a macro which refers to $VAR.
6763 sub variable_assert ($$)
6765   my ($var, $where) = @_;
6767   return 1
6768     if variable_defined $var;
6770   require_variables ($where, "variable `$var' is used", 'TRUE', $var);
6772   return 0;
6775 # Mark a variable as examined.
6776 sub examine_variable
6778   my ($var) = @_;
6779   variable_defined ($var);
6783 # &variable_conditions_recursive ($VAR)
6784 # -------------------------------------
6785 # Return the set of conditions for which a variable is defined.
6787 # If the variable is not defined conditionally, and is not defined in
6788 # terms of any variables which are defined conditionally, then this
6789 # returns the empty list.
6791 # If the variable is defined conditionally, but is not defined in
6792 # terms of any variables which are defined conditionally, then this
6793 # returns the list of conditions for which the variable is defined.
6795 # If the variable is defined in terms of any variables which are
6796 # defined conditionally, then this returns a full set of permutations
6797 # of the subvariable conditions.  For example, if the variable is
6798 # defined in terms of a variable which is defined for COND_TRUE,
6799 # then this returns both COND_TRUE and COND_FALSE.  This is
6800 # because we will need to define the variable under both conditions.
6801 sub variable_conditions_recursive ($)
6803     my ($var) = @_;
6805     %vars_scanned = ();
6807     my @new_conds = variable_conditions_recursive_sub ($var, '');
6809     # Now we want to return all permutations of the subvariable
6810     # conditions.
6811     my %allconds = ();
6812     foreach my $item (@new_conds)
6813     {
6814         foreach (split (' ', $item))
6815         {
6816             s/^(.*)_(TRUE|FALSE)$/$1_TRUE/;
6817             $allconds{$_} = 1;
6818         }
6819     }
6820     @new_conds = variable_conditions_permutations (sort keys %allconds);
6822     my %uniqify;
6823     foreach my $cond (@new_conds)
6824     {
6825         my $reduce = variable_conditions_reduce (split (' ', $cond));
6826         next
6827             if $reduce eq 'FALSE';
6828         $uniqify{$cond} = 1;
6829     }
6831     # Note we cannot just do `return sort keys %uniqify', because this
6832     # function is sometimes used in a scalar context.
6833     my @uniq_list = sort by_condition keys %uniqify;
6834     return @uniq_list;
6838 # @CONDS
6839 # variable_conditions ($VAR)
6840 # --------------------------
6841 # Get the list of conditions that a variable is defined with, without
6842 # recursing through the conditions of any subvariables.
6843 # Argument is $VAR: the variable to get the conditions of.
6844 # Returns the list of conditions.
6845 sub variable_conditions ($)
6847     my ($var) = @_;
6848     my @conds = keys %{$var_value{$var}};
6849     return sort by_condition @conds;
6853 # $BOOLEAN
6854 # &variable_conditionally_defined ($VAR)
6855 # --------------------------------------
6856 sub variable_conditionally_defined ($)
6858     my ($var) = @_;
6859     foreach my $cond (variable_conditions_recursive ($var))
6860       {
6861         return 1
6862           unless $cond =~ /^TRUE|FALSE$/;
6863       }
6864     return 0;
6867 # @LIST
6868 # &scan_variable_expansions ($TEXT)
6869 # ---------------------------------
6870 # Return the list of variable names expanded in $TEXT.
6871 # Note that unlike some other functions, $TEXT is not split
6872 # on spaces before we check for subvariables.
6873 sub scan_variable_expansions ($)
6875   my ($text) = @_;
6876   my @result = ();
6878   # Strip comments.
6879   $text =~ s/#.*$//;
6881   # Record each use of ${stuff} or $(stuff) that do not follow a $.
6882   while ($text =~ /(?<!\$)\$(?:\{([^\}]*)\}|\(([^\)]*)\))/g)
6883     {
6884       my $var = $1 || $2;
6885       # The occurent may look like $(string1[:subst1=[subst2]]) but
6886       # we want only `string1'.
6887       $var =~ s/:[^:=]*=[^=]*$//;
6888       push @result, $var;
6889     }
6891   return @result;
6894 # &check_variable_expansions ($TEXT, $WHERE)
6895 # ------------------------------------------
6896 # Check variable expansions in $TEXT and warn about any name that
6897 # does not conform to POSIX.  $WHERE is the location of $TEXT for
6898 # the error message.
6899 sub check_variable_expansions ($$)
6901   my ($text, $where) = @_;
6902   # Catch expansion of variables whose name does not conform to POSIX.
6903   foreach my $var (scan_variable_expansions ($text))
6904     {
6905       if ($var !~ /$MACRO_PATTERN/)
6906         {
6907           # If the variable name contains a space, it's likely
6908           # to be a GNU make extension (such as $(addsuffix ...)).
6909           # Mention this in the diagnostic.
6910           my $gnuext = "";
6911           $gnuext = "\n(probably a GNU make extension)" if $var =~ / /;
6912           msg ('portability', $where,
6913                "$var: non-POSIX variable name$gnuext");
6914         }
6915     }
6918 # &variable_conditions_recursive_sub ($VAR, $PARENT)
6919 # -------------------------------------------------------
6920 # A subroutine of variable_conditions_recursive.  This returns all the
6921 # conditions of $VAR, including those of any sub-variables.
6922 sub variable_conditions_recursive_sub
6924     my ($var, $parent) = @_;
6925     my @new_conds = ();
6927     if (defined $vars_scanned{$var})
6928     {
6929         err_var $parent, "variable `$var' recursively defined";
6930         return ();
6931     }
6932     $vars_scanned{$var} = 1;
6934     my @this_conds = ();
6935     # Examine every condition under which $VAR is defined.
6936     foreach my $vcond (keys %{$var_value{$var}})
6937     {
6938       push (@this_conds, $vcond);
6940       # If $VAR references some other variable, then compute the
6941       # conditions for that subvariable.
6942       my @subvar_conds = ();
6943       foreach my $varname (scan_variable_expansions $var_value{$var}{$vcond})
6944         {
6945           if ($varname =~ /$SUBST_REF_PATTERN/o)
6946             {
6947               $varname = $1;
6948             }
6950           # Here we compute all the conditions under which the
6951           # subvariable is defined.  Then we go through and add
6952           # $VCOND to each.
6953           my @svc = variable_conditions_recursive_sub ($varname, $var);
6954           foreach my $item (@svc)
6955             {
6956               my $val = conditional_string ($vcond, split (' ', $item));
6957               $val ||= 'TRUE';
6958               push (@subvar_conds, $val);
6959             }
6960         }
6962       # If there are no conditional subvariables, then we want to
6963       # return this condition.  Otherwise, we want to return the
6964       # permutations of the subvariables, taking into account the
6965       # conditions of $VAR.
6966       if (! @subvar_conds)
6967         {
6968           push (@new_conds, $vcond);
6969         }
6970       else
6971         {
6972           push (@new_conds, variable_conditions_reduce (@subvar_conds));
6973         }
6974     }
6976     # Unset our entry in vars_scanned.  We only care about recursive
6977     # definitions.
6978     delete $vars_scanned{$var};
6980     # If we are being called on behalf of another variable, we need to
6981     # return all possible permutations of the conditions.  We have
6982     # already handled everything in @this_conds along with their
6983     # subvariables.  We now need to add any permutations that are not
6984     # in @this_conds.
6985     foreach my $this_cond (@this_conds)
6986     {
6987         my @perms =
6988             variable_conditions_permutations (split (' ', $this_cond));
6989         foreach my $perm (@perms)
6990         {
6991             my $ok = 1;
6992             foreach my $scan (@this_conds)
6993             {
6994                 if (&conditional_true_when ($perm, $scan)
6995                     || &conditional_true_when ($scan, $perm))
6996                 {
6997                     $ok = 0;
6998                     last;
6999                 }
7000             }
7001             next if ! $ok;
7003             # This permutation was not already handled, and is valid
7004             # for the parents.
7005             push (@new_conds, $perm);
7006         }
7007     }
7009     return @new_conds;
7013 # Filter a list of conditionals so that only the exclusive ones are
7014 # retained.  For example, if both `COND1_TRUE COND2_TRUE' and
7015 # `COND1_TRUE' are in the list, discard the latter.
7016 # If the list is empty, return TRUE
7017 sub variable_conditions_reduce
7019     my (@conds) = @_;
7020     my @ret = ();
7021     my $cond;
7022     while(@conds > 0)
7023     {
7024         $cond = shift(@conds);
7026         # FALSE is absorbent.
7027         return 'FALSE'
7028           if $cond eq 'FALSE';
7030         if (!conditional_is_redundant ($cond, @ret, @conds))
7031           {
7032             push (@ret, $cond);
7033           }
7034     }
7036     return "TRUE" if @ret == 0;
7037     return @ret;
7040 # @CONDS
7041 # invert_conditions (@CONDS)
7042 # --------------------------
7043 # Invert a list of conditionals.  Returns a set of conditionals which
7044 # are never true for any of the input conditionals, and when taken
7045 # together with the input conditionals cover all possible cases.
7047 # For example:
7048 #   invert_conditions("A_TRUE B_TRUE", "A_FALSE B_FALSE")
7049 #     => ("A_FALSE B_TRUE", "A_TRUE B_FALSE")
7051 #   invert_conditions("A_TRUE B_TRUE", "A_TRUE B_FALSE", "A_FALSE")
7052 #     => ()
7053 sub invert_conditions
7055     my (@conds) = @_;
7057     my @notconds = ();
7059     # Generate all permutation for all inputs.
7060     my @perm =
7061         map { variable_conditions_permutations (split(' ', $_)); } @conds;
7062     # Remove redundant conditions.
7063     @perm = variable_conditions_reduce @perm;
7065     # Now remove all conditions which imply one of the input conditions.
7066     foreach my $perm (@perm)
7067     {
7068         push @notconds, $perm
7069             if ! conditional_implies_any ($perm, @conds);
7070     }
7071     return @notconds;
7074 # Return a list of permutations of a conditional string.
7075 # (But never output FALSE conditions, they are useless.)
7077 # Examples:
7078 #   variable_conditions_permutations ("FOO_FALSE", "BAR_TRUE")
7079 #     => ("FOO_FALSE BAR_FALSE",
7080 #         "FOO_FALSE BAR_TRUE",
7081 #         "FOO_TRUE BAR_FALSE",
7082 #         "FOO_TRUE BAR_TRUE")
7083 #   variable_conditions_permutations ("FOO_FALSE", "TRUE")
7084 #     => ("FOO_FALSE TRUE",
7085 #         "FOO_TRUE TRUE")
7086 #   variable_conditions_permutations ("TRUE")
7087 #     => ("TRUE")
7088 #   variable_conditions_permutations ("FALSE")
7089 #     => ("TRUE")
7090 sub variable_conditions_permutations
7092     my (@comps) = @_;
7093     return ()
7094         if ! @comps;
7095     my $comp = shift (@comps);
7096     return variable_conditions_permutations (@comps)
7097         if $comp eq '';
7098     my $neg = condition_negate ($comp);
7100     my @ret;
7101     foreach my $sub (variable_conditions_permutations (@comps))
7102     {
7103         push (@ret, "$comp $sub") if $comp ne 'FALSE';
7104         push (@ret, "$neg $sub") if $neg ne 'FALSE';
7105     }
7106     if (! @ret)
7107     {
7108         push (@ret, $comp) if $comp ne 'FALSE';
7109         push (@ret, $neg) if $neg ne 'FALSE';
7110     }
7111     return @ret;
7115 # $BOOL
7116 # &check_variable_defined_unconditionally($VAR, $PARENT)
7117 # ------------------------------------------------------
7118 # Warn if a variable is conditionally defined.  This is called if we
7119 # are using the value of a variable.
7120 sub check_variable_defined_unconditionally ($$)
7122   my ($var, $parent) = @_;
7123   foreach my $cond (keys %{$var_value{$var}})
7124     {
7125       next
7126         if $cond =~ /^TRUE|FALSE$/;
7128       if ($parent)
7129         {
7130           msg_var ('unsupported', $parent,
7131                    "automake does not support conditional definition of "
7132                    . "$var in $parent");
7133         }
7134       else
7135         {
7136           msg_var ('unsupported', $var,
7137                    "automake does not support $var being defined "
7138                    . "conditionally");
7139         }
7140     }
7144 # Get the TRUE value of a variable, warn if the variable is
7145 # conditionally defined.
7146 sub variable_value
7148     my ($var) = @_;
7149     &check_variable_defined_unconditionally ($var);
7150     return $var_value{$var}{'TRUE'};
7154 # @VALUES
7155 # &value_to_list ($VAR, $VAL, $COND)
7156 # ----------------------------------
7157 # Convert a variable value to a list, split as whitespace.  This will
7158 # recursively follow $(...) and ${...} inclusions.  It preserves @...@
7159 # substitutions.
7161 # If COND is 'all', then all values under all conditions should be
7162 # returned; if COND is a particular condition (all conditions are
7163 # surrounded by @...@) then only the value for that condition should
7164 # be returned; otherwise, warn if VAR is conditionally defined.
7165 # SCANNED is a global hash listing whose keys are all the variables
7166 # already scanned; it is an error to rescan a variable.
7167 sub value_to_list ($$$)
7169     my ($var, $val, $cond) = @_;
7170     my @result;
7172     # Strip backslashes
7173     $val =~ s/\\(\n|$)/ /g;
7175     foreach (split (' ', $val))
7176     {
7177         # If a comment seen, just leave.
7178         last if /^#/;
7180         # Handle variable substitutions.
7181         if (/^\$\{([^}]*)\}$/ || /^\$\(([^)]*)\)$/)
7182         {
7183             my $varname = $1;
7185             # If the user uses a losing variable name, just ignore it.
7186             # This isn't ideal, but people have requested it.
7187             next if ($varname =~ /\@.*\@/);
7189             my ($from, $to);
7190             my @temp_list;
7191             if ($varname =~ /$SUBST_REF_PATTERN/o)
7192             {
7193                 $varname = $1;
7194                 $to = $3;
7195                 $from = quotemeta $2;
7196             }
7198             # Find the value.
7199             @temp_list =
7200               variable_value_as_list_recursive_worker ($1, $cond, $var);
7202             # Now rewrite the value if appropriate.
7203             if (defined $from)
7204             {
7205                 grep (s/$from$/$to/, @temp_list);
7206             }
7208             push (@result, @temp_list);
7209         }
7210         else
7211         {
7212             push (@result, $_);
7213         }
7214     }
7216     return @result;
7220 # @VALUES
7221 # variable_value_as_list ($VAR, $COND, $PARENT)
7222 # ---------------------------------------------
7223 # Get the value of a variable given a specified condition. without
7224 # recursing through any subvariables.
7225 # Arguments are:
7226 #   $VAR    is the variable
7227 #   $COND   is the condition.  If this is not given, the value for the
7228 #           "TRUE" condition will be returned.
7229 #   $PARENT is the variable in which the variable is used: this is used
7230 #           only for error messages.
7231 # Returns the list of conditions.
7232 # For example, if A is defined as "foo $(B) bar", and B is defined as
7233 # "baz", this will return ("foo", "$(B)", "bar")
7234 sub variable_value_as_list
7236     my ($var, $cond, $parent) = @_;
7237     my @result;
7239     # Check defined
7240     return
7241       unless variable_assert $var, $parent;
7243     # Get value for given condition
7244     $cond ||= 'TRUE';
7245     my $onceflag;
7246     foreach my $vcond (keys %{$var_value{$var}})
7247     {
7248         my $val = $var_value{$var}{$vcond};
7250         if (&conditional_true_when ($vcond, $cond))
7251         {
7252             # Unless variable is not defined conditionally, there should only
7253             # be one value of $vcond true when $cond.
7254             &check_variable_defined_unconditionally ($var, $parent)
7255                     if $onceflag;
7256             $onceflag = 1;
7258             # Strip backslashes
7259             $val =~ s/\\(\n|$)/ /g;
7261             foreach (split (' ', $val))
7262             {
7263                 # If a comment seen, just leave.
7264                 last if /^#/;
7266                 push (@result, $_);
7267             }
7268         }
7269     }
7271     return @result;
7275 # @VALUE
7276 # &variable_value_as_list_recursive_worker ($VAR, $COND, $PARENT)
7277 # ---------------------------------------------------------------
7278 # Return contents of VAR as a list, split on whitespace.  This will
7279 # recursively follow $(...) and ${...} inclusions.  It preserves @...@
7280 # substitutions.  If COND is 'all', then all values under all
7281 # conditions should be returned; if COND is a particular condition
7282 # (all conditions are surrounded by @...@) then only the value for
7283 # that condition should be returned; otherwise, warn if VAR is
7284 # conditionally defined.  If PARENT is specified, it is the name of
7285 # the including variable; this is only used for error reports.
7286 sub variable_value_as_list_recursive_worker ($$$)
7288     my ($var, $cond, $parent) = @_;
7289     my @result = ();
7291     return
7292       unless variable_assert $var, $parent;
7294     if (defined $vars_scanned{$var})
7295     {
7296         # `vars_scanned' is a global we use to keep track of which
7297         # variables we've already examined.
7298         err_var $parent, "variable `$var' recursively defined";
7299     }
7300     elsif ($cond eq 'all')
7301     {
7302         $vars_scanned{$var} = 1;
7303         foreach my $vcond (keys %{$var_value{$var}})
7304         {
7305             my $val = $var_value{$var}{$vcond};
7306             push (@result, &value_to_list ($var, $val, $cond));
7307         }
7308     }
7309     else
7310     {
7311         $cond ||= 'TRUE';
7312         $vars_scanned{$var} = 1;
7313         my $onceflag;
7314         foreach my $vcond (keys %{$var_value{$var}})
7315         {
7316             my $val = $var_value{$var}{$vcond};
7317             if (&conditional_true_when ($vcond, $cond))
7318             {
7319                 # Warn if we have an ambiguity.  It's hard to know how
7320                 # to handle this case correctly.
7321                 &check_variable_defined_unconditionally ($var, $parent)
7322                     if $onceflag;
7323                 $onceflag = 1;
7324                 push (@result, &value_to_list ($var, $val, $cond));
7325             }
7326         }
7327     }
7329     # Unset our entry in vars_scanned.  We only care about recursive
7330     # definitions.
7331     delete $vars_scanned{$var};
7333     return @result;
7337 # &variable_output ($VAR, [@CONDS])
7338 # ---------------------------------
7339 # Output all the values of $VAR is @COND is not specified, else only
7340 # that corresponding to @COND.
7341 sub variable_output ($@)
7343   my ($var, @conds) = @_;
7345   @conds = keys %{$var_value{$var}}
7346     unless @conds;
7348   foreach my $cond (sort by_condition @conds)
7349     {
7350       prog_error ("unknown condition `$cond' for `$var'")
7351         unless exists $var_value{$var}{$cond};
7353       if (exists $var_comment{$var} && exists $var_comment{$var}{$cond})
7354         {
7355           $output_vars .= $var_comment{$var}{$cond};
7356         }
7358       my $val = $var_value{$var}{$cond};
7359       my $equals = $var_type{$var}{$cond} eq ':' ? ':=' : '=';
7360       my $output_var = "$var $equals $val";
7361       $output_var =~ s/^/make_condition ($cond)/meg;
7362       $output_vars .= $output_var . "\n";
7363     }
7367 # &variable_pretty_output ($VAR, [@CONDS])
7368 # ----------------------------------------
7369 # Likewise, but pretty, i.e., we *split* the values at spaces.   Use only
7370 # with variables holding filenames.
7371 sub variable_pretty_output ($@)
7373   my ($var, @conds) = @_;
7375   @conds = keys %{$var_value{$var}}
7376     unless @conds;
7378   foreach my $cond (sort by_condition @conds)
7379     {
7380       prog_error ("unknown condition `$cond' for `$var'")
7381         unless exists $var_value{$var}{$cond};
7383       if (exists $var_comment{$var} && exists $var_comment{$var}{$cond})
7384         {
7385           $output_vars .= $var_comment{$var}{$cond};
7386         }
7388       my $val = $var_value{$var}{$cond};
7389       my $equals = $var_type{$var}{$cond} eq ':' ? ':=' : '=';
7390       my $make_condition = make_condition ($cond);
7392       # Suppress escaped new lines.  &pretty_print_internal will
7393       # add them back, maybe at other places.
7394       $val =~ s/\\$//mg;
7396       $output_vars .= pretty_print_internal ("$make_condition$var $equals",
7397                                              "$make_condition\t",
7398                                              split (' ' , $val));
7399     }
7403 # &variable_value_as_list_recursive ($VAR, $COND, $PARENT)
7404 # --------------------------------------------------------
7405 # This is just a wrapper for variable_value_as_list_recursive_worker that
7406 # initializes the global hash `vars_scanned'.  This hash is used to
7407 # avoid infinite recursion.
7408 sub variable_value_as_list_recursive ($$@)
7410     my ($var, $cond, $parent) = @_;
7411     %vars_scanned = ();
7412     return &variable_value_as_list_recursive_worker ($var, $cond, $parent);
7416 # &define_pretty_variable ($VAR, $COND, @VALUE)
7417 # ---------------------------------------------
7418 # Like define_variable, but the value is a list, and the variable may
7419 # be defined conditionally.  The second argument is the conditional
7420 # under which the value should be defined; this should be the empty
7421 # string to define the variable unconditionally.  The third argument
7422 # is a list holding the values to use for the variable.  The value is
7423 # pretty printed in the output file.
7424 sub define_pretty_variable ($$@)
7426     my ($var, $cond, @value) = @_;
7428     # Beware that an empty $cond has a different semantics for
7429     # macro_define and variable_pretty_output.
7430     $cond ||= 'TRUE';
7432     if (! variable_defined ($var, $cond))
7433     {
7434         macro_define ($var, VAR_AUTOMAKE, '', $cond, "@value", undef);
7435         variable_pretty_output ($var, $cond || 'TRUE');
7436         $content_seen{$var} = 1;
7437     }
7441 # define_variable ($VAR, $VALUE)
7442 # ------------------------------
7443 # Define a new user variable VAR to VALUE, but only if not already defined.
7444 sub define_variable ($$)
7446     my ($var, $value) = @_;
7447     define_pretty_variable ($var, 'TRUE', $value);
7451 # Like define_variable, but define a variable to be the configure
7452 # substitution by the same name.
7453 sub define_configure_variable ($)
7455   my ($var) = @_;
7456   if (! variable_defined ($var, 'TRUE')
7457       # Explicitly avoid ANSI2KNR -- we AC_SUBST that in
7458       # protos.m4, but later define it elsewhere.  This is
7459       # pretty hacky.  We also explicitly avoid AMDEPBACKSLASH:
7460       # it might be subst'd by `\', which certainly would not be
7461       # appreciated by Make.
7462       && ! grep { $_ eq $var } (qw(ANSI2KNR AMDEPBACKSLASH)))
7463     {
7464       macro_define ($var, VAR_CONFIGURE, '', 'TRUE',
7465                     subst $var, $configure_vars{$var});
7466       variable_pretty_output ($var, 'TRUE');
7467     }
7471 # define_compiler_variable ($LANG)
7472 # --------------------------------
7473 # Define a compiler variable.  We also handle defining the `LT'
7474 # version of the command when using libtool.
7475 sub define_compiler_variable ($)
7477     my ($lang) = @_;
7479     my ($var, $value) = ($lang->compiler, $lang->compile);
7480     &define_variable ($var, $value);
7481     &define_variable ("LT$var", "\$(LIBTOOL) --mode=compile $value")
7482       if variable_defined ('LIBTOOL');
7486 # define_linker_variable ($LANG)
7487 # ------------------------------
7488 # Define linker variables.
7489 sub define_linker_variable ($)
7491     my ($lang) = @_;
7493     my ($var, $value) = ($lang->lder, $lang->ld);
7494     # CCLD = $(CC).
7495     &define_variable ($lang->lder, $lang->ld);
7496     # CCLINK = $(CCLD) blah blah...
7497     &define_variable ($lang->linker,
7498                       ((variable_defined ('LIBTOOL')
7499                         ? '$(LIBTOOL) --mode=link ' : '')
7500                        . $lang->link));
7503 ################################################################
7505 ## ---------------- ##
7506 ## Handling rules.  ##
7507 ## ---------------- ##
7509 sub register_suffix_rule ($$$)
7511   my ($where, $src, $dest) = @_;
7513   verb "Sources ending in $src become $dest";
7514   push @suffixes, $src, $dest;
7516   # When tranforming sources to objects, Automake uses the
7517   # %suffix_rules to move from each source extension to
7518   # `.$(OBJEXT)', not to `.o' or `.obj'.  However some people
7519   # define suffix rules for `.o' or `.obj', so internally we will
7520   # consider these extensions equivalent to `.$(OBJEXT)'.  We
7521   # CANNOT rewrite the target (i.e., automagically replace `.o'
7522   # and `.obj' by `.$(OBJEXT)' in the output), or warn the user
7523   # that (s)he'd better use `.$(OBJEXT)', because Automake itself
7524   # output suffix rules for `.o' or `.obj'...
7525   $dest = '.$(OBJEXT)' if ($dest eq '.o' || $dest eq '.obj');
7527   # Reading the comments near the declaration of $suffix_rules might
7528   # help to understand the update of $suffix_rules that follows...
7530   # Register $dest as a possible destination from $src.
7531   # We might have the create the \hash.
7532   if (exists $suffix_rules->{$src})
7533     {
7534       $suffix_rules->{$src}{$dest} = [ $dest, 1 ];
7535     }
7536   else
7537     {
7538       $suffix_rules->{$src} = { $dest => [ $dest, 1 ] };
7539     }
7541   # If we know how to transform $dest in something else, then
7542   # we know how to transform $src in that "something else".
7543   if (exists $suffix_rules->{$dest})
7544     {
7545       for my $dest2 (keys %{$suffix_rules->{$dest}})
7546         {
7547           my $dist = $suffix_rules->{$dest}{$dest2}[1] + 1;
7548           # Overwrite an existing $src->$dest2 path only if
7549           # the path via $dest which is shorter.
7550           if (! exists $suffix_rules->{$src}{$dest2}
7551               || $suffix_rules->{$src}{$dest2}[1] > $dist)
7552             {
7553               $suffix_rules->{$src}{$dest2} = [ $dest, $dist ];
7554             }
7555         }
7556     }
7558   # Similarly, any extension that can be derived into $src
7559   # can be derived into the same extenstions as $src can.
7560   my @dest2 = keys %{$suffix_rules->{$src}};
7561   for my $src2 (keys %$suffix_rules)
7562     {
7563       if (exists $suffix_rules->{$src2}{$src})
7564         {
7565           for my $dest2 (@dest2)
7566             {
7567               my $dist = $suffix_rules->{$src}{$dest2} + 1;
7568               # Overwrite an existing $src2->$dest2 path only if
7569               # the path via $src is shorter.
7570               if (! exists $suffix_rules->{$src2}{$dest2}
7571                   || $suffix_rules->{$src2}{$dest2}[1] > $dist)
7572                 {
7573                   $suffix_rules->{$src2}{$dest2} = [ $src, $dist ];
7574                 }
7575             }
7576         }
7577     }
7580 # @CONDS
7581 # rule_define ($TARGET, $SOURCE, $OWNER, $COND, $WHERE)
7582 # -----------------------------------------------------
7583 # Define a new rule.  $TARGET is the rule name.  $SOURCE
7584 # is the filename the rule comes from.  $OWNER is the
7585 # owener of the rule (TARGET_AUTOMAKE or TARGET_USER).
7586 # $COND is the condition string under which the rule is defined.
7587 # $WHERE is where the rule is defined (file name and/or line number).
7588 # Returns a (possibly empty) list of conditions where the rule
7589 # should be defined.
7590 sub rule_define ($$$$$)
7592   my ($target, $source, $owner, $cond, $where) = @_;
7594   # Don't even think about defining a rule in condition FALSE.
7595   return () if $cond eq 'FALSE';
7597   # For now `foo:' will override `foo$(EXEEXT):'.  This is temporary,
7598   # though, so we emit a warning.
7599   (my $noexe = $target) =~ s,\$\(EXEEXT\)$,,;
7600   if ($noexe ne $target
7601       && exists $targets{$noexe}
7602       && exists $targets{$noexe}{$cond}
7603       && $target_name{$noexe}{$cond} ne $target)
7604     {
7605       # The no-exeext option enables this feature.
7606       if (! defined $options{'no-exeext'})
7607         {
7608           msg ('obsolete', $noexe,
7609                "deprecated feature: `$noexe' overrides `$noexe\$(EXEEXT)'\n"
7610                . "change your target to read `$noexe\$(EXEEXT)'");
7611         }
7612       # Don't define.
7613       return ();
7614     }
7616   # For now on, strip off $(EXEEXT) from $target, so we can diagnose
7617   # a clash if `ctags$(EXEEXT):' is redefined after `ctags:'.
7618   my $realtarget = $target;
7619   $target = $noexe;
7621   # A GNU make-style pattern rule has a single "%" in the target name.
7622   msg ('portability', $where,
7623        "`%'-style pattern rules are a GNU make extension")
7624     if $target =~ /^[^%]*%[^%]*$/;
7626   # Diagnose target redefinitions.
7627   if (exists $target_source{$target}{$cond})
7628     {
7629       # Sanity checks.
7630       prog_error ("\$target_source{$target}{$cond} exists, but \$target_owner"
7631                   . " doesn't.")
7632         unless exists $target_owner{$target}{$cond};
7633       prog_error ("\$target_source{$target}{$cond} exists, but \$targets"
7634                   . " doesn't.")
7635         unless exists $targets{$target}{$cond};
7636       prog_error ("\$target_source{$target}{$cond} exists, but \$target_name"
7637                   . " doesn't.")
7638         unless exists $target_name{$target}{$cond};
7640       my $oldowner  = $target_owner{$target}{$cond};
7642       # Don't mention true conditions in diagnostics.
7643       my $condmsg = $cond ne 'TRUE' ? " in condition `$cond'" : '';
7645       if ($owner == TARGET_USER)
7646         {
7647           if ($oldowner eq TARGET_USER)
7648             {
7649               # Ignore `%'-style pattern rules.  We'd need the
7650               # dependencies to detect duplicates, and they are
7651               # already diagnosed as unportable by -Wportability.
7652               if ($target !~ /^[^%]*%[^%]*$/)
7653                 {
7654                   ## FIXME: Presently we can't diagnose duplcate user rules
7655                   ## because we doesn't distinguish rules with commands
7656                   ## from rules that only add dependencies.  E.g.,
7657                   ##   .PHONY: foo
7658                   ##   .PHONY: bar
7659                   ## is legitimate. (This is phony.test.)
7661                   # msg ('syntax', $where,
7662                   #      "redefinition of `$target'$condmsg...");
7663                   # msg_cond_target ('syntax', $cond, $target,
7664                   #                "... `$target' previously defined here.");
7665                 }
7666               # Return so we don't redefine the rule in our tables,
7667               # don't check for ambiguous conditional, etc.  The rule
7668               # will be output anyway beauce &read_am_file ignore the
7669               # return code.
7670               return ();
7671             }
7672           else
7673             {
7674               # Since we parse the user Makefile.am before reading
7675               # the Automake fragments, this condition should never happen.
7676               prog_error ("user target `$target' seen after Automake's "
7677                           . "definition\nfrom `$targets{$target}$condmsg'");
7678             }
7679         }
7680       else # $owner == TARGET_AUTOMAKE
7681         {
7682           if ($oldowner == TARGET_USER)
7683             {
7684               # Don't overwrite the user definition of TARGET.
7685               return ();
7686             }
7687           else # $oldowner == TARGET_AUTOMAKE
7688             {
7689               # Automake should ignore redefinitions of its own
7690               # rules if they came from the same file.  This makes
7691               # it easier to process a Makefile fragment several times.
7692               # Hower it's an error if the target is defined in many
7693               # files.  E.g., the user might be using bin_PROGRAMS = ctags
7694               # which clashes with our `ctags' rule.
7695               # (It would be more accurate if we had a way to compare
7696               # the *content* of both rules.  Then $targets_source would
7697               # be useless.)
7698               my $oldsource = $target_source{$target}{$cond};
7699               return () if $source eq $oldsource;
7701               msg ('syntax', $where, "redefinition of `$target'$condmsg...");
7702               msg_cond_target ('syntax', $cond, $target,
7703                                "... `$target' previously defined here.");
7704               return ();
7705             }
7706         }
7707       # Never reached.
7708       prog_error ("Unreachable place reached.");
7709     }
7711   # Conditions for which the rule should be defined.
7712   my @conds = $cond;
7714   # Check ambiguous conditional definitions.
7715   my ($message, $ambig_cond) =
7716     conditional_ambiguous_p ($target, $cond, keys %{$targets{$target}});
7717   if ($message)                 # We have an ambiguty.
7718     {
7719       if ($owner == TARGET_USER)
7720         {
7721           # For user rules, just diagnose the ambiguity.
7722           msg 'syntax', $where, "$message ...";
7723           msg_cond_target ('syntax', $ambig_cond, $target,
7724                            "... `$target' previously defined here.");
7725           return ();
7726         }
7727       else
7728         {
7729           # FIXME: for Automake rules, we can't diagnose ambiguities yet.
7730           # The point is that Automake doesn't propagate conditionals
7731           # everywhere.  For instance &handle_PROGRAMS doesn't care if
7732           # bin_PROGRAMS was defined conditionally or not.
7733           # On the following input
7734           #   if COND1
7735           #   foo:
7736           #           ...
7737           #   else
7738           #   bin_PROGRAMS = foo
7739           #   endif
7740           # &handle_PROGRAMS will attempt to define a `foo:' rule
7741           # in condition TRUE (which conflicts with COND1).  Fixing
7742           # this in &handle_PROGRAMS and siblings seems hard: you'd
7743           # have to explain &file_contents what to do with a
7744           # conditional.  So for now we do our best *here*.  If `foo:'
7745           # was already defined in condition COND1 and we want to define
7746           # it in condition TRUE, then define it only in condition !COND1.
7747           # (See cond14.test and cond15.test for some test cases.)
7748           my @defined_conds = keys %{$targets{$target}};
7749           @conds = ();
7750           for my $undefined_cond (invert_conditions(@defined_conds))
7751             {
7752               push @conds, make_condition ($cond, $undefined_cond);
7753             }
7754           # No conditions left to define the rule.
7755           # Warn, because our workaround is meaningless in this case.
7756           if (scalar @conds == 0)
7757             {
7758               msg 'syntax', $where, "$message ...";
7759               msg_cond_target ('syntax', $ambig_cond, $target,
7760                                "... `$target' previously defined here.");
7761               return ();
7762             }
7763         }
7764     }
7766   # Finally define this rule.
7767   for my $c (@conds)
7768     {
7769       $targets{$target}{$c} = $where;
7770       $target_source{$target}{$c} = $source;
7771       $target_owner{$target}{$c} = $owner;
7772       $target_name{$target}{$c} = $realtarget;
7773     }
7775   # We honor inference rules with multiple targets because many
7776   # make support this and people use it.  However this is disallowed
7777   # by POSIX.  We'll print a warning later.
7778   my $target_count = 0;
7779   my $inference_rule_count = 0;
7780   for my $t (split (' ', $target))
7781     {
7782       ++$target_count;
7783       # Check the rule for being a suffix rule. If so, store in a hash.
7784       # Either it's a rule for two known extensions...
7785       if ($t =~ /^($KNOWN_EXTENSIONS_PATTERN)($KNOWN_EXTENSIONS_PATTERN)$/
7786           # ...or it's a rule with unknown extensions (.i.e, the rule
7787           # looks like `.foo.bar:' but `.foo' or `.bar' are not
7788           # declared in SUFFIXES and are not known language
7789           # extensions).  Automake will complete SUFFIXES from
7790           # @suffixes automatically (see handle_footer).
7791           || ($t =~ /$SUFFIX_RULE_PATTERN/o && accept_extensions($1)))
7792         {
7793           ++$inference_rule_count;
7794           register_suffix_rule ($where, $1, $2);
7795         }
7796     }
7798   # POSIX allow multiple targets befor the colon, but disallow
7799   # definitions of multiple Inference rules.  It's also
7800   # disallowed to mix plain targets with inference rules.
7801   msg ('portability', $where,
7802        "Inference rules can have only one target before the colon (POSIX).")
7803     if $inference_rule_count > 0 && $target_count > 1;
7805   # Return "" instead of TRUE so it can be used with make_paragraphs
7806   # directly.
7807   return "" if 1 == @conds && $conds[0] eq 'TRUE';
7808   return @conds;
7812 # See if a target exists.
7813 sub target_defined
7815     my ($target) = @_;
7816     return exists $targets{$target};
7820 ################################################################
7822 # &append_comments ($VARIABLE, $SPACING, $COMMENT)
7823 # ------------------------------------------------
7824 # Apped $COMMENT to the other comments for $VARIABLE, using
7825 # $SPACING as separator.
7826 sub append_comments ($$$$)
7828     my ($cond, $var, $spacing, $comment) = @_;
7829     $var_comment{$var}{$cond} .= $spacing
7830         if (!defined $var_comment{$var}{$cond}
7831             || $var_comment{$var}{$cond} !~ /\n$/o);
7832     $var_comment{$var}{$cond} .= $comment;
7836 # &read_am_file ($AMFILE)
7837 # -----------------------
7838 # Read Makefile.am and set up %contents.  Simultaneously copy lines
7839 # from Makefile.am into $output_trailer or $output_vars as
7840 # appropriate.  NOTE we put rules in the trailer section.  We want
7841 # user rules to come after our generated stuff.
7842 sub read_am_file ($)
7844     my ($amfile) = @_;
7846     my $am_file = new Automake::XFile ("< $amfile");
7847     verb "reading $amfile";
7849     my $spacing = '';
7850     my $comment = '';
7851     my $blank = 0;
7852     my $saw_bk = 0;
7854     use constant IN_VAR_DEF => 0;
7855     use constant IN_RULE_DEF => 1;
7856     use constant IN_COMMENT => 2;
7857     my $prev_state = IN_RULE_DEF;
7859     while ($_ = $am_file->getline)
7860     {
7861         if (/$IGNORE_PATTERN/o)
7862         {
7863             # Merely delete comments beginning with two hashes.
7864         }
7865         elsif (/$WHITE_PATTERN/o)
7866         {
7867             error "$amfile:$.", "blank line following trailing backslash"
7868               if $saw_bk;
7869             # Stick a single white line before the incoming macro or rule.
7870             $spacing = "\n";
7871             $blank = 1;
7872             # Flush all comments seen so far.
7873             if ($comment ne '')
7874             {
7875                 $output_vars .= $comment;
7876                 $comment = '';
7877             }
7878         }
7879         elsif (/$COMMENT_PATTERN/o)
7880         {
7881             # Stick comments before the incoming macro or rule.  Make
7882             # sure a blank line preceeds first block of comments.
7883             $spacing = "\n" unless $blank;
7884             $blank = 1;
7885             $comment .= $spacing . $_;
7886             $spacing = '';
7887             $prev_state = IN_COMMENT;
7888         }
7889         else
7890         {
7891             last;
7892         }
7893         $saw_bk = /\\$/ && ! /$IGNORE_PATTERN/o;
7894     }
7896     # We save the conditional stack on entry, and then check to make
7897     # sure it is the same on exit.  This lets us conditonally include
7898     # other files.
7899     my @saved_cond_stack = @cond_stack;
7900     my $cond = conditional_string (@cond_stack);
7902     my $last_var_name = '';
7903     my $last_var_type = '';
7904     my $last_var_value = '';
7905     # FIXME: shouldn't use $_ in this loop; it is too big.
7906     while ($_)
7907     {
7908         my $here = "$amfile:$.";
7910         # Make sure the line is \n-terminated.
7911         chomp;
7912         $_ .= "\n";
7914         # Don't look at MAINTAINER_MODE_TRUE here.  That shouldn't be
7915         # used by users.  @MAINT@ is an anachronism now.
7916         $_ =~ s/\@MAINT\@//g
7917             unless $seen_maint_mode;
7919         my $new_saw_bk = /\\$/ && ! /$IGNORE_PATTERN/o;
7921         if (/$IGNORE_PATTERN/o)
7922         {
7923             # Merely delete comments beginning with two hashes.
7924         }
7925         elsif (/$WHITE_PATTERN/o)
7926         {
7927             # Stick a single white line before the incoming macro or rule.
7928             $spacing = "\n";
7929             error $here, "blank line following trailing backslash"
7930               if $saw_bk;
7931         }
7932         elsif (/$COMMENT_PATTERN/o)
7933         {
7934             # Stick comments before the incoming macro or rule.
7935             $comment .= $spacing . $_;
7936             $spacing = '';
7937             error $here, "comment following trailing backslash"
7938               if $saw_bk && $comment eq '';
7939             $prev_state = IN_COMMENT;
7940         }
7941         elsif ($saw_bk)
7942         {
7943             if ($prev_state == IN_RULE_DEF)
7944             {
7945                 $output_trailer .= &make_condition (@cond_stack);
7946                 $output_trailer .= $_;
7947             }
7948             elsif ($prev_state == IN_COMMENT)
7949             {
7950                 # If the line doesn't start with a `#', add it.
7951                 # We do this because a continuated comment like
7952                 #   # A = foo \
7953                 #         bar \
7954                 #         baz
7955                 # is not portable.  BSD make doesn't honor
7956                 # escaped newlines in comments.
7957                 s/^#?/#/;
7958                 $comment .= $spacing . $_;
7959             }
7960             else # $prev_state == IN_VAR_DEF
7961             {
7962               $last_var_value .= ' '
7963                 unless $last_var_value =~ /\s$/;
7964               $last_var_value .= $_;
7966               if (!/\\$/)
7967                 {
7968                   append_comments ($cond || 'TRUE',
7969                                    $last_var_name, $spacing, $comment);
7970                   $comment = $spacing = '';
7971                   macro_define ($last_var_name, VAR_MAKEFILE,
7972                                 $last_var_type, $cond,
7973                                 $last_var_value, $here)
7974                     if $cond ne 'FALSE';
7975                   push (@var_list, $last_var_name);
7976                 }
7977             }
7978         }
7980         elsif (/$IF_PATTERN/o)
7981           {
7982             $cond = cond_stack_if ($1, $2, $here);
7983           }
7984         elsif (/$ELSE_PATTERN/o)
7985           {
7986             $cond = cond_stack_else ($1, $2, $here);
7987           }
7988         elsif (/$ENDIF_PATTERN/o)
7989           {
7990             $cond = cond_stack_endif ($1, $2, $here);
7991           }
7993         elsif (/$RULE_PATTERN/o)
7994         {
7995             # Found a rule.
7996             $prev_state = IN_RULE_DEF;
7998             # For now we have to output all definitions of user rules
7999             # and can't diagnose duplicates (see the comment in
8000             # rule_define). So we go on and ignore the return value.
8001             rule_define ($1, $amfile, TARGET_USER, $cond || 'TRUE', $here);
8003             check_variable_expansions ($_, $here);
8005             $output_trailer .= $comment . $spacing;
8006             $output_trailer .= &make_condition (@cond_stack);
8007             $output_trailer .= $_;
8008             $comment = $spacing = '';
8009         }
8010         elsif (/$ASSIGNMENT_PATTERN/o)
8011         {
8012             # Found a macro definition.
8013             $prev_state = IN_VAR_DEF;
8014             $last_var_name = $1;
8015             $last_var_type = $2;
8016             $last_var_value = $3;
8017             if ($3 ne '' && substr ($3, -1) eq "\\")
8018             {
8019                 # We preserve the `\' because otherwise the long lines
8020                 # that are generated will be truncated by broken
8021                 # `sed's.
8022                 $last_var_value = $3 . "\n";
8023             }
8025             if (!/\\$/)
8026               {
8027                 # Accumulating variables must not be output.
8028                 append_comments ($cond || 'TRUE',
8029                                  $last_var_name, $spacing, $comment);
8030                 $comment = $spacing = '';
8032                 macro_define ($last_var_name, VAR_MAKEFILE,
8033                               $last_var_type, $cond,
8034                               $last_var_value, $here)
8035                   if $cond ne 'FALSE';
8036                 push (@var_list, $last_var_name);
8037               }
8038         }
8039         elsif (/$INCLUDE_PATTERN/o)
8040         {
8041             my $path = $1;
8043             if ($path =~ s/^\$\(top_srcdir\)\///)
8044               {
8045                 push (@include_stack, "\$\(top_srcdir\)/$path");
8046                 # Distribute any included file.
8048                 # Always use the $(top_srcdir) prefix in DIST_COMMON,
8049                 # otherwise OSF make will implicitely copy the included
8050                 # file in the build tree during `make distdir' to satisfy
8051                 # the dependency.
8052                 # (subdircond2.test and subdircond3.test will fail.)
8053                 push_dist_common ("\$\(top_srcdir\)/$path");
8054               }
8055             else
8056               {
8057                 $path =~ s/\$\(srcdir\)\///;
8058                 push (@include_stack, "\$\(srcdir\)/$path");
8059                 # Always use the $(srcdir) prefix in DIST_COMMON,
8060                 # otherwise OSF make will implicitely copy the included
8061                 # file in the build tree during `make distdir' to satisfy
8062                 # the dependency.
8063                 # (subdircond2.test and subdircond3.test will fail.)
8064                 push_dist_common ("\$\(srcdir\)/$path");
8065                 $path = $relative_dir . "/" . $path;
8066               }
8067             &read_am_file ($path);
8068         }
8069         else
8070         {
8071             # This isn't an error; it is probably a continued rule.
8072             # In fact, this is what we assume.
8073             $prev_state = IN_RULE_DEF;
8074             check_variable_expansions ($_, $here);
8075             $output_trailer .= $comment . $spacing;
8076             $output_trailer .= &make_condition  (@cond_stack);
8077             $output_trailer .= $_;
8078             $comment = $spacing = '';
8079             error $here, "`#' comment at start of rule is unportable"
8080               if $_ =~ /^\t\s*\#/;
8081         }
8083         $saw_bk = $new_saw_bk;
8084         $_ = $am_file->getline;
8085     }
8087     $output_trailer .= $comment;
8089     err_am ("trailing backslash on last line")
8090       if $saw_bk;
8092     err_am (@cond_stack ? "unterminated conditionals: @cond_stack"
8093             : "too many conditionals closed in include file")
8094       if "@saved_cond_stack" ne "@cond_stack";
8098 # define_standard_variables ()
8099 # ----------------------------
8100 # A helper for read_main_am_file which initializes configure variables
8101 # and variables from header-vars.am.
8102 sub define_standard_variables
8104     my $saved_output_vars = $output_vars;
8105     my ($comments, undef, $rules) =
8106       file_contents_internal (1, "$libdir/am/header-vars.am");
8108     # This will output the definitions in $output_vars, which we don't
8109     # want...
8110     foreach my $var (sort keys %configure_vars)
8111     {
8112         &define_configure_variable ($var);
8113         push (@var_list, $var);
8114     }
8116     # ... hence, we restore $output_vars.
8117     $output_vars = $saved_output_vars . $comments . $rules;
8120 # Read main am file.
8121 sub read_main_am_file
8123     my ($amfile) = @_;
8125     # This supports the strange variable tricks we are about to play.
8126     prog_error (macros_dump () . "variable defined before read_main_am_file")
8127       if (scalar keys %var_value > 0);
8129     # Generate copyright header for generated Makefile.in.
8130     # We do discard the output of predefined variables, handled below.
8131     $output_vars = ("# $in_file_name generated by automake "
8132                    . $VERSION . " from $am_file_name.\n");
8133     $output_vars .= '# ' . subst ('configure_input') . "\n";
8134     $output_vars .= $gen_copyright;
8136     # We want to predefine as many variables as possible.  This lets
8137     # the user set them with `+=' in Makefile.am.  However, we don't
8138     # want these initial definitions to end up in the output quite
8139     # yet.  So we just load them, but output them later.
8140     &define_standard_variables;
8142     # Read user file, which might override some of our values.
8143     &read_am_file ($amfile);
8145     # Output all the Automake variables.  If the user changed one,
8146     # then it is now marked as VAR_CONFIGURE or VAR_MAKEFILE.
8147     foreach my $var (uniq @var_list)
8148     {
8149       # Some variables, like AMDEPBACKSLASH are in @var_list
8150       # but don't have a owner.  This is good, because we don't want
8151       # to output them.
8152       foreach my $cond (keys %{$var_owner{$var}})
8153         {
8154           variable_output ($var, $cond)
8155             if $var_owner{$var}{$cond} == VAR_AUTOMAKE;
8156         }
8157     }
8159     # Now dump the user variables that were defined.  We do it in the same
8160     # order in which they were defined (skipping duplicates).
8161     foreach my $var (uniq @var_list)
8162     {
8163       foreach my $cond (keys %{$var_owner{$var}})
8164         {
8165           variable_output ($var, $cond)
8166             if $var_owner{$var}{$cond} != VAR_AUTOMAKE;
8167         }
8168     }
8171 ################################################################
8173 # $FLATTENED
8174 # &flatten ($STRING)
8175 # ------------------
8176 # Flatten the $STRING and return the result.
8177 sub flatten
8179   $_ = shift;
8181   s/\\\n//somg;
8182   s/\s+/ /g;
8183   s/^ //;
8184   s/ $//;
8186   return $_;
8190 # @PARAGRAPHS
8191 # &make_paragraphs ($MAKEFILE, [%TRANSFORM])
8192 # ------------------------------------------
8193 # Load a $MAKEFILE, apply the %TRANSFORM, and return it as a list of
8194 # paragraphs.
8195 sub make_paragraphs ($%)
8197     my ($file, %transform) = @_;
8199     # Complete %transform with global options and make it a Perl
8200     # $command.
8201     my $command =
8202       "s/$IGNORE_PATTERN//gm;"
8203         . transform (%transform,
8205                      'CYGNUS'          => $cygnus_mode,
8206                      'MAINTAINER-MODE'
8207                      => $seen_maint_mode ? subst ('MAINTAINER_MODE_TRUE') : '',
8209                      'SHAR'        => $options{'dist-shar'} || 0,
8210                      'BZIP2'       => $options{'dist-bzip2'} || 0,
8211                      'ZIP'         => $options{'dist-zip'} || 0,
8212                      'COMPRESS'    => $options{'dist-tarZ'} || 0,
8214                      'INSTALL-INFO' => !$options{'no-installinfo'},
8215                      'INSTALL-MAN'  => !$options{'no-installman'},
8216                      'CK-NEWS'      => $options{'check-news'} || 0,
8218                      'SUBDIRS'      => variable_defined ('SUBDIRS'),
8219                      'TOPDIR'       => backname ($relative_dir),
8220                      'TOPDIR_P'     => $relative_dir eq '.',
8221                      'CONFIGURE-AC' => $configure_ac,
8223                      'BUILD'    => $seen_canonical == AC_CANONICAL_SYSTEM,
8224                      'HOST'     => $seen_canonical,
8225                      'TARGET'   => $seen_canonical == AC_CANONICAL_SYSTEM,
8227                      'LIBTOOL'      => variable_defined ('LIBTOOL'))
8228           # We don't need more than two consecutive new-lines.
8229           . 's/\n{3,}/\n\n/g';
8231     # Swallow the file and apply the COMMAND.
8232     my $fc_file = new Automake::XFile "< $file";
8233     # Looks stupid?
8234     verb "reading $file";
8235     my $saved_dollar_slash = $/;
8236     undef $/;
8237     $_ = $fc_file->getline;
8238     $/ = $saved_dollar_slash;
8239     eval $command;
8240     $fc_file->close;
8241     my $content = $_;
8243     # Split at unescaped new lines.
8244     my @lines = split (/(?<!\\)\n/, $content);
8245     my @res;
8247     while (defined ($_ = shift @lines))
8248       {
8249         my $paragraph = "$_";
8250         # If we are a rule, eat as long as we start with a tab.
8251         if (/$RULE_PATTERN/smo)
8252           {
8253             while (defined ($_ = shift @lines) && $_ =~ /^\t/)
8254               {
8255                 $paragraph .= "\n$_";
8256               }
8257             unshift (@lines, $_);
8258           }
8260         # If we are a comments, eat as much comments as you can.
8261         elsif (/$COMMENT_PATTERN/smo)
8262           {
8263             while (defined ($_ = shift @lines)
8264                    && $_ =~ /$COMMENT_PATTERN/smo)
8265               {
8266                 $paragraph .= "\n$_";
8267               }
8268             unshift (@lines, $_);
8269           }
8271         push @res, $paragraph;
8272         $paragraph = '';
8273       }
8275     return @res;
8280 # ($COMMENT, $VARIABLES, $RULES)
8281 # &file_contents_internal ($IS_AM, $FILE, [%TRANSFORM])
8282 # -----------------------------------------------------
8283 # Return contents of a file from $libdir/am, automatically skipping
8284 # macros or rules which are already known. $IS_AM iff the caller is
8285 # reading an Automake file (as opposed to the user's Makefile.am).
8286 sub file_contents_internal ($$%)
8288     my ($is_am, $file, %transform) = @_;
8290     my $result_vars = '';
8291     my $result_rules = '';
8292     my $comment = '';
8293     my $spacing = '';
8295     # The following flags are used to track rules spanning across
8296     # multiple paragraphs.
8297     my $is_rule = 0;            # 1 if we are processing a rule.
8298     my $discard_rule = 0;       # 1 if the current rule should not be output.
8300     # We save the conditional stack on entry, and then check to make
8301     # sure it is the same on exit.  This lets us conditonally include
8302     # other files.
8303     my @saved_cond_stack = @cond_stack;
8304     my $cond = conditional_string (@cond_stack);
8306     foreach (make_paragraphs ($file, %transform))
8307     {
8308         # Sanity checks.
8309         error $file, "blank line following trailing backslash:\n$_"
8310           if /\\$/;
8311         error $file, "comment following trailing backslash:\n$_"
8312           if /\\#/;
8314         if (/^$/)
8315         {
8316             $is_rule = 0;
8317             # Stick empty line before the incoming macro or rule.
8318             $spacing = "\n";
8319         }
8320         elsif (/$COMMENT_PATTERN/mso)
8321         {
8322             $is_rule = 0;
8323             # Stick comments before the incoming macro or rule.
8324             $comment = "$_\n";
8325         }
8327         # Handle inclusion of other files.
8328         elsif (/$INCLUDE_PATTERN/o)
8329         {
8330             if ($cond ne 'FALSE')
8331               {
8332                 my $file = ($is_am ? "$libdir/am/" : '') . $1;
8333                 # N-ary `.=' fails.
8334                 my ($com, $vars, $rules)
8335                   = file_contents_internal ($is_am, $file, %transform);
8336                 $comment .= $com;
8337                 $result_vars .= $vars;
8338                 $result_rules .= $rules;
8339               }
8340         }
8342         # Handling the conditionals.
8343         elsif (/$IF_PATTERN/o)
8344           {
8345             $cond = cond_stack_if ($1, $2, $file);
8346           }
8347         elsif (/$ELSE_PATTERN/o)
8348           {
8349             $cond = cond_stack_else ($1, $2, $file);
8350           }
8351         elsif (/$ENDIF_PATTERN/o)
8352           {
8353             $cond = cond_stack_endif ($1, $2, $file);
8354           }
8356         # Handling rules.
8357         elsif (/$RULE_PATTERN/mso)
8358         {
8359           $is_rule = 1;
8360           $discard_rule = 0;
8361           # Separate relationship from optional actions: the first
8362           # `new-line tab" not preceded by backslash (continuation
8363           # line).
8364           my $paragraph = $_;
8365           /^(.*?)(?:(?<!\\)\n(\t.*))?$/s;
8366           my ($relationship, $actions) = ($1, $2 || '');
8368           # Separate targets from dependencies: the first colon.
8369           $relationship =~ /^([^:]+\S+) *: *(.*)$/som;
8370           my ($targets, $dependencies) = ($1, $2);
8371           # Remove the escaped new lines.
8372           # I don't know why, but I have to use a tmp $flat_deps.
8373           my $flat_deps = &flatten ($dependencies);
8374           my @deps = split (' ', $flat_deps);
8376           foreach (split (' ' , $targets))
8377             {
8378               # FIXME: 1. We are not robust to people defining several targets
8379               # at once, only some of them being in %dependencies.  The
8380               # actions from the targets in %dependencies are usually generated
8381               # from the content of %actions, but if some targets in $targets
8382               # are not in %dependencies the ELSE branch will output
8383               # a rule for all $targets (i.e. the targets which are both
8384               # in %dependencies and $targets will have two rules).
8386               # FIXME: 2. The logic here is not able to output a
8387               # multi-paragraph rule several time (e.g. for each conditional
8388               # it is defined for) because it only knows the first paragraph.
8390               # FIXME: 3. We are not robust to people defining a subset
8391               # of a previously defined "multiple-target" rule.  E.g.
8392               # `foo:' after `foo bar:'.
8394               # Output only if not in FALSE.
8395               if (defined $dependencies{$_} && $cond ne 'FALSE')
8396                 {
8397                   &depend ($_, @deps);
8398                   $actions{$_} .= $actions;
8399                 }
8400               else
8401                 {
8402                   # Free-lance dependency.  Output the rule for all the
8403                   # targets instead of one by one.
8404                   my @undefined_conds =
8405                     rule_define ($targets, $file,
8406                                  $is_am ? TARGET_AUTOMAKE : TARGET_USER,
8407                                  $cond || 'TRUE', $file);
8408                   for my $undefined_cond (@undefined_conds)
8409                     {
8410                       my $condparagraph = $paragraph;
8411                       $condparagraph =~ s/^/$undefined_cond/gm;
8412                       $result_rules .= "$spacing$comment$condparagraph\n";
8413                     }
8414                   if (scalar @undefined_conds == 0)
8415                     {
8416                       # Remember to discard next paragraphs
8417                       # if they belong to this rule.
8418                       # (but see also FIXME: #2 above.)
8419                       $discard_rule = 1;
8420                     }
8421                   $comment = $spacing = '';
8422                   last;
8423                 }
8424             }
8425         }
8427         elsif (/$ASSIGNMENT_PATTERN/mso)
8428         {
8429             my ($var, $type, $val) = ($1, $2, $3);
8430             error $file, "variable `$var' with trailing backslash"
8431               if /\\$/;
8433             $is_rule = 0;
8435             # Accumulating variables must not be output.
8436             append_comments ($cond || 'TRUE', $var, $spacing, $comment);
8437             macro_define ($var, $is_am ? VAR_AUTOMAKE : VAR_MAKEFILE,
8438                           $type, $cond, $val, $file)
8439               if $cond ne 'FALSE';
8440             push (@var_list, $var);
8442             # If the user has set some variables we were in charge
8443             # of (which is detected by the first reading of
8444             # `header-vars.am'), we must not output them.
8445             $result_vars .= "$spacing$comment$_\n"
8446               if ($cond ne 'FALSE' && $type ne '+'
8447                   && exists $var_owner{$var}{$cond || 'TRUE'}
8448                   && $var_owner{$var}{$cond || 'TRUE'} == VAR_AUTOMAKE);
8450             $comment = $spacing = '';
8451         }
8452         else
8453         {
8454             # This isn't an error; it is probably some tokens which
8455             # configure is supposed to replace, such as `@SET-MAKE@',
8456             # or some part of a rule cut by an if/endif.
8457             if ($cond ne 'FALSE' && ! ($is_rule && $discard_rule))
8458               {
8459                 s/^/make_condition (@cond_stack)/gme;
8460                 $result_rules .= "$spacing$comment$_\n";
8461               }
8462             $comment = $spacing = '';
8463         }
8464     }
8466     err_am (@cond_stack ?
8467             "unterminated conditionals: @cond_stack" :
8468             "too many conditionals closed in include file")
8469       if "@saved_cond_stack" ne "@cond_stack";
8471     return ($comment, $result_vars, $result_rules);
8475 # $CONTENTS
8476 # &file_contents ($BASENAME, [%TRANSFORM])
8477 # ----------------------------------------
8478 # Return contents of a file from $libdir/am, automatically skipping
8479 # macros or rules which are already known.
8480 sub file_contents ($%)
8482     my ($basename, %transform) = @_;
8483     my ($comments, $variables, $rules) =
8484       file_contents_internal (1, "$libdir/am/$basename.am", %transform);
8485     return "$comments$variables$rules";
8489 # $REGEXP
8490 # &transform (%PAIRS)
8491 # -------------------
8492 # Foreach ($TOKEN, $VAL) in %PAIRS produce a replacement expression suitable
8493 # for file_contents which:
8494 #   - replaces %$TOKEN% with $VAL,
8495 #   - enables/disables ?$TOKEN? and ?!$TOKEN?,
8496 #   - replaces %?$TOKEN% with TRUE or FALSE.
8497 sub transform (%)
8499     my (%pairs) = @_;
8500     my $result = '';
8502     while (my ($token, $val) = each %pairs)
8503     {
8504         $result .= "s/\Q%$token%\E/\Q$val\E/gm;";
8505         if ($val)
8506         {
8507             $result .= "s/\Q?$token?\E//gm;s/^.*\Q?!$token?\E.*\\n//gm;";
8508             $result .= "s/\Q%?$token%\E/TRUE/gm;";
8509         }
8510         else
8511         {
8512             $result .= "s/\Q?!$token?\E//gm;s/^.*\Q?$token?\E.*\\n//gm;";
8513             $result .= "s/\Q%?$token%\E/FALSE/gm;";
8514         }
8515     }
8517     return $result;
8521 # &append_exeext ($MACRO)
8522 # -----------------------
8523 # Macro is an Automake magic macro which primary is PROGRAMS, e.g.
8524 # bin_PROGRAMS.  Make sure these programs have $(EXEEXT) appended.
8525 sub append_exeext ($)
8527   my ($macro) = @_;
8529   prog_error "append_exeext ($macro)"
8530     unless $macro =~ /_PROGRAMS$/;
8532   my @conds = variable_conditions_recursive ($macro);
8534   my @condvals;
8535   foreach my $cond (@conds)
8536     {
8537       my @one_binlist = ();
8538       my @condval = variable_value_as_list_recursive ($macro, $cond);
8539       foreach my $rcurs (@condval)
8540         {
8541           # Skip autoconf substs.  Also skip if the user
8542           # already applied $(EXEEXT).
8543           if ($rcurs =~ /^\@.*\@$/ || $rcurs =~ /\$\(EXEEXT\)$/)
8544             {
8545               push (@one_binlist, $rcurs);
8546             }
8547           else
8548             {
8549               push (@one_binlist, $rcurs . '$(EXEEXT)');
8550             }
8551         }
8553       push (@condvals, $cond);
8554       push (@condvals, "@one_binlist");
8555     }
8557   macro_delete ($macro);
8558   while (@condvals)
8559     {
8560       my $cond = shift (@condvals);
8561       my @val = split (' ', shift (@condvals));
8562       define_pretty_variable ($macro, $cond, @val);
8563     }
8567 # @PREFIX
8568 # &am_primary_prefixes ($PRIMARY, $CAN_DIST, @PREFIXES)
8569 # -----------------------------------------------------
8570 # Find all variable prefixes that are used for install directories.  A
8571 # prefix `zar' qualifies iff:
8573 # * `zardir' is a variable.
8574 # * `zar_PRIMARY' is a variable.
8576 # As a side effect, it looks for misspellings.  It is an error to have
8577 # a variable ending in a "reserved" suffix whose prefix is unknown, eg
8578 # "bni_PROGRAMS".  However, unusual prefixes are allowed if a variable
8579 # of the same name (with "dir" appended) exists.  For instance, if the
8580 # variable "zardir" is defined, then "zar_PROGRAMS" becomes valid.
8581 # This is to provide a little extra flexibility in those cases which
8582 # need it.
8583 sub am_primary_prefixes ($$@)
8585   my ($primary, $can_dist, @prefixes) = @_;
8587   local $_;
8588   my %valid = map { $_ => 0 } @prefixes;
8589   $valid{'EXTRA'} = 0;
8590   foreach my $varname (keys %var_value)
8591     {
8592       # Automake is allowed to define variables that look like primaries
8593       # but which aren't.  E.g. INSTALL_sh_DATA.
8594       # Autoconf can also define variables like INSTALL_DATA, so
8595       # ignore all configure variables (at least those which are not
8596       # redefined in Makefile.am).
8597       # FIXME: We should make sure that these variables are not
8598       # conditionally defined (or else adjust the condition below).
8599       next
8600         if (exists $var_owner{$varname}
8601             && exists $var_owner{$varname}{'TRUE'}
8602             && $var_owner{$varname}{'TRUE'} != VAR_MAKEFILE);
8604       if ($varname =~ /^(nobase_)?(dist_|nodist_)?(.*)_$primary$/)
8605         {
8606           my ($base, $dist, $X) = ($1 || '', $2 || '', $3 || '');
8607           if ($dist ne '' && ! $can_dist)
8608             {
8609               err_var ($varname,
8610                        "invalid variable `$varname': `dist' is forbidden");
8611             }
8612           # Standard directories must be explicitely allowed.
8613           elsif (! defined $valid{$X} && exists $standard_prefix{$X})
8614             {
8615               err_var ($varname,
8616                        "`${X}dir' is not a legitimate directory " .
8617                        "for `$primary'");
8618             }
8619           # A not explicitely valid directory is allowed if Xdir is defined.
8620           elsif (! defined $valid{$X} &&
8621                  require_variables_for_macro ($varname, "`$varname' is used",
8622                                               "${X}dir"))
8623             {
8624               # Nothing to do.  Any error message has been output
8625               # by require_variables_for_macro.
8626             }
8627           else
8628             {
8629               # Ensure all extended prefixes are actually used.
8630               $valid{"$base$dist$X"} = 1;
8631             }
8632         }
8633     }
8635   # Return only those which are actually defined.
8636   return sort grep { variable_defined ($_ . '_' . $primary) } keys %valid;
8640 # Handle `where_HOW' variable magic.  Does all lookups, generates
8641 # install code, and possibly generates code to define the primary
8642 # variable.  The first argument is the name of the .am file to munge,
8643 # the second argument is the primary variable (eg HEADERS), and all
8644 # subsequent arguments are possible installation locations.  Returns
8645 # list of all values of all _HOW targets.
8647 # FIXME: this should be rewritten to be cleaner.  It should be broken
8648 # up into multiple functions.
8650 # Usage is: am_install_var (OPTION..., file, HOW, where...)
8651 sub am_install_var
8653     my (@args) = @_;
8655     my $do_require = 1;
8656     my $can_dist = 0;
8657     my $default_dist = 0;
8658     while (@args)
8659     {
8660         if ($args[0] eq '-noextra')
8661         {
8662             $do_require = 0;
8663         }
8664         elsif ($args[0] eq '-candist')
8665         {
8666             $can_dist = 1;
8667         }
8668         elsif ($args[0] eq '-defaultdist')
8669         {
8670             $default_dist = 1;
8671             $can_dist = 1;
8672         }
8673         elsif ($args[0] !~ /^-/)
8674         {
8675             last;
8676         }
8677         shift (@args);
8678     }
8680     my ($file, $primary, @prefix) = @args;
8682     # Now that configure substitutions are allowed in where_HOW
8683     # variables, it is an error to actually define the primary.  We
8684     # allow `JAVA', as it is customarily used to mean the Java
8685     # interpreter.  This is but one of several Java hacks.  Similarly,
8686     # `PYTHON' is customarily used to mean the Python interpreter.
8687     reject_var $primary, "`$primary' is an anachronism"
8688       unless $primary eq 'JAVA' || $primary eq 'PYTHON';
8690     # Get the prefixes which are valid and actually used.
8691     @prefix = am_primary_prefixes ($primary, $can_dist, @prefix);
8693     # If a primary includes a configure substitution, then the EXTRA_
8694     # form is required.  Otherwise we can't properly do our job.
8695     my $require_extra;
8697     my @used = ();
8698     my @result = ();
8700     # True if the iteration is the first one.  Used for instance to
8701     # output parts of the associated file only once.
8702     my $first = 1;
8703     foreach my $X (@prefix)
8704     {
8705         my $nodir_name = $X;
8706         my $one_name = $X . '_' . $primary;
8708         my $strip_subdir = 1;
8709         # If subdir prefix should be preserved, do so.
8710         if ($nodir_name =~ /^nobase_/)
8711           {
8712             $strip_subdir = 0;
8713             $nodir_name =~ s/^nobase_//;
8714           }
8716         # If files should be distributed, do so.
8717         my $dist_p = 0;
8718         if ($can_dist)
8719           {
8720             $dist_p = (($default_dist && $nodir_name !~ /^nodist_/)
8721                        || (! $default_dist && $nodir_name =~ /^dist_/));
8722             $nodir_name =~ s/^(dist|nodist)_//;
8723           }
8725         # Append actual contents of where_PRIMARY variable to
8726         # result.
8727         foreach my $rcurs (&variable_value_as_list_recursive ($one_name, 'all'))
8728           {
8729             # Skip configure substitutions.  Possibly bogus.
8730             if ($rcurs =~ /^\@.*\@$/)
8731               {
8732                 if ($nodir_name eq 'EXTRA')
8733                   {
8734                     err_var ($one_name,
8735                              "`$one_name' contains configure substitution, "
8736                              . "but shouldn't");
8737                   }
8738                 # Check here to make sure variables defined in
8739                 # configure.ac do not imply that EXTRA_PRIMARY
8740                 # must be defined.
8741                 elsif (! defined $configure_vars{$one_name})
8742                   {
8743                     $require_extra = $one_name
8744                       if $do_require;
8745                   }
8747                 next;
8748               }
8750             push (@result, $rcurs);
8751           }
8752         # A blatant hack: we rewrite each _PROGRAMS primary to include
8753         # EXEEXT.
8754         append_exeext ($one_name)
8755           if $primary eq 'PROGRAMS';
8756         # "EXTRA" shouldn't be used when generating clean targets,
8757         # all, or install targets.  We used to warn if EXTRA_FOO was
8758         # defined uselessly, but this was annoying.
8759         next
8760           if $nodir_name eq 'EXTRA';
8762         if ($nodir_name eq 'check')
8763           {
8764             push (@check, '$(' . $one_name . ')');
8765           }
8766         else
8767           {
8768             push (@used, '$(' . $one_name . ')');
8769           }
8771         # Is this to be installed?
8772         my $install_p = $nodir_name ne 'noinst' && $nodir_name ne 'check';
8774         # If so, with install-exec? (or install-data?).
8775         my $exec_p = ($nodir_name =~ /$EXEC_DIR_PATTERN/o);
8777         my $check_options_p = $install_p
8778                               && defined $options{'std-options'};
8780         # Singular form of $PRIMARY.
8781         (my $one_primary = $primary) =~ s/S$//;
8782         $output_rules .= &file_contents ($file,
8783                                          ('FIRST' => $first,
8785                                           'PRIMARY'     => $primary,
8786                                           'ONE_PRIMARY' => $one_primary,
8787                                           'DIR'         => $X,
8788                                           'NDIR'        => $nodir_name,
8789                                           'BASE'        => $strip_subdir,
8791                                           'EXEC'    => $exec_p,
8792                                           'INSTALL' => $install_p,
8793                                           'DIST'    => $dist_p,
8794                                           'CK-OPTS' => $check_options_p));
8796         $first = 0;
8797     }
8799     # The JAVA variable is used as the name of the Java interpreter.
8800     # The PYTHON variable is used as the name of the Python interpreter.
8801     if (@used && $primary ne 'JAVA' && $primary ne 'PYTHON')
8802     {
8803         # Define it.
8804         define_pretty_variable ($primary, '', @used);
8805         $output_vars .= "\n";
8806     }
8808     err_var ($require_extra,
8809              "`$require_extra' contains configure substitution,\n"
8810              . "but `EXTRA_$primary' not defined")
8811       if ($require_extra && ! variable_defined ('EXTRA_' . $primary));
8813     # Push here because PRIMARY might be configure time determined.
8814     push (@all, '$(' . $primary . ')')
8815         if @used && $primary ne 'JAVA' && $primary ne 'PYTHON';
8817     # Make the result unique.  This lets the user use conditionals in
8818     # a natural way, but still lets us program lazily -- we don't have
8819     # to worry about handling a particular object more than once.
8820     return uniq (sort @result);
8824 ################################################################
8826 # Each key in this hash is the name of a directory holding a
8827 # Makefile.in.  These variables are local to `is_make_dir'.
8828 my %make_dirs = ();
8829 my $make_dirs_set = 0;
8831 sub is_make_dir
8833     my ($dir) = @_;
8834     if (! $make_dirs_set)
8835     {
8836         foreach my $iter (@configure_input_files)
8837         {
8838             $make_dirs{dirname ($iter)} = 1;
8839         }
8840         # We also want to notice Makefile.in's.
8841         foreach my $iter (@other_input_files)
8842         {
8843             if ($iter =~ /Makefile\.in$/)
8844             {
8845                 $make_dirs{dirname ($iter)} = 1;
8846             }
8847         }
8848         $make_dirs_set = 1;
8849     }
8850     return defined $make_dirs{$dir};
8853 ################################################################
8855 # This variable is local to the "require file" set of functions.
8856 my @require_file_paths = ();
8859 # &maybe_push_required_file ($DIR, $FILE, $FULLFILE)
8860 # --------------------------------------------------
8861 # See if we want to push this file onto dist_common.  This function
8862 # encodes the rules for deciding when to do so.
8863 sub maybe_push_required_file
8865     my ($dir, $file, $fullfile) = @_;
8867     if ($dir eq $relative_dir)
8868     {
8869         push_dist_common ($file);
8870         return 1;
8871     }
8872     elsif ($relative_dir eq '.' && ! &is_make_dir ($dir))
8873     {
8874         # If we are doing the topmost directory, and the file is in a
8875         # subdir which does not have a Makefile, then we distribute it
8876         # here.
8877         push_dist_common ($fullfile);
8878         return 1;
8879     }
8880     return 0;
8884 # &require_file_internal ($WHERE, $MYSTRICT, @FILES)
8885 # --------------------------------------------------
8886 # Verify that the file must exist in the current directory.
8887 # $MYSTRICT is the strictness level at which this file becomes required.
8889 # Must set require_file_paths before calling this function.
8890 # require_file_paths is set to hold a single directory (the one in
8891 # which the first file was found) before return.
8892 sub require_file_internal ($$@)
8894     my ($where, $mystrict, @files) = @_;
8896     foreach my $file (@files)
8897     {
8898         my $fullfile;
8899         my $errdir;
8900         my $errfile;
8901         my $save_dir;
8903         my $found_it = 0;
8904         my $dangling_sym = 0;
8905         foreach my $dir (@require_file_paths)
8906         {
8907             $fullfile = $dir . "/" . $file;
8908             $errdir = $dir unless $errdir;
8910             # Use different name for "error filename".  Otherwise on
8911             # an error the bad file will be reported as eg
8912             # `../../install-sh' when using the default
8913             # config_aux_path.
8914             $errfile = $errdir . '/' . $file;
8916             if (-l $fullfile && ! -f $fullfile)
8917             {
8918                 $dangling_sym = 1;
8919                 last;
8920             }
8921             elsif (-f $fullfile)
8922             {
8923                 $found_it = 1;
8924                 maybe_push_required_file ($dir, $file, $fullfile);
8925                 $save_dir = $dir;
8926                 last;
8927             }
8928         }
8930         # `--force-missing' only has an effect if `--add-missing' is
8931         # specified.
8932         if ($found_it && (! $add_missing || ! $force_missing))
8933         {
8934             # Prune the path list.
8935             @require_file_paths = $save_dir;
8936         }
8937         else
8938         {
8939             # If we've already looked for it, we're done.  You might
8940             # wonder why we don't do this before searching for the
8941             # file.  If we do that, then something like
8942             # AC_OUTPUT(subdir/foo foo) will fail to put foo.in into
8943             # DIST_COMMON.
8944             if (! $found_it)
8945             {
8946                 next if defined $require_file_found{$fullfile};
8947                 $require_file_found{$fullfile} = 1;
8948             }
8950             if ($strictness >= $mystrict)
8951             {
8952                 if ($dangling_sym && $add_missing)
8953                 {
8954                     unlink ($fullfile);
8955                 }
8957                 my $trailer = '';
8958                 my $suppress = 0;
8960                 # Only install missing files according to our desired
8961                 # strictness level.
8962                 my $message = "required file `$errfile' not found";
8963                 if ($add_missing)
8964                 {
8965                     if (-f ("$libdir/$file"))
8966                     {
8967                         $suppress = 1;
8969                         # Install the missing file.  Symlink if we
8970                         # can, copy if we must.  Note: delete the file
8971                         # first, in case it is a dangling symlink.
8972                         $message = "installing `$errfile'";
8973                         # Windows Perl will hang if we try to delete a
8974                         # file that doesn't exist.
8975                         unlink ($errfile) if -f $errfile;
8976                         if ($symlink_exists && ! $copy_missing)
8977                         {
8978                             if (! symlink ("$libdir/$file", $errfile))
8979                             {
8980                                 $suppress = 0;
8981                                 $trailer = "; error while making link: $!";
8982                             }
8983                         }
8984                         elsif (system ('cp', "$libdir/$file", $errfile))
8985                         {
8986                             $suppress = 0;
8987                             $trailer = "\n    error while copying";
8988                         }
8989                     }
8991                     if (! maybe_push_required_file (dirname ($errfile),
8992                                                     $file, $errfile))
8993                     {
8994                         if (! $found_it)
8995                         {
8996                             # We have added the file but could not push it
8997                             # into DIST_COMMON (probably because this is
8998                             # an auxiliary file and we are not processing
8999                             # the top level Makefile). This is unfortunate,
9000                             # since it means we are using a file which is not
9001                             # distributed!
9003                             # Get Automake to be run again: on the second
9004                             # run the file will be found, and pushed into
9005                             # the toplevel DIST_COMMON automatically.
9006                             $automake_needs_to_reprocess_all_files = 1;
9007                         }
9008                     }
9010                     # Prune the path list.
9011                     @require_file_paths = &dirname ($errfile);
9012                 }
9014                 # If --force-missing was specified, and we have
9015                 # actually found the file, then do nothing.
9016                 next
9017                     if $found_it && $force_missing;
9019                 # If we couldn' install the file, but it is a target in
9020                 # the Makefile, don't print anything.  This allows files
9021                 # like README, AUTHORS, or THANKS to be generated.
9022                 next
9023                   if !$suppress && target_defined ($file);
9025                 msg ($suppress ? 'note' : 'error', $where, "$message$trailer");
9026             }
9027         }
9028     }
9031 # &require_file ($WHERE, $MYSTRICT, @FILES)
9032 # -----------------------------------------
9033 sub require_file ($$@)
9035     my ($where, $mystrict, @files) = @_;
9036     @require_file_paths = $relative_dir;
9037     require_file_internal ($where, $mystrict, @files);
9040 # &require_file_with_macro ($COND, $MACRO, $MYSTRICT, @FILES)
9041 # -----------------------------------------------------------
9042 sub require_file_with_macro ($$$@)
9044     my ($cond, $macro, $mystrict, @files) = @_;
9045     require_file ($var_location{$macro}{$cond}, $mystrict, @files);
9049 # &require_conf_file ($WHERE, $MYSTRICT, @FILES)
9050 # ----------------------------------------------
9051 # Looks in configuration path, as specified by AC_CONFIG_AUX_DIR.
9052 sub require_conf_file ($$@)
9054     my ($where, $mystrict, @files) = @_;
9055     @require_file_paths = @config_aux_path;
9056     require_file_internal ($where, $mystrict, @files);
9057     my $dir = $require_file_paths[0];
9058     @config_aux_path = @require_file_paths;
9059      # Avoid unsightly '/.'s.
9060     $config_aux_dir = '$(top_srcdir)' . ($dir eq '.' ? "" : "/$dir");
9064 # &require_conf_file_with_macro ($COND, $MACRO, $MYSTRICT, @FILES)
9065 # ----------------------------------------------------------------
9066 sub require_conf_file_with_macro ($$$@)
9068     my ($cond, $macro, $mystrict, @files) = @_;
9069     require_conf_file ($var_location{$macro}{$cond}, $mystrict, @files);
9072 ################################################################
9074 # &require_build_directory ($DIRECTORY)
9075 # ------------------------------------
9076 # Emit rules to create $DIRECTORY if needed, and return
9077 # the file that any target requiring this directory should be made
9078 # dependent upon.
9079 sub require_build_directory ($)
9081   my $directory = shift;
9082   my $dirstamp = "$directory/\$(am__dirstamp)";
9084   # Don't emit the rule twice.
9085   if (! defined $directory_map{$directory})
9086     {
9087       $directory_map{$directory} = 1;
9089       # Set a variable for the dirstamp basename.
9090       define_pretty_variable ('am__dirstamp', 'TRUE',
9091                               '$(am__leading_dot)dirstamp')
9092         unless variable_defined ('am__dirstamp');
9094       # Directory must be removed by `make distclean'.
9095       $clean_files{$dirstamp} = DIST_CLEAN;
9097       $output_rules .= ("$dirstamp:\n"
9098                         . "\t\@\$(mkinstalldirs) $directory\n"
9099                         . "\t\@: > $dirstamp\n");
9100     }
9102   return $dirstamp;
9105 # &require_build_directory_maybe ($FILE)
9106 # --------------------------------------
9107 # If $FILE lies in a subdirectory, emit a rule to create this
9108 # directory and return the file that $FILE should be made
9109 # dependent upon.  Otherwise, just return the empty string.
9110 sub require_build_directory_maybe ($)
9112     my $file = shift;
9113     my $directory = dirname ($file);
9115     if ($directory ne '.')
9116     {
9117         return require_build_directory ($directory);
9118     }
9119     else
9120     {
9121         return '';
9122     }
9125 ################################################################
9127 # Push a list of files onto dist_common.
9128 sub push_dist_common
9130   prog_error "push_dist_common run after handle_dist"
9131     if $handle_dist_run;
9132   macro_define ('DIST_COMMON', VAR_AUTOMAKE, '+', '', "@_", '');
9136 # Set strictness.
9137 sub set_strictness
9139   $strictness_name = $_[0];
9141   # FIXME: 'portability' warnings are currently disabled by default.
9142   # Eventually we want to turn them on in GNU and GNITS modes, but
9143   # we don't do this yet in Automake 1.7 to help the 1.6/1.7 transition.
9144   #
9145   # Indeed there would be only two ways to get rid of these new warnings:
9146   #  1. adjusting Makefile.am
9147   #     This is not always easy (or wanted).  Consider %-rules or
9148   #     $(function args) variables.
9149   #  2. using -Wno-portability
9150   #     This means there is no way to have the same Makefile.am
9151   #     working both with Automake 1.6 and 1.7 (since 1.6 does not
9152   #     understand -Wno-portability).
9153   #
9154   # In Automake 1.8 (or whatever it is called) we can turn these
9155   # warnings on, since -Wno-portability will not be an issue for
9156   # the 1.7/1.8 transition.
9157   if ($strictness_name eq 'gnu')
9158     {
9159       $strictness = GNU;
9160       setup_channel 'error-gnu', silent => 0;
9161       setup_channel 'error-gnu/warn', silent => 0, type => 'error';
9162       setup_channel 'error-gnits', silent => 1;
9163       # setup_channel 'portability', silent => 0;
9164       setup_channel 'gnu', silent => 0;
9165     }
9166   elsif ($strictness_name eq 'gnits')
9167     {
9168       $strictness = GNITS;
9169       setup_channel 'error-gnu', silent => 0;
9170       setup_channel 'error-gnu/warn', silent => 0, type => 'error';
9171       setup_channel 'error-gnits', silent => 0;
9172       # setup_channel 'portability', silent => 0;
9173       setup_channel 'gnu', silent => 0;
9174     }
9175   elsif ($strictness_name eq 'foreign')
9176     {
9177       $strictness = FOREIGN;
9178       setup_channel 'error-gnu', silent => 1;
9179       setup_channel 'error-gnu/warn', silent => 0, type => 'warning';
9180       setup_channel 'error-gnits', silent => 1;
9181       # setup_channel 'portability', silent => 1;
9182       setup_channel 'gnu', silent => 1;
9183     }
9184   else
9185     {
9186       prog_error "level `$strictness_name' not recognized\n";
9187     }
9191 ################################################################
9193 # Glob something.  Do this to avoid indentation screwups everywhere we
9194 # want to glob.  Gross!
9195 sub my_glob
9197     my ($pat) = @_;
9198     return <${pat}>;
9201 ################################################################
9203 # INTEGER
9204 # require_variables ($WHERE, $REASON, $COND, @VARIABLES)
9205 # ------------------------------------------------------
9206 # Make sure that each supplied variable is defined in $COND.
9207 # Otherwise, issue a warning.  If we know which macro can
9208 # define this variable, hint the user.
9209 # Return the number of undefined variables.
9210 sub require_variables ($$$@)
9212   my ($where, $reason, $cond, @vars) = @_;
9213   my $res = 0;
9214   $reason .= ' but ' unless $reason eq '';
9216  VARIABLE:
9217   foreach my $var (@vars)
9218     {
9219       # Nothing to do if the variable exists.  The $configure_vars test
9220       # needed for strange variables like AMDEPBACKSLASH or ANSI2KNR
9221       # that are AC_SUBST'ed but never macro_define'd.
9222       next VARIABLE
9223         if ((exists $var_value{$var} && exists $var_value{$var}{$cond})
9224             || exists $configure_vars{$var});
9226       my @undef_cond = variable_not_always_defined_in_cond $var, $cond;
9227       next VARIABLE
9228         unless @undef_cond;
9230       my $text = "$reason`$var' is undefined\n";
9231       if (@undef_cond && $undef_cond[0] ne 'TRUE')
9232         {
9233           $text .= ("in the following conditions:\n  "
9234                     . join ("\n  ", @undef_cond));
9235         }
9237       ++$res;
9239       if (exists $am_macro_for_var{$var})
9240         {
9241           $text .= "\nThe usual way to define `$var' is to add "
9242             . "`$am_macro_for_var{$var}'\nto `$configure_ac' and run "
9243             . "`aclocal' and `autoconf' again.";
9244         }
9245       elsif (exists $ac_macro_for_var{$var})
9246         {
9247           $text .= "\nThe usual way to define `$var' is to add "
9248             . "`$ac_macro_for_var{$var}'\nto `$configure_ac' and run "
9249             . "`autoconf' again.";
9250         }
9252       error $where, $text, uniq_scope => US_GLOBAL;
9253     }
9254   return $res;
9257 # INTEGER
9258 # require_variables_for_macro ($MACRO, $REASON, @VARIABLES)
9259 # ---------------------------------------------------------
9260 # Same as require_variables, but take a macro mame as first argument.
9261 sub require_variables_for_macro ($$@)
9263   my ($macro, $reason, @args) = @_;
9264   for my $cond (keys %{$var_value{$macro}})
9265     {
9266       return require_variables ($var_location{$macro}{$cond}, $reason,
9267                                 $cond, @args);
9268     }
9271 # Print usage information.
9272 sub usage ()
9274     print "Usage: $0 [OPTION] ... [Makefile]...
9276 Generate Makefile.in for configure from Makefile.am.
9278 Operation modes:
9279       --help               print this help, then exit
9280       --version            print version number, then exit
9281   -v, --verbose            verbosely list files processed
9282       --no-force           only update Makefile.in's that are out of date
9283   -W, --warnings=CATEGORY  report the warnings falling in CATEGORY
9285 Dependency tracking:
9286   -i, --ignore-deps      disable dependency tracking code
9287       --include-deps     enable dependency tracking code
9289 Flavors:
9290       --cygnus           assume program is part of Cygnus-style tree
9291       --foreign          set strictness to foreign
9292       --gnits            set strictness to gnits
9293       --gnu              set strictness to gnu
9295 Library files:
9296   -a, --add-missing      add missing standard files to package
9297       --libdir=DIR       directory storing library files
9298   -c, --copy             with -a, copy missing files (default is symlink)
9299   -f, --force-missing    force update of standard files
9301 Warning categories include:
9302   `gnu'           GNU coding standards (default in gnu and gnits modes)
9303   `obsolete'      obsolete features or constructions
9304   `portability'   portability issues
9305   `syntax'        dubious syntactic constructs (default)
9306   `unsupported'   unsupported or incomplete features (default)
9307   `all'           all the warnings
9308   `no-CATEGORY'   turn off warnings in CATEGORY
9309   `none'          turn off all the warnings
9310   `error'         treat warnings as errors
9313     my ($last, @lcomm);
9314     $last = '';
9315     foreach my $iter (sort ((@common_files, @common_sometimes)))
9316     {
9317         push (@lcomm, $iter) unless $iter eq $last;
9318         $last = $iter;
9319     }
9321     my @four;
9322     print "\nFiles which are automatically distributed, if found:\n";
9323     format USAGE_FORMAT =
9324   @<<<<<<<<<<<<<<<<   @<<<<<<<<<<<<<<<<   @<<<<<<<<<<<<<<<<   @<<<<<<<<<<<<<<<<
9325   $four[0],           $four[1],           $four[2],           $four[3]
9327     $~ = "USAGE_FORMAT";
9329     my $cols = 4;
9330     my $rows = int(@lcomm / $cols);
9331     my $rest = @lcomm % $cols;
9333     if ($rest)
9334     {
9335         $rows++;
9336     }
9337     else
9338     {
9339         $rest = $cols;
9340     }
9342     for (my $y = 0; $y < $rows; $y++)
9343     {
9344         @four = ("", "", "", "");
9345         for (my $x = 0; $x < $cols; $x++)
9346         {
9347             last if $y + 1 == $rows && $x == $rest;
9349             my $idx = (($x > $rest)
9350                        ?  ($rows * $rest + ($rows - 1) * ($x - $rest))
9351                        : ($rows * $x));
9353             $idx += $y;
9354             $four[$x] = $lcomm[$idx];
9355         }
9356         write;
9357     }
9359     print "\nReport bugs to <bug-automake\@gnu.org>.\n";
9361     # --help always returns 0 per GNU standards.
9362     exit 0;
9366 # &version ()
9367 # -----------
9368 # Print version information
9369 sub version ()
9371   print <<EOF;
9372 automake (GNU $PACKAGE) $VERSION
9373 Written by Tom Tromey <tromey\@redhat.com>.
9375 Copyright 2003 Free Software Foundation, Inc.
9376 This is free software; see the source for copying conditions.  There is NO
9377 warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
9379   # --version always returns 0 per GNU standards.
9380   exit 0;
9383 ### Setup "GNU" style for perl-mode and cperl-mode.
9384 ## Local Variables:
9385 ## perl-indent-level: 2
9386 ## perl-continued-statement-offset: 2
9387 ## perl-continued-brace-offset: 0
9388 ## perl-brace-offset: 0
9389 ## perl-brace-imaginary-offset: 0
9390 ## perl-label-offset: -2
9391 ## cperl-indent-level: 2
9392 ## cperl-brace-offset: 0
9393 ## cperl-continued-brace-offset: 0
9394 ## cperl-label-offset: -2
9395 ## cperl-extra-newline-before-brace: t
9396 ## cperl-merge-trailing-else: nil
9397 ## cperl-continued-statement-offset: 2
9398 ## End: