Avoid expand-before-require warning from newer autoconf.
[automake/ericb.git] / automake.in
blob5523d750912b7c8b97c8a961df558bfcd79c20f5
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,
10 # 2003, 2004, 2005, 2006, 2007, 2008  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 3, 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, see <http://www.gnu.org/licenses/>.
25 # Originally written by David Mackenzie <djm@gnu.ai.mit.edu>.
26 # Perl reimplementation by Tom Tromey <tromey@redhat.com>, and
27 # Alexandre Duret-Lutz <adl@gnu.org>.
29 package Language;
31 BEGIN
33   my $perllibdir = $ENV{'perllibdir'} || '@datadir@/@PACKAGE@-@APIVERSION@';
34   unshift @INC, (split '@PATH_SEPARATOR@', $perllibdir);
36   # Override SHELL.  This is required on DJGPP so that system() uses
37   # bash, not COMMAND.COM which doesn't quote arguments properly.
38   # Other systems aren't expected to use $SHELL when Automake
39   # runs, but it should be safe to drop the `if DJGPP' guard if
40   # it turns up other systems need the same thing.  After all,
41   # if SHELL is used, ./configure's SHELL is always better than
42   # the user's SHELL (which may be something like tcsh).
43   $ENV{'SHELL'} = '@SHELL@' if exists $ENV{'DJGPP'};
46 use Automake::Struct;
47 struct (# Short name of the language (c, f77...).
48         'name' => "\$",
49         # Nice name of the language (C, Fortran 77...).
50         'Name' => "\$",
52         # List of configure variables which must be defined.
53         'config_vars' => '@',
55         'ansi'    => "\$",
56         # `pure' is `1' or `'.  A `pure' language is one where, if
57         # all the files in a directory are of that language, then we
58         # do not require the C compiler or any code to call it.
59         'pure'   => "\$",
61         'autodep' => "\$",
63         # Name of the compiling variable (COMPILE).
64         'compiler'  => "\$",
65         # Content of the compiling variable.
66         'compile'  => "\$",
67         # Flag to require compilation without linking (-c).
68         'compile_flag' => "\$",
69         'extensions' => '@',
70         # A subroutine to compute a list of possible extensions of
71         # the product given the input extensions.
72         # (defaults to a subroutine which returns ('.$(OBJEXT)', '.lo'))
73         'output_extensions' => "\$",
74         # A list of flag variables used in 'compile'.
75         # (defaults to [])
76         'flags' => "@",
78         # Any tag to pass to libtool while compiling.
79         'libtool_tag' => "\$",
81         # The file to use when generating rules for this language.
82         # The default is 'depend2'.
83         'rule_file' => "\$",
85         # Name of the linking variable (LINK).
86         'linker' => "\$",
87         # Content of the linking variable.
88         'link' => "\$",
90         # Name of the linker variable (LD).
91         'lder' => "\$",
92         # Content of the linker variable ($(CC)).
93         'ld' => "\$",
95         # Flag to specify the output file (-o).
96         'output_flag' => "\$",
97         '_finish' => "\$",
99         # This is a subroutine which is called whenever we finally
100         # determine the context in which a source file will be
101         # compiled.
102         '_target_hook' => "\$",
104         # If TRUE, nodist_ sources will be compiled using specific rules
105         # (i.e. not inference rules).  The default is FALSE.
106         'nodist_specific' => "\$");
109 sub finish ($)
111   my ($self) = @_;
112   if (defined $self->_finish)
113     {
114       &{$self->_finish} ();
115     }
118 sub target_hook ($$$$%)
120     my ($self) = @_;
121     if (defined $self->_target_hook)
122     {
123         &{$self->_target_hook} (@_);
124     }
127 package Automake;
129 use strict;
130 use Automake::Config;
131 BEGIN
133   if ($perl_threads)
134     {
135       require threads;
136       import threads;
137       require Thread::Queue;
138       import Thread::Queue;
139     }
141 use Automake::General;
142 use Automake::XFile;
143 use Automake::Channels;
144 use Automake::ChannelDefs;
145 use Automake::Configure_ac;
146 use Automake::FileUtils;
147 use Automake::Location;
148 use Automake::Condition qw/TRUE FALSE/;
149 use Automake::DisjConditions;
150 use Automake::Options;
151 use Automake::Version;
152 use Automake::Variable;
153 use Automake::VarDef;
154 use Automake::Rule;
155 use Automake::RuleDef;
156 use Automake::Wrap 'makefile_wrap';
157 use File::Basename;
158 use File::Spec;
159 use Carp;
161 ## ----------- ##
162 ## Constants.  ##
163 ## ----------- ##
165 # Some regular expressions.  One reason to put them here is that it
166 # makes indentation work better in Emacs.
168 # Writing singled-quoted-$-terminated regexes is a pain because
169 # perl-mode thinks of $' as the ${'} variable (instead of a $ followed
170 # by a closing quote.  Letting perl-mode think the quote is not closed
171 # leads to all sort of misindentations.  On the other hand, defining
172 # regexes as double-quoted strings is far less readable.  So usually
173 # we will write:
175 #  $REGEX = '^regex_value' . "\$";
177 my $IGNORE_PATTERN = '^\s*##([^#\n].*)?\n';
178 my $WHITE_PATTERN = '^\s*' . "\$";
179 my $COMMENT_PATTERN = '^#';
180 my $TARGET_PATTERN='[$a-zA-Z0-9_.@%][-.a-zA-Z0-9_(){}/$+@%]*';
181 # A rule has three parts: a list of targets, a list of dependencies,
182 # and optionally actions.
183 my $RULE_PATTERN =
184   "^($TARGET_PATTERN(?:(?:\\\\\n|\\s)+$TARGET_PATTERN)*) *:([^=].*|)\$";
186 # Only recognize leading spaces, not leading tabs.  If we recognize
187 # leading tabs here then we need to make the reader smarter, because
188 # otherwise it will think rules like `foo=bar; \' are errors.
189 my $ASSIGNMENT_PATTERN = '^ *([^ \t=:+]*)\s*([:+]?)=\s*(.*)' . "\$";
190 # This pattern recognizes a Gnits version id and sets $1 if the
191 # release is an alpha release.  We also allow a suffix which can be
192 # used to extend the version number with a "fork" identifier.
193 my $GNITS_VERSION_PATTERN = '\d+\.\d+([a-z]|\.\d+)?(-[A-Za-z0-9]+)?';
195 my $IF_PATTERN = '^if\s+(!?)\s*([A-Za-z][A-Za-z0-9_]*)\s*(?:#.*)?' . "\$";
196 my $ELSE_PATTERN =
197   '^else(?:\s+(!?)\s*([A-Za-z][A-Za-z0-9_]*))?\s*(?:#.*)?' . "\$";
198 my $ENDIF_PATTERN =
199   '^endif(?:\s+(!?)\s*([A-Za-z][A-Za-z0-9_]*))?\s*(?:#.*)?' . "\$";
200 my $PATH_PATTERN = '(\w|[+/.-])+';
201 # This will pass through anything not of the prescribed form.
202 my $INCLUDE_PATTERN = ('^include\s+'
203                        . '((\$\(top_srcdir\)/' . $PATH_PATTERN . ')'
204                        . '|(\$\(srcdir\)/' . $PATH_PATTERN . ')'
205                        . '|([^/\$]' . $PATH_PATTERN . '))\s*(#.*)?' . "\$");
207 # Match `-d' as a command-line argument in a string.
208 my $DASH_D_PATTERN = "(^|\\s)-d(\\s|\$)";
209 # Directories installed during 'install-exec' phase.
210 my $EXEC_DIR_PATTERN =
211   '^(?:bin|sbin|libexec|sysconf|localstate|lib|pkglib|.*exec.*)' . "\$";
213 # Values for AC_CANONICAL_*
214 use constant AC_CANONICAL_BUILD  => 1;
215 use constant AC_CANONICAL_HOST   => 2;
216 use constant AC_CANONICAL_TARGET => 3;
218 # Values indicating when something should be cleaned.
219 use constant MOSTLY_CLEAN     => 0;
220 use constant CLEAN            => 1;
221 use constant DIST_CLEAN       => 2;
222 use constant MAINTAINER_CLEAN => 3;
224 # Libtool files.
225 my @libtool_files = qw(ltmain.sh config.guess config.sub);
226 # ltconfig appears here for compatibility with old versions of libtool.
227 my @libtool_sometimes = qw(ltconfig ltcf-c.sh ltcf-cxx.sh ltcf-gcj.sh);
229 # Commonly found files we look for and automatically include in
230 # DISTFILES.
231 my @common_files =
232     (qw(ABOUT-GNU ABOUT-NLS AUTHORS BACKLOG COPYING COPYING.DOC COPYING.LIB
233         COPYING.LESSER ChangeLog INSTALL NEWS README THANKS TODO
234         ansi2knr.1 ansi2knr.c compile config.guess config.rpath config.sub
235         depcomp elisp-comp install-sh libversion.in mdate-sh missing
236         mkinstalldirs py-compile texinfo.tex ylwrap),
237      @libtool_files, @libtool_sometimes);
239 # Commonly used files we auto-include, but only sometimes.  This list
240 # is used for the --help output only.
241 my @common_sometimes =
242   qw(aclocal.m4 acconfig.h config.h.top config.h.bot configure
243      configure.ac configure.in stamp-vti);
245 # Standard directories from the GNU Coding Standards, and additional
246 # pkg* directories from Automake.  Stored in a hash for fast member check.
247 my %standard_prefix =
248     map { $_ => 1 } (qw(bin data dataroot dvi exec html include info
249                         lib libexec lisp localstate man man1 man2 man3
250                         man4 man5 man6 man7 man8 man9 oldinclude pdf
251                         pkgdatadir pkgincludedir pkglibdir pkglibexecdir
252                         ps sbin sharedstate sysconf));
254 # Copyright on generated Makefile.ins.
255 my $gen_copyright = "\
256 # Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002,
257 # 2003, 2004, 2005, 2006, 2007, 2008  Free Software Foundation, Inc.
258 # This Makefile.in is free software; the Free Software Foundation
259 # gives unlimited permission to copy and/or distribute it,
260 # with or without modifications, as long as this notice is preserved.
262 # This program is distributed in the hope that it will be useful,
263 # but WITHOUT ANY WARRANTY, to the extent permitted by law; without
264 # even the implied warranty of MERCHANTABILITY or FITNESS FOR A
265 # PARTICULAR PURPOSE.
268 # These constants are returned by the lang_*_rewrite functions.
269 # LANG_SUBDIR means that the resulting object file should be in a
270 # subdir if the source file is.  In this case the file name cannot
271 # have `..' components.
272 use constant LANG_IGNORE  => 0;
273 use constant LANG_PROCESS => 1;
274 use constant LANG_SUBDIR  => 2;
276 # These are used when keeping track of whether an object can be built
277 # by two different paths.
278 use constant COMPILE_LIBTOOL  => 1;
279 use constant COMPILE_ORDINARY => 2;
281 # We can't always associate a location to a variable or a rule,
282 # when it's defined by Automake.  We use INTERNAL in this case.
283 use constant INTERNAL => new Automake::Location;
285 # Serialization keys for message queues.
286 use constant {
287   QUEUE_MESSAGE   => "msg",
288   QUEUE_CONF_FILE => "conf file",
289   QUEUE_LOCATION  => "location",
290   QUEUE_STRING    => "string"
294 ## ---------------------------------- ##
295 ## Variables related to the options.  ##
296 ## ---------------------------------- ##
298 # TRUE if we should always generate Makefile.in.
299 my $force_generation = 1;
301 # From the Perl manual.
302 my $symlink_exists = (eval 'symlink ("", "");', $@ eq '');
304 # TRUE if missing standard files should be installed.
305 my $add_missing = 0;
307 # TRUE if we should copy missing files; otherwise symlink if possible.
308 my $copy_missing = 0;
310 # TRUE if we should always update files that we know about.
311 my $force_missing = 0;
314 ## ---------------------------------------- ##
315 ## Variables filled during files scanning.  ##
316 ## ---------------------------------------- ##
318 # Name of the configure.ac file.
319 my $configure_ac;
321 # Files found by scanning configure.ac for LIBOBJS.
322 my %libsources = ();
324 # Names used in AC_CONFIG_HEADER call.
325 my @config_headers = ();
327 # Names used in AC_CONFIG_LINKS call.
328 my @config_links = ();
330 # Directory where output files go.  Actually, output files are
331 # relative to this directory.
332 my $output_directory;
334 # List of Makefile.am's to process, and their corresponding outputs.
335 my @input_files = ();
336 my %output_files = ();
338 # Complete list of Makefile.am's that exist.
339 my @configure_input_files = ();
341 # List of files in AC_CONFIG_FILES/AC_OUTPUT without Makefile.am's,
342 # and their outputs.
343 my @other_input_files = ();
344 # Where each AC_CONFIG_FILES/AC_OUTPUT/AC_CONFIG_LINK/AC_CONFIG_HEADER appears.
345 # The keys are the files created by these macros.
346 my %ac_config_files_location = ();
347 # The condition under which AC_CONFIG_FOOS appears.
348 my %ac_config_files_condition = ();
350 # Directory to search for configure-required files.  This
351 # will be computed by &locate_aux_dir and can be set using
352 # AC_CONFIG_AUX_DIR in configure.ac.
353 # $CONFIG_AUX_DIR is the `raw' directory, valid only in the source-tree.
354 my $config_aux_dir = '';
355 my $config_aux_dir_set_in_configure_ac = 0;
356 # $AM_CONFIG_AUX_DIR is prefixed with $(top_srcdir), so it can be used
357 # in Makefiles.
358 my $am_config_aux_dir = '';
360 # Directory to search for AC_LIBSOURCE files, as set by AC_CONFIG_LIBOBJ_DIR
361 # in configure.ac.
362 my $config_libobj_dir = '';
364 # Whether AM_GNU_GETTEXT has been seen in configure.ac.
365 my $seen_gettext = 0;
366 # Whether AM_GNU_GETTEXT([external]) is used.
367 my $seen_gettext_external = 0;
368 # Where AM_GNU_GETTEXT appears.
369 my $ac_gettext_location;
370 # Whether AM_GNU_GETTEXT_INTL_SUBDIR has been seen.
371 my $seen_gettext_intl = 0;
373 # Lists of tags supported by Libtool.
374 my %libtool_tags = ();
375 # 1 if Libtool uses LT_SUPPORTED_TAG.  If it does, then it also
376 # uses AC_REQUIRE_AUX_FILE.
377 my $libtool_new_api = 0;
379 # Most important AC_CANONICAL_* macro seen so far.
380 my $seen_canonical = 0;
381 # Location of that macro.
382 my $canonical_location;
384 # Where AM_MAINTAINER_MODE appears.
385 my $seen_maint_mode;
387 # Actual version we've seen.
388 my $package_version = '';
390 # Where version is defined.
391 my $package_version_location;
393 # TRUE if we've seen AM_ENABLE_MULTILIB.
394 my $seen_multilib = 0;
396 # TRUE if we've seen AM_PROG_CC_C_O
397 my $seen_cc_c_o = 0;
399 # Location of AC_REQUIRE_AUX_FILE calls, indexed by their argument.
400 my %required_aux_file = ();
402 # Where AM_INIT_AUTOMAKE is called;
403 my $seen_init_automake = 0;
405 # TRUE if we've seen AM_AUTOMAKE_VERSION.
406 my $seen_automake_version = 0;
408 # Hash table of discovered configure substitutions.  Keys are names,
409 # values are `FILE:LINE' strings which are used by error message
410 # generation.
411 my %configure_vars = ();
413 # Ignored configure substitutions (i.e., variables not to be output in
414 # Makefile.in)
415 my %ignored_configure_vars = ();
417 # Files included by $configure_ac.
418 my @configure_deps = ();
420 # Greatest timestamp of configure's dependencies.
421 my $configure_deps_greatest_timestamp = 0;
423 # Hash table of AM_CONDITIONAL variables seen in configure.
424 my %configure_cond = ();
426 # This maps extensions onto language names.
427 my %extension_map = ();
429 # List of the DIST_COMMON files we discovered while reading
430 # configure.in
431 my $configure_dist_common = '';
433 # This maps languages names onto objects.
434 my %languages = ();
435 # Maps each linker variable onto a language object.
436 my %link_languages = ();
438 # maps extensions to needed source flags.
439 my %sourceflags = ();
441 # List of targets we must always output.
442 # FIXME: Complete, and remove falsely required targets.
443 my %required_targets =
444   (
445    'all'          => 1,
446    'dvi'          => 1,
447    'pdf'          => 1,
448    'ps'           => 1,
449    'info'         => 1,
450    'install-info' => 1,
451    'install'      => 1,
452    'install-data' => 1,
453    'install-exec' => 1,
454    'uninstall'    => 1,
456    # FIXME: Not required, temporary hacks.
457    # Well, actually they are sort of required: the -recursive
458    # targets will run them anyway...
459    'dvi-am'          => 1,
460    'pdf-am'          => 1,
461    'ps-am'           => 1,
462    'info-am'         => 1,
463    'install-data-am' => 1,
464    'install-exec-am' => 1,
465    'installcheck-am' => 1,
466    'uninstall-am' => 1,
468    'install-man' => 1,
469   );
471 # Set to 1 if this run will create the Makefile.in that distributes
472 # the files in config_aux_dir.
473 my $automake_will_process_aux_dir = 0;
475 # The name of the Makefile currently being processed.
476 my $am_file = 'BUG';
479 ################################################################
481 ## ------------------------------------------ ##
482 ## Variables reset by &initialize_per_input.  ##
483 ## ------------------------------------------ ##
485 # Basename and relative dir of the input file.
486 my $am_file_name;
487 my $am_relative_dir;
489 # Same but wrt Makefile.in.
490 my $in_file_name;
491 my $relative_dir;
493 # Relative path to the top directory.
494 my $topsrcdir;
496 # Greatest timestamp of the output's dependencies (excluding
497 # configure's dependencies).
498 my $output_deps_greatest_timestamp;
500 # These variables are used when generating each Makefile.in.
501 # They hold the Makefile.in until it is ready to be printed.
502 my $output_vars;
503 my $output_all;
504 my $output_header;
505 my $output_rules;
506 my $output_trailer;
508 # This is the conditional stack, updated on if/else/endif, and
509 # used to build Condition objects.
510 my @cond_stack;
512 # This holds the set of included files.
513 my @include_stack;
515 # List of dependencies for the obvious targets.
516 my @all;
517 my @check;
518 my @check_tests;
520 # Keys in this hash table are files to delete.  The associated
521 # value tells when this should happen (MOSTLY_CLEAN, DIST_CLEAN, etc.)
522 my %clean_files;
524 # Keys in this hash table are object files or other files in
525 # subdirectories which need to be removed.  This only holds files
526 # which are created by compilations.  The value in the hash indicates
527 # when the file should be removed.
528 my %compile_clean_files;
530 # Keys in this hash table are directories where we expect to build a
531 # libtool object.  We use this information to decide what directories
532 # to delete.
533 my %libtool_clean_directories;
535 # Value of `$(SOURCES)', used by tags.am.
536 my @sources;
537 # Sources which go in the distribution.
538 my @dist_sources;
540 # This hash maps object file names onto their corresponding source
541 # file names.  This is used to ensure that each object is created
542 # by a single source file.
543 my %object_map;
545 # This hash maps object file names onto an integer value representing
546 # whether this object has been built via ordinary compilation or
547 # libtool compilation (the COMPILE_* constants).
548 my %object_compilation_map;
551 # This keeps track of the directories for which we've already
552 # created dirstamp code.  Keys are directories, values are stamp files.
553 # Several keys can share the same stamp files if they are equivalent
554 # (as are `.//foo' and `foo').
555 my %directory_map;
557 # All .P files.
558 my %dep_files;
560 # This is a list of all targets to run during "make dist".
561 my @dist_targets;
563 # Keep track of all programs declared in this Makefile, without
564 # $(EXEEXT).  @substitutions@ are not listed.
565 my %known_programs;
567 # Keys in this hash are the basenames of files which must depend on
568 # ansi2knr.  Values are either the empty string, or the directory in
569 # which the ANSI source file appears; the directory must have a
570 # trailing `/'.
571 my %de_ansi_files;
573 # This keeps track of which extensions we've seen (that we care
574 # about).
575 my %extension_seen;
577 # This is random scratch space for the language finish functions.
578 # Don't randomly overwrite it; examine other uses of keys first.
579 my %language_scratch;
581 # We keep track of which objects need special (per-executable)
582 # handling on a per-language basis.
583 my %lang_specific_files;
585 # This is set when `handle_dist' has finished.  Once this happens,
586 # we should no longer push on dist_common.
587 my $handle_dist_run;
589 # Used to store a set of linkers needed to generate the sources currently
590 # under consideration.
591 my %linkers_used;
593 # True if we need `LINK' defined.  This is a hack.
594 my $need_link;
596 # Was get_object_extension run?
597 # FIXME: This is a hack. a better switch should be found.
598 my $get_object_extension_was_run;
600 # Record each file processed by make_paragraphs.
601 my %transformed_files;
604 ################################################################
606 ## ---------------------------------------------- ##
607 ## Variables not reset by &initialize_per_input.  ##
608 ## ---------------------------------------------- ##
610 # Cache each file processed by make_paragraphs.
611 # (This is different from %transformed_files because
612 # %transformed_files is reset for each file while %am_file_cache
613 # it global to the run.)
614 my %am_file_cache;
616 ################################################################
618 # var_SUFFIXES_trigger ($TYPE, $VALUE)
619 # ------------------------------------
620 # This is called by Automake::Variable::define() when SUFFIXES
621 # is defined ($TYPE eq '') or appended ($TYPE eq '+').
622 # The work here needs to be performed as a side-effect of the
623 # macro_define() call because SUFFIXES definitions impact
624 # on $KNOWN_EXTENSIONS_PATTERN which is used used when parsing
625 # the input am file.
626 sub var_SUFFIXES_trigger ($$)
628     my ($type, $value) = @_;
629     accept_extensions (split (' ', $value));
631 Automake::Variable::hook ('SUFFIXES', \&var_SUFFIXES_trigger);
633 ################################################################
635 ## --------------------------------- ##
636 ## Forward subroutine declarations.  ##
637 ## --------------------------------- ##
638 sub register_language (%);
639 sub file_contents_internal ($$$%);
640 sub define_files_variable ($\@$$);
643 # &initialize_per_input ()
644 # ------------------------
645 # (Re)-Initialize per-Makefile.am variables.
646 sub initialize_per_input ()
648     reset_local_duplicates ();
650     $am_file_name = undef;
651     $am_relative_dir = undef;
653     $in_file_name = undef;
654     $relative_dir = undef;
655     $topsrcdir = undef;
657     $output_deps_greatest_timestamp = 0;
659     $output_vars = '';
660     $output_all = '';
661     $output_header = '';
662     $output_rules = '';
663     $output_trailer = '';
665     Automake::Options::reset;
666     Automake::Variable::reset;
667     Automake::Rule::reset;
669     @cond_stack = ();
671     @include_stack = ();
673     @all = ();
674     @check = ();
675     @check_tests = ();
677     %clean_files = ();
678     %compile_clean_files = ();
680     # We always include `.'.  This isn't strictly correct.
681     %libtool_clean_directories = ('.' => 1);
683     @sources = ();
684     @dist_sources = ();
686     %object_map = ();
687     %object_compilation_map = ();
689     %directory_map = ();
691     %dep_files = ();
693     @dist_targets = ();
695     %known_programs = ();
697     %de_ansi_files = ();
699     %extension_seen = ();
701     %language_scratch = ();
703     %lang_specific_files = ();
705     $handle_dist_run = 0;
707     $need_link = 0;
709     $get_object_extension_was_run = 0;
711     %transformed_files = ();
715 ################################################################
717 # Initialize our list of languages that are internally supported.
719 # C.
720 register_language ('name' => 'c',
721                    'Name' => 'C',
722                    'config_vars' => ['CC'],
723                    'ansi' => 1,
724                    'autodep' => '',
725                    'flags' => ['CFLAGS', 'CPPFLAGS'],
726                    'compiler' => 'COMPILE',
727                    'compile' => '$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS)',
728                    'lder' => 'CCLD',
729                    'ld' => '$(CC)',
730                    'linker' => 'LINK',
731                    'link' => '$(CCLD) $(AM_CFLAGS) $(CFLAGS) $(AM_LDFLAGS) $(LDFLAGS) -o $@',
732                    'compile_flag' => '-c',
733                    'libtool_tag' => 'CC',
734                    'extensions' => ['.c'],
735                    '_finish' => \&lang_c_finish);
737 # C++.
738 register_language ('name' => 'cxx',
739                    'Name' => 'C++',
740                    'config_vars' => ['CXX'],
741                    'linker' => 'CXXLINK',
742                    'link' => '$(CXXLD) $(AM_CXXFLAGS) $(CXXFLAGS) $(AM_LDFLAGS) $(LDFLAGS) -o $@',
743                    'autodep' => 'CXX',
744                    'flags' => ['CXXFLAGS', 'CPPFLAGS'],
745                    'compile' => '$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS)',
746                    'compiler' => 'CXXCOMPILE',
747                    'compile_flag' => '-c',
748                    'output_flag' => '-o',
749                    'libtool_tag' => 'CXX',
750                    'lder' => 'CXXLD',
751                    'ld' => '$(CXX)',
752                    'pure' => 1,
753                    'extensions' => ['.c++', '.cc', '.cpp', '.cxx', '.C']);
755 # Objective C.
756 register_language ('name' => 'objc',
757                    'Name' => 'Objective C',
758                    'config_vars' => ['OBJC'],
759                    'linker' => 'OBJCLINK',
760                    'link' => '$(OBJCLD) $(AM_OBJCFLAGS) $(OBJCFLAGS) $(AM_LDFLAGS) $(LDFLAGS) -o $@',
761                    'autodep' => 'OBJC',
762                    'flags' => ['OBJCFLAGS', 'CPPFLAGS'],
763                    'compile' => '$(OBJC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_OBJCFLAGS) $(OBJCFLAGS)',
764                    'compiler' => 'OBJCCOMPILE',
765                    'compile_flag' => '-c',
766                    'output_flag' => '-o',
767                    'lder' => 'OBJCLD',
768                    'ld' => '$(OBJC)',
769                    'pure' => 1,
770                    'extensions' => ['.m']);
772 # Unified Parallel C.
773 register_language ('name' => 'upc',
774                    'Name' => 'Unified Parallel C',
775                    'config_vars' => ['UPC'],
776                    'linker' => 'UPCLINK',
777                    'link' => '$(UPCLD) $(AM_UPCFLAGS) $(UPCFLAGS) $(AM_LDFLAGS) $(LDFLAGS) -o $@',
778                    'autodep' => 'UPC',
779                    'flags' => ['UPCFLAGS', 'CPPFLAGS'],
780                    'compile' => '$(UPC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_UPCFLAGS) $(UPCFLAGS)',
781                    'compiler' => 'UPCCOMPILE',
782                    'compile_flag' => '-c',
783                    'output_flag' => '-o',
784                    'lder' => 'UPCLD',
785                    'ld' => '$(UPC)',
786                    'pure' => 1,
787                    'extensions' => ['.upc']);
789 # Headers.
790 register_language ('name' => 'header',
791                    'Name' => 'Header',
792                    'extensions' => ['.h', '.H', '.hxx', '.h++', '.hh',
793                                     '.hpp', '.inc'],
794                    # No output.
795                    'output_extensions' => sub { return () },
796                    # Nothing to do.
797                    '_finish' => sub { });
799 # Yacc (C & C++).
800 register_language ('name' => 'yacc',
801                    'Name' => 'Yacc',
802                    'config_vars' => ['YACC'],
803                    'flags' => ['YFLAGS'],
804                    'compile' => '$(YACC) $(YFLAGS) $(AM_YFLAGS)',
805                    'compiler' => 'YACCCOMPILE',
806                    'extensions' => ['.y'],
807                    'output_extensions' => sub { (my $ext = $_[0]) =~ tr/y/c/;
808                                                 return ($ext,) },
809                    'rule_file' => 'yacc',
810                    '_finish' => \&lang_yacc_finish,
811                    '_target_hook' => \&lang_yacc_target_hook,
812                    'nodist_specific' => 1);
813 register_language ('name' => 'yaccxx',
814                    'Name' => 'Yacc (C++)',
815                    'config_vars' => ['YACC'],
816                    'rule_file' => 'yacc',
817                    'flags' => ['YFLAGS'],
818                    'compiler' => 'YACCCOMPILE',
819                    'compile' => '$(YACC) $(YFLAGS) $(AM_YFLAGS)',
820                    'extensions' => ['.y++', '.yy', '.yxx', '.ypp'],
821                    'output_extensions' => sub { (my $ext = $_[0]) =~ tr/y/c/;
822                                                 return ($ext,) },
823                    '_finish' => \&lang_yacc_finish,
824                    '_target_hook' => \&lang_yacc_target_hook,
825                    'nodist_specific' => 1);
827 # Lex (C & C++).
828 register_language ('name' => 'lex',
829                    'Name' => 'Lex',
830                    'config_vars' => ['LEX'],
831                    'rule_file' => 'lex',
832                    'flags' => ['LFLAGS'],
833                    'compile' => '$(LEX) $(LFLAGS) $(AM_LFLAGS)',
834                    'compiler' => 'LEXCOMPILE',
835                    'extensions' => ['.l'],
836                    'output_extensions' => sub { (my $ext = $_[0]) =~ tr/l/c/;
837                                                 return ($ext,) },
838                    '_finish' => \&lang_lex_finish,
839                    '_target_hook' => \&lang_lex_target_hook,
840                    'nodist_specific' => 1);
841 register_language ('name' => 'lexxx',
842                    'Name' => 'Lex (C++)',
843                    'config_vars' => ['LEX'],
844                    'rule_file' => 'lex',
845                    'flags' => ['LFLAGS'],
846                    'compile' => '$(LEX) $(LFLAGS) $(AM_LFLAGS)',
847                    'compiler' => 'LEXCOMPILE',
848                    'extensions' => ['.l++', '.ll', '.lxx', '.lpp'],
849                    'output_extensions' => sub { (my $ext = $_[0]) =~ tr/l/c/;
850                                                 return ($ext,) },
851                    '_finish' => \&lang_lex_finish,
852                    '_target_hook' => \&lang_lex_target_hook,
853                    'nodist_specific' => 1);
855 # Assembler.
856 register_language ('name' => 'asm',
857                    'Name' => 'Assembler',
858                    'config_vars' => ['CCAS', 'CCASFLAGS'],
860                    'flags' => ['CCASFLAGS'],
861                    # Users can set AM_CCASFLAGS to include DEFS, INCLUDES,
862                    # or anything else required.  They can also set CCAS.
863                    # Or simply use Preprocessed Assembler.
864                    'compile' => '$(CCAS) $(AM_CCASFLAGS) $(CCASFLAGS)',
865                    'compiler' => 'CCASCOMPILE',
866                    'compile_flag' => '-c',
867                    'output_flag' => '-o',
868                    'extensions' => ['.s'],
870                    # With assembly we still use the C linker.
871                    '_finish' => \&lang_c_finish);
873 # Preprocessed Assembler.
874 register_language ('name' => 'cppasm',
875                    'Name' => 'Preprocessed Assembler',
876                    'config_vars' => ['CCAS', 'CCASFLAGS'],
878                    'autodep' => 'CCAS',
879                    'flags' => ['CCASFLAGS', 'CPPFLAGS'],
880                    'compile' => '$(CCAS) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CCASFLAGS) $(CCASFLAGS)',
881                    'compiler' => 'CPPASCOMPILE',
882                    'compile_flag' => '-c',
883                    'output_flag' => '-o',
884                    'extensions' => ['.S', '.sx'],
886                    # With assembly we still use the C linker.
887                    '_finish' => \&lang_c_finish);
889 # Fortran 77
890 register_language ('name' => 'f77',
891                    'Name' => 'Fortran 77',
892                    'config_vars' => ['F77'],
893                    'linker' => 'F77LINK',
894                    'link' => '$(F77LD) $(AM_FFLAGS) $(FFLAGS) $(AM_LDFLAGS) $(LDFLAGS) -o $@',
895                    'flags' => ['FFLAGS'],
896                    'compile' => '$(F77) $(AM_FFLAGS) $(FFLAGS)',
897                    'compiler' => 'F77COMPILE',
898                    'compile_flag' => '-c',
899                    'output_flag' => '-o',
900                    'libtool_tag' => 'F77',
901                    'lder' => 'F77LD',
902                    'ld' => '$(F77)',
903                    'pure' => 1,
904                    'extensions' => ['.f', '.for']);
906 # Fortran
907 register_language ('name' => 'fc',
908                    'Name' => 'Fortran',
909                    'config_vars' => ['FC'],
910                    'linker' => 'FCLINK',
911                    'link' => '$(FCLD) $(AM_FCFLAGS) $(FCFLAGS) $(AM_LDFLAGS) $(LDFLAGS) -o $@',
912                    'flags' => ['FCFLAGS'],
913                    'compile' => '$(FC) $(AM_FCFLAGS) $(FCFLAGS)',
914                    'compiler' => 'FCCOMPILE',
915                    'compile_flag' => '-c',
916                    'output_flag' => '-o',
917                    'lder' => 'FCLD',
918                    'ld' => '$(FC)',
919                    'pure' => 1,
920                    'extensions' => ['.f90', '.f95', '.f03', '.f08']);
922 # Preprocessed Fortran
923 register_language ('name' => 'ppfc',
924                    'Name' => 'Preprocessed Fortran',
925                    'config_vars' => ['FC'],
926                    'linker' => 'FCLINK',
927                    'link' => '$(FCLD) $(AM_FCFLAGS) $(FCFLAGS) $(AM_LDFLAGS) $(LDFLAGS) -o $@',
928                    'lder' => 'FCLD',
929                    'ld' => '$(FC)',
930                    'flags' => ['FCFLAGS', 'CPPFLAGS'],
931                    'compiler' => 'PPFCCOMPILE',
932                    'compile' => '$(FC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_FCFLAGS) $(FCFLAGS)',
933                    'compile_flag' => '-c',
934                    'output_flag' => '-o',
935                    'libtool_tag' => 'FC',
936                    'pure' => 1,
937                    'extensions' => ['.F90','.F95', '.F03', '.F08']);
939 # Preprocessed Fortran 77
941 # The current support for preprocessing Fortran 77 just involves
942 # passing `$(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS)
943 # $(CPPFLAGS)' as additional flags to the Fortran 77 compiler, since
944 # this is how GNU Make does it; see the `GNU Make Manual, Edition 0.51
945 # for `make' Version 3.76 Beta' (specifically, from info file
946 # `(make)Catalogue of Rules').
948 # A better approach would be to write an Autoconf test
949 # (i.e. AC_PROG_FPP) for a Fortran 77 preprocessor, because not all
950 # Fortran 77 compilers know how to do preprocessing.  The Autoconf
951 # macro AC_PROG_FPP should test the Fortran 77 compiler first for
952 # preprocessing capabilities, and then fall back on cpp (if cpp were
953 # available).
954 register_language ('name' => 'ppf77',
955                    'Name' => 'Preprocessed Fortran 77',
956                    'config_vars' => ['F77'],
957                    'linker' => 'F77LINK',
958                    'link' => '$(F77LD) $(AM_FFLAGS) $(FFLAGS) $(AM_LDFLAGS) $(LDFLAGS) -o $@',
959                    'lder' => 'F77LD',
960                    'ld' => '$(F77)',
961                    'flags' => ['FFLAGS', 'CPPFLAGS'],
962                    'compiler' => 'PPF77COMPILE',
963                    'compile' => '$(F77) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_FFLAGS) $(FFLAGS)',
964                    'compile_flag' => '-c',
965                    'output_flag' => '-o',
966                    'libtool_tag' => 'F77',
967                    'pure' => 1,
968                    'extensions' => ['.F']);
970 # Ratfor.
971 register_language ('name' => 'ratfor',
972                    'Name' => 'Ratfor',
973                    'config_vars' => ['F77'],
974                    'linker' => 'F77LINK',
975                    'link' => '$(F77LD) $(AM_FFLAGS) $(FFLAGS) $(AM_LDFLAGS) $(LDFLAGS) -o $@',
976                    'lder' => 'F77LD',
977                    'ld' => '$(F77)',
978                    'flags' => ['RFLAGS', 'FFLAGS'],
979                    # FIXME also FFLAGS.
980                    'compile' => '$(F77) $(AM_FFLAGS) $(FFLAGS) $(AM_RFLAGS) $(RFLAGS)',
981                    'compiler' => 'RCOMPILE',
982                    'compile_flag' => '-c',
983                    'output_flag' => '-o',
984                    'libtool_tag' => 'F77',
985                    'pure' => 1,
986                    'extensions' => ['.r']);
988 # Java via gcj.
989 register_language ('name' => 'java',
990                    'Name' => 'Java',
991                    'config_vars' => ['GCJ'],
992                    'linker' => 'GCJLINK',
993                    'link' => '$(GCJLD) $(AM_GCJFLAGS) $(GCJFLAGS) $(AM_LDFLAGS) $(LDFLAGS) -o $@',
994                    'autodep' => 'GCJ',
995                    'flags' => ['GCJFLAGS'],
996                    'compile' => '$(GCJ) $(AM_GCJFLAGS) $(GCJFLAGS)',
997                    'compiler' => 'GCJCOMPILE',
998                    'compile_flag' => '-c',
999                    'output_flag' => '-o',
1000                    'libtool_tag' => 'GCJ',
1001                    'lder' => 'GCJLD',
1002                    'ld' => '$(GCJ)',
1003                    'pure' => 1,
1004                    'extensions' => ['.java', '.class', '.zip', '.jar']);
1006 ################################################################
1008 # Error reporting functions.
1010 # err_am ($MESSAGE, [%OPTIONS])
1011 # -----------------------------
1012 # Uncategorized errors about the current Makefile.am.
1013 sub err_am ($;%)
1015   msg_am ('error', @_);
1018 # err_ac ($MESSAGE, [%OPTIONS])
1019 # -----------------------------
1020 # Uncategorized errors about configure.ac.
1021 sub err_ac ($;%)
1023   msg_ac ('error', @_);
1026 # msg_am ($CHANNEL, $MESSAGE, [%OPTIONS])
1027 # ---------------------------------------
1028 # Messages about about the current Makefile.am.
1029 sub msg_am ($$;%)
1031   my ($channel, $msg, %opts) = @_;
1032   msg $channel, "${am_file}.am", $msg, %opts;
1035 # msg_ac ($CHANNEL, $MESSAGE, [%OPTIONS])
1036 # ---------------------------------------
1037 # Messages about about configure.ac.
1038 sub msg_ac ($$;%)
1040   my ($channel, $msg, %opts) = @_;
1041   msg $channel, $configure_ac, $msg, %opts;
1044 ################################################################
1046 # subst ($TEXT)
1047 # -------------
1048 # Return a configure-style substitution using the indicated text.
1049 # We do this to avoid having the substitutions directly in automake.in;
1050 # when we do that they are sometimes removed and this causes confusion
1051 # and bugs.
1052 sub subst ($)
1054     my ($text) = @_;
1055     return '@' . $text . '@';
1058 ################################################################
1061 # $BACKPATH
1062 # &backname ($REL-DIR)
1063 # --------------------
1064 # If I `cd $REL-DIR', then to come back, I should `cd $BACKPATH'.
1065 # For instance `src/foo' => `../..'.
1066 # Works with non strictly increasing paths, i.e., `src/../lib' => `..'.
1067 sub backname ($)
1069     my ($file) = @_;
1070     my @res;
1071     foreach (split (/\//, $file))
1072     {
1073         next if $_ eq '.' || $_ eq '';
1074         if ($_ eq '..')
1075         {
1076             pop @res
1077               or prog_error ("trying to reverse path `$file' pointing outside tree");
1078         }
1079         else
1080         {
1081             push (@res, '..');
1082         }
1083     }
1084     return join ('/', @res) || '.';
1087 ################################################################
1090 # Handle AUTOMAKE_OPTIONS variable.  Return 1 on error, 0 otherwise.
1091 sub handle_options
1093   my $var = var ('AUTOMAKE_OPTIONS');
1094   if ($var)
1095     {
1096       if ($var->has_conditional_contents)
1097         {
1098           msg_var ('unsupported', $var,
1099                    "`AUTOMAKE_OPTIONS' cannot have conditional contents");
1100         }
1101       foreach my $locvals ($var->value_as_list_recursive (cond_filter => TRUE,
1102                                                           location => 1))
1103         {
1104           my ($loc, $value) = @$locvals;
1105           return 1 if (process_option_list ($loc, $value))
1106         }
1107     }
1109   if ($strictness == GNITS)
1110     {
1111       set_option ('readme-alpha', INTERNAL);
1112       set_option ('std-options', INTERNAL);
1113       set_option ('check-news', INTERNAL);
1114     }
1116   return 0;
1119 # shadow_unconditionally ($varname, $where)
1120 # -----------------------------------------
1121 # Return a $(variable) that contains all possible values
1122 # $varname can take.
1123 # If the VAR wasn't defined conditionally, return $(VAR).
1124 # Otherwise we create a am__VAR_DIST variable which contains
1125 # all possible values, and return $(am__VAR_DIST).
1126 sub shadow_unconditionally ($$)
1128   my ($varname, $where) = @_;
1129   my $var = var $varname;
1130   if ($var->has_conditional_contents)
1131     {
1132       $varname = "am__${varname}_DIST";
1133       my @files = uniq ($var->value_as_list_recursive);
1134       define_pretty_variable ($varname, TRUE, $where, @files);
1135     }
1136   return "\$($varname)"
1139 # get_object_extension ($EXTENSION)
1140 # ---------------------------------
1141 # Prefix $EXTENSION with $U if ansi2knr is in use.
1142 sub get_object_extension ($)
1144     my ($extension) = @_;
1146     # Check for automatic de-ANSI-fication.
1147     $extension = '$U' . $extension
1148       if option 'ansi2knr';
1150     $get_object_extension_was_run = 1;
1152     return $extension;
1155 # check_user_variables (@LIST)
1156 # ----------------------------
1157 # Make sure each variable VAR in @LIST does not exist, suggest using AM_VAR
1158 # otherwise.
1159 sub check_user_variables (@)
1161   my @dont_override = @_;
1162   foreach my $flag (@dont_override)
1163     {
1164       my $var = var $flag;
1165       if ($var)
1166         {
1167           for my $cond ($var->conditions->conds)
1168             {
1169               if ($var->rdef ($cond)->owner == VAR_MAKEFILE)
1170                 {
1171                   msg_cond_var ('gnu', $cond, $flag,
1172                                 "`$flag' is a user variable, "
1173                                 . "you should not override it;\n"
1174                                 . "use `AM_$flag' instead.");
1175                 }
1176             }
1177         }
1178     }
1181 # Call finish function for each language that was used.
1182 sub handle_languages
1184     if (! option 'no-dependencies')
1185     {
1186         # Include auto-dep code.  Don't include it if DEP_FILES would
1187         # be empty.
1188         if (&saw_sources_p (0) && keys %dep_files)
1189         {
1190             # Set location of depcomp.
1191             &define_variable ('depcomp',
1192                               "\$(SHELL) $am_config_aux_dir/depcomp",
1193                               INTERNAL);
1194             &define_variable ('am__depfiles_maybe', 'depfiles', INTERNAL);
1196             require_conf_file ("$am_file.am", FOREIGN, 'depcomp');
1198             my @deplist = sort keys %dep_files;
1199             # Generate each `include' individually.  Irix 6 make will
1200             # not properly include several files resulting from a
1201             # variable expansion; generating many separate includes
1202             # seems safest.
1203             $output_rules .= "\n";
1204             foreach my $iter (@deplist)
1205             {
1206                 $output_rules .= (subst ('AMDEP_TRUE')
1207                                   . subst ('am__include')
1208                                   . ' '
1209                                   . subst ('am__quote')
1210                                   . $iter
1211                                   . subst ('am__quote')
1212                                   . "\n");
1213             }
1215             # Compute the set of directories to remove in distclean-depend.
1216             my @depdirs = uniq (map { dirname ($_) } @deplist);
1217             $output_rules .= &file_contents ('depend',
1218                                              new Automake::Location,
1219                                              DEPDIRS => "@depdirs");
1220         }
1221     }
1222     else
1223     {
1224         &define_variable ('depcomp', '', INTERNAL);
1225         &define_variable ('am__depfiles_maybe', '', INTERNAL);
1226     }
1228     my %done;
1230     # Is the c linker needed?
1231     my $needs_c = 0;
1232     foreach my $ext (sort keys %extension_seen)
1233     {
1234         next unless $extension_map{$ext};
1236         my $lang = $languages{$extension_map{$ext}};
1238         my $rule_file = $lang->rule_file || 'depend2';
1240         # Get information on $LANG.
1241         my $pfx = $lang->autodep;
1242         my $fpfx = ($pfx eq '') ? 'CC' : $pfx;
1244         my ($AMDEP, $FASTDEP) =
1245           (option 'no-dependencies' || $lang->autodep eq 'no')
1246           ? ('FALSE', 'FALSE') : ('AMDEP', "am__fastdep$fpfx");
1248         my %transform = ('EXT'     => $ext,
1249                          'PFX'     => $pfx,
1250                          'FPFX'    => $fpfx,
1251                          'AMDEP'   => $AMDEP,
1252                          'FASTDEP' => $FASTDEP,
1253                          '-c'      => $lang->compile_flag || '',
1254                          # These are not used, but they need to be defined
1255                          # so &transform do not complain.
1256                          SUBDIROBJ     => 0,
1257                          'DERIVED-EXT' => 'BUG',
1258                          DIST_SOURCE   => 1,
1259                         );
1261         # Generate the appropriate rules for this extension.
1262         if (((! option 'no-dependencies') && $lang->autodep ne 'no')
1263             || defined $lang->compile)
1264         {
1265             # Some C compilers don't support -c -o.  Use it only if really
1266             # needed.
1267             my $output_flag = $lang->output_flag || '';
1268             $output_flag = '-o'
1269               if (! $output_flag
1270                   && $lang->name eq 'c'
1271                   && option 'subdir-objects');
1273             # Compute a possible derived extension.
1274             # This is not used by depend2.am.
1275             my $der_ext = (&{$lang->output_extensions} ($ext))[0];
1277             # When we output an inference rule like `.c.o:' we
1278             # have two cases to consider: either subdir-objects
1279             # is used, or it is not.
1280             #
1281             # In the latter case the rule is used to build objects
1282             # in the current directory, and dependencies always
1283             # go into `./$(DEPDIR)/'.  We can hard-code this value.
1284             #
1285             # In the former case the rule can be used to build
1286             # objects in sub-directories too.  Dependencies should
1287             # go into the appropriate sub-directories, e.g.,
1288             # `sub/$(DEPDIR)/'.  The value of this directory
1289             # needs to be computed on-the-fly.
1290             #
1291             # DEPBASE holds the name of this directory, plus the
1292             # basename part of the object file (extensions Po, TPo,
1293             # Plo, TPlo will be added later as appropriate).  It is
1294             # either hardcoded, or a shell variable (`$depbase') that
1295             # will be computed by the rule.
1296             my $depbase =
1297               option ('subdir-objects') ? '$$depbase' : '$(DEPDIR)/$*';
1298             $output_rules .=
1299               file_contents ($rule_file,
1300                              new Automake::Location,
1301                              %transform,
1302                              GENERIC   => 1,
1304                              'DERIVED-EXT' => $der_ext,
1306                              DEPBASE   => $depbase,
1307                              BASE      => '$*',
1308                              SOURCE    => '$<',
1309                              SOURCEFLAG => $sourceflags{$ext} || '',
1310                              OBJ       => '$@',
1311                              OBJOBJ    => '$@',
1312                              LTOBJ     => '$@',
1314                              COMPILE   => '$(' . $lang->compiler . ')',
1315                              LTCOMPILE => '$(LT' . $lang->compiler . ')',
1316                              -o        => $output_flag,
1317                              SUBDIROBJ => !! option 'subdir-objects');
1318         }
1320         # Now include code for each specially handled object with this
1321         # language.
1322         my %seen_files = ();
1323         foreach my $file (@{$lang_specific_files{$lang->name}})
1324         {
1325             my ($derived, $source, $obj, $myext, $srcext, %file_transform) = @$file;
1327             # We might see a given object twice, for instance if it is
1328             # used under different conditions.
1329             next if defined $seen_files{$obj};
1330             $seen_files{$obj} = 1;
1332             prog_error ("found " . $lang->name .
1333                         " in handle_languages, but compiler not defined")
1334               unless defined $lang->compile;
1336             my $obj_compile = $lang->compile;
1338             # Rewrite each occurrence of `AM_$flag' in the compile
1339             # rule into `${derived}_$flag' if it exists.
1340             for my $flag (@{$lang->flags})
1341               {
1342                 my $val = "${derived}_$flag";
1343                 $obj_compile =~ s/\(AM_$flag\)/\($val\)/
1344                   if set_seen ($val);
1345               }
1347             my $libtool_tag = '';
1348             if ($lang->libtool_tag && exists $libtool_tags{$lang->libtool_tag})
1349               {
1350                 $libtool_tag = '--tag=' . $lang->libtool_tag . ' '
1351               }
1353             my $ptltflags = "${derived}_LIBTOOLFLAGS";
1354             $ptltflags = 'AM_LIBTOOLFLAGS' unless set_seen $ptltflags;
1356             my $obj_ltcompile =
1357               "\$(LIBTOOL) $libtool_tag\$($ptltflags) \$(LIBTOOLFLAGS) "
1358               . "--mode=compile $obj_compile";
1360             # We _need_ `-o' for per object rules.
1361             my $output_flag = $lang->output_flag || '-o';
1363             my $depbase = dirname ($obj);
1364             $depbase = ''
1365                 if $depbase eq '.';
1366             $depbase .= '/'
1367                 unless $depbase eq '';
1368             $depbase .= '$(DEPDIR)/' . basename ($obj);
1370             # Support for deansified files in subdirectories is ugly
1371             # enough to deserve an explanation.
1372             #
1373             # A Note about normal ansi2knr processing first.  On
1374             #
1375             #   AUTOMAKE_OPTIONS = ansi2knr
1376             #   bin_PROGRAMS = foo
1377             #   foo_SOURCES = foo.c
1378             #
1379             # we generate rules similar to:
1380             #
1381             #   foo: foo$U.o; link ...
1382             #   foo$U.o: foo$U.c; compile ...
1383             #   foo_.c: foo.c; ansi2knr ...
1384             #
1385             # this is fairly compact, and will call ansi2knr depending
1386             # on the value of $U (`' or `_').
1387             #
1388             # It's harder with subdir sources. On
1389             #
1390             #   AUTOMAKE_OPTIONS = ansi2knr
1391             #   bin_PROGRAMS = foo
1392             #   foo_SOURCES = sub/foo.c
1393             #
1394             # we have to create foo_.c in the current directory.
1395             # (Unless the user asks 'subdir-objects'.)  This is important
1396             # in case the same file (`foo.c') is compiled from other
1397             # directories with different cpp options: foo_.c would
1398             # be preprocessed for only one set of options if it were
1399             # put in the subdirectory.
1400             #
1401             # Because foo$U.o must be built from either foo_.c or
1402             # sub/foo.c we can't be as concise as in the first example.
1403             # Instead we output
1404             #
1405             #   foo: foo$U.o; link ...
1406             #   foo_.o: foo_.c; compile ...
1407             #   foo.o: sub/foo.c; compile ...
1408             #   foo_.c: foo.c; ansi2knr ...
1409             #
1410             # This is why we'll now transform $rule_file twice
1411             # if we detect this case.
1412             # A first time we output the compile rule with `$U'
1413             # replaced by `_' and the source directory removed,
1414             # and another time we simply remove `$U'.
1415             #
1416             # Note that at this point $source (as computed by
1417             # &handle_single_transform) is `sub/foo$U.c'.
1418             # This can be confusing: it can be used as-is when
1419             # subdir-objects is set, otherwise you have to know
1420             # it really means `foo_.c' or `sub/foo.c'.
1421             my $objdir = dirname ($obj);
1422             my $srcdir = dirname ($source);
1423             if ($lang->ansi && $obj =~ /\$U/)
1424               {
1425                 prog_error "`$obj' contains \$U, but `$source' doesn't."
1426                   if $source !~ /\$U/;
1428                 (my $source_ = $source) =~ s/\$U/_/g;
1429                 # Output an additional rule if _.c and .c are not in
1430                 # the same directory.  (_.c is always in $objdir.)
1431                 if ($objdir ne $srcdir)
1432                   {
1433                     (my $obj_ = $obj) =~ s/\$U/_/g;
1434                     (my $depbase_ = $depbase) =~ s/\$U/_/g;
1435                     $source_ = basename ($source_);
1437                     $output_rules .=
1438                       file_contents ($rule_file,
1439                                      new Automake::Location,
1440                                      %transform,
1441                                      GENERIC   => 0,
1443                                      DEPBASE   => $depbase_,
1444                                      BASE      => $obj_,
1445                                      SOURCE    => $source_,
1446                                      SOURCEFLAG => $sourceflags{$srcext} || '',
1447                                      OBJ       => "$obj_$myext",
1448                                      OBJOBJ    => "$obj_.obj",
1449                                      LTOBJ     => "$obj_.lo",
1451                                      COMPILE   => $obj_compile,
1452                                      LTCOMPILE => $obj_ltcompile,
1453                                      -o        => $output_flag,
1454                                      %file_transform);
1455                     $obj =~ s/\$U//g;
1456                     $depbase =~ s/\$U//g;
1457                     $source =~ s/\$U//g;
1458                   }
1459               }
1461             $output_rules .=
1462               file_contents ($rule_file,
1463                              new Automake::Location,
1464                              %transform,
1465                              GENERIC   => 0,
1467                              DEPBASE   => $depbase,
1468                              BASE      => $obj,
1469                              SOURCE    => $source,
1470                              SOURCEFLAG => $sourceflags{$srcext} || '',
1471                              # Use $myext and not `.o' here, in case
1472                              # we are actually building a new source
1473                              # file -- e.g. via yacc.
1474                              OBJ       => "$obj$myext",
1475                              OBJOBJ    => "$obj.obj",
1476                              LTOBJ     => "$obj.lo",
1478                              COMPILE   => $obj_compile,
1479                              LTCOMPILE => $obj_ltcompile,
1480                              -o        => $output_flag,
1481                              %file_transform);
1482         }
1484         # The rest of the loop is done once per language.
1485         next if defined $done{$lang};
1486         $done{$lang} = 1;
1488         # Load the language dependent Makefile chunks.
1489         my %lang = map { uc ($_) => 0 } keys %languages;
1490         $lang{uc ($lang->name)} = 1;
1491         $output_rules .= file_contents ('lang-compile',
1492                                         new Automake::Location,
1493                                         %transform, %lang);
1495         # If the source to a program consists entirely of code from a
1496         # `pure' language, for instance C++ or Fortran 77, then we
1497         # don't need the C compiler code.  However if we run into
1498         # something unusual then we do generate the C code.  There are
1499         # probably corner cases here that do not work properly.
1500         # People linking Java code to Fortran code deserve pain.
1501         $needs_c ||= ! $lang->pure;
1503         define_compiler_variable ($lang)
1504           if ($lang->compile);
1506         define_linker_variable ($lang)
1507           if ($lang->link);
1509         require_variables ("$am_file.am", $lang->Name . " source seen",
1510                            TRUE, @{$lang->config_vars});
1512         # Call the finisher.
1513         $lang->finish;
1515         # Flags listed in `->flags' are user variables (per GNU Standards),
1516         # they should not be overridden in the Makefile...
1517         my @dont_override = @{$lang->flags};
1518         # ... and so is LDFLAGS.
1519         push @dont_override, 'LDFLAGS' if $lang->link;
1521         check_user_variables @dont_override;
1522     }
1524     # If the project is entirely C++ or entirely Fortran 77 (i.e., 1
1525     # suffix rule was learned), don't bother with the C stuff.  But if
1526     # anything else creeps in, then use it.
1527     $needs_c = 1
1528       if $need_link || suffix_rules_count > 1;
1530     if ($needs_c)
1531       {
1532         &define_compiler_variable ($languages{'c'})
1533           unless defined $done{$languages{'c'}};
1534         define_linker_variable ($languages{'c'});
1535       }
1539 # append_exeext { PREDICATE } $MACRO
1540 # ----------------------------------
1541 # Append $(EXEEXT) to each filename in $F appearing in the Makefile
1542 # variable $MACRO if &PREDICATE($F) is true.  @substitutions@ are
1543 # ignored.
1545 # This is typically used on all filenames of *_PROGRAMS, and filenames
1546 # of TESTS that are programs.
1547 sub append_exeext (&$)
1549   my ($pred, $macro) = @_;
1551   transform_variable_recursively
1552     ($macro, $macro, 'am__EXEEXT', 0, INTERNAL,
1553      sub {
1554        my ($subvar, $val, $cond, $full_cond) = @_;
1555        # Append $(EXEEXT) unless the user did it already, or it's a
1556        # @substitution@.
1557        $val .= '$(EXEEXT)'
1558          if $val !~ /(?:\$\(EXEEXT\)$|^[@]\w+[@]$)/ && &$pred ($val);
1559        return $val;
1560      });
1564 # Check to make sure a source defined in LIBOBJS is not explicitly
1565 # mentioned.  This is a separate function (as opposed to being inlined
1566 # in handle_source_transform) because it isn't always appropriate to
1567 # do this check.
1568 sub check_libobjs_sources
1570   my ($one_file, $unxformed) = @_;
1572   foreach my $prefix ('', 'EXTRA_', 'dist_', 'nodist_',
1573                       'dist_EXTRA_', 'nodist_EXTRA_')
1574     {
1575       my @files;
1576       my $varname = $prefix . $one_file . '_SOURCES';
1577       my $var = var ($varname);
1578       if ($var)
1579         {
1580           @files = $var->value_as_list_recursive;
1581         }
1582       elsif ($prefix eq '')
1583         {
1584           @files = ($unxformed . '.c');
1585         }
1586       else
1587         {
1588           next;
1589         }
1591       foreach my $file (@files)
1592         {
1593           err_var ($prefix . $one_file . '_SOURCES',
1594                    "automatically discovered file `$file' should not" .
1595                    " be explicitly mentioned")
1596             if defined $libsources{$file};
1597         }
1598     }
1602 # @OBJECTS
1603 # handle_single_transform ($VAR, $TOPPARENT, $DERIVED, $OBJ, $FILE, %TRANSFORM)
1604 # -----------------------------------------------------------------------------
1605 # Does much of the actual work for handle_source_transform.
1606 # Arguments are:
1607 #   $VAR is the name of the variable that the source filenames come from
1608 #   $TOPPARENT is the name of the _SOURCES variable which is being processed
1609 #   $DERIVED is the name of resulting executable or library
1610 #   $OBJ is the object extension (e.g., `$U.lo')
1611 #   $FILE the source file to transform
1612 #   %TRANSFORM contains extras arguments to pass to file_contents
1613 #     when producing explicit rules
1614 # Result is a list of the names of objects
1615 # %linkers_used will be updated with any linkers needed
1616 sub handle_single_transform ($$$$$%)
1618     my ($var, $topparent, $derived, $obj, $_file, %transform) = @_;
1619     my @files = ($_file);
1620     my @result = ();
1621     my $nonansi_obj = $obj;
1622     $nonansi_obj =~ s/\$U//g;
1624     # Turn sources into objects.  We use a while loop like this
1625     # because we might add to @files in the loop.
1626     while (scalar @files > 0)
1627     {
1628         $_ = shift @files;
1630         # Configure substitutions in _SOURCES variables are errors.
1631         if (/^\@.*\@$/)
1632         {
1633           my $parent_msg = '';
1634           $parent_msg = "\nand is referred to from `$topparent'"
1635             if $topparent ne $var->name;
1636           err_var ($var,
1637                    "`" . $var->name . "' includes configure substitution `$_'"
1638                    . $parent_msg . ";\nconfigure " .
1639                    "substitutions are not allowed in _SOURCES variables");
1640           next;
1641         }
1643         # If the source file is in a subdirectory then the `.o' is put
1644         # into the current directory, unless the subdir-objects option
1645         # is in effect.
1647         # Split file name into base and extension.
1648         next if ! /^(?:(.*)\/)?([^\/]*)($KNOWN_EXTENSIONS_PATTERN)$/;
1649         my $full = $_;
1650         my $directory = $1 || '';
1651         my $base = $2;
1652         my $extension = $3;
1654         # We must generate a rule for the object if it requires its own flags.
1655         my $renamed = 0;
1656         my ($linker, $object);
1658         # This records whether we've seen a derived source file (e.g.
1659         # yacc output).
1660         my $derived_source = 0;
1662         # This holds the `aggregate context' of the file we are
1663         # currently examining.  If the file is compiled with
1664         # per-object flags, then it will be the name of the object.
1665         # Otherwise it will be `AM'.  This is used by the target hook
1666         # language function.
1667         my $aggregate = 'AM';
1669         $extension = &derive_suffix ($extension, $nonansi_obj);
1670         my $lang;
1671         if ($extension_map{$extension} &&
1672             ($lang = $languages{$extension_map{$extension}}))
1673         {
1674             # Found the language, so see what it says.
1675             &saw_extension ($extension);
1677             # Do we have per-executable flags for this executable?
1678             my $have_per_exec_flags = 0;
1679             my @peflags = @{$lang->flags};
1680             push @peflags, 'LIBTOOLFLAGS' if $nonansi_obj eq '.lo';
1681             foreach my $flag (@peflags)
1682               {
1683                 if (set_seen ("${derived}_$flag"))
1684                   {
1685                     $have_per_exec_flags = 1;
1686                     last;
1687                   }
1688               }
1690             # Note: computed subr call.  The language rewrite function
1691             # should return one of the LANG_* constants.  It could
1692             # also return a list whose first value is such a constant
1693             # and whose second value is a new source extension which
1694             # should be applied.  This means this particular language
1695             # generates another source file which we must then process
1696             # further.
1697             my $subr = \&{'lang_' . $lang->name . '_rewrite'};
1698             my ($r, $source_extension)
1699                 = &$subr ($directory, $base, $extension,
1700                           $nonansi_obj, $have_per_exec_flags, $var);
1701             # Skip this entry if we were asked not to process it.
1702             next if $r == LANG_IGNORE;
1704             # Now extract linker and other info.
1705             $linker = $lang->linker;
1707             my $this_obj_ext;
1708             if (defined $source_extension)
1709             {
1710                 $this_obj_ext = $source_extension;
1711                 $derived_source = 1;
1712             }
1713             elsif ($lang->ansi)
1714             {
1715                 $this_obj_ext = $obj;
1716             }
1717             else
1718             {
1719                 $this_obj_ext = $nonansi_obj;
1720             }
1721             $object = $base . $this_obj_ext;
1723             if ($have_per_exec_flags)
1724             {
1725                 # We have a per-executable flag in effect for this
1726                 # object.  In this case we rewrite the object's
1727                 # name to ensure it is unique.
1729                 # We choose the name `DERIVED_OBJECT' to ensure
1730                 # (1) uniqueness, and (2) continuity between
1731                 # invocations.  However, this will result in a
1732                 # name that is too long for losing systems, in
1733                 # some situations.  So we provide _SHORTNAME to
1734                 # override.
1736                 my $dname = $derived;
1737                 my $var = var ($derived . '_SHORTNAME');
1738                 if ($var)
1739                 {
1740                     # FIXME: should use the same Condition as
1741                     # the _SOURCES variable.  But this is really
1742                     # silly overkill -- nobody should have
1743                     # conditional shortnames.
1744                     $dname = $var->variable_value;
1745                 }
1746                 $object = $dname . '-' . $object;
1748                 prog_error ($lang->name . " flags defined without compiler")
1749                   if ! defined $lang->compile;
1751                 $renamed = 1;
1752             }
1754             # If rewrite said it was ok, put the object into a
1755             # subdir.
1756             if ($r == LANG_SUBDIR && $directory ne '')
1757             {
1758                 $object = $directory . '/' . $object;
1759             }
1761             # If the object file has been renamed (because per-target
1762             # flags are used) we cannot compile the file with an
1763             # inference rule: we need an explicit rule.
1764             #
1765             # If the source is in a subdirectory and the object is in
1766             # the current directory, we also need an explicit rule.
1767             #
1768             # If both source and object files are in a subdirectory
1769             # (this happens when the subdir-objects option is used),
1770             # then the inference will work.
1771             #
1772             # The latter case deserves a historical note.  When the
1773             # subdir-objects option was added on 1999-04-11 it was
1774             # thought that inferences rules would work for
1775             # subdirectory objects too.  Later, on 1999-11-22,
1776             # automake was changed to output explicit rules even for
1777             # subdir-objects.  Nobody remembers why, but this occurred
1778             # soon after the merge of the user-dep-gen-branch so it
1779             # might be related.  In late 2003 people complained about
1780             # the size of the generated Makefile.ins (libgcj, with
1781             # 2200+ subdir objects was reported to have a 9MB
1782             # Makefile), so we now rely on inference rules again.
1783             # Maybe we'll run across the same issue as in the past,
1784             # but at least this time we can document it.  However since
1785             # dependency tracking has evolved it is possible that
1786             # our old problem no longer exists.
1787             # Using inference rules for subdir-objects has been tested
1788             # with GNU make, Solaris make, Ultrix make, BSD make,
1789             # HP-UX make, and OSF1 make successfully.
1790             if ($renamed
1791                 || ($directory ne '' && ! option 'subdir-objects')
1792                 # We must also use specific rules for a nodist_ source
1793                 # if its language requests it.
1794                 || ($lang->nodist_specific && ! $transform{'DIST_SOURCE'}))
1795             {
1796                 my $obj_sans_ext = substr ($object, 0,
1797                                            - length ($this_obj_ext));
1798                 my $full_ansi = $full;
1799                 if ($lang->ansi && option 'ansi2knr')
1800                   {
1801                     $full_ansi =~ s/$KNOWN_EXTENSIONS_PATTERN$/\$U$&/;
1802                     $obj_sans_ext .= '$U';
1803                   }
1805                 my @specifics = ($full_ansi, $obj_sans_ext,
1806                                  # Only use $this_obj_ext in the derived
1807                                  # source case because in the other case we
1808                                  # *don't* want $(OBJEXT) to appear here.
1809                                  ($derived_source ? $this_obj_ext : '.o'),
1810                                  $extension);
1812                 # If we renamed the object then we want to use the
1813                 # per-executable flag name.  But if this is simply a
1814                 # subdir build then we still want to use the AM_ flag
1815                 # name.
1816                 if ($renamed)
1817                   {
1818                     unshift @specifics, $derived;
1819                     $aggregate = $derived;
1820                   }
1821                 else
1822                   {
1823                     unshift @specifics, 'AM';
1824                   }
1826                 # Each item on this list is a reference to a list consisting
1827                 # of four values followed by additional transform flags for
1828                 # file_contents.   The four values are the derived flag prefix
1829                 # (e.g. for `foo_CFLAGS', it is `foo'), the name of the
1830                 # source file, the base name of the output file, and
1831                 # the extension for the object file.
1832                 push (@{$lang_specific_files{$lang->name}},
1833                       [@specifics, %transform]);
1834             }
1835         }
1836         elsif ($extension eq $nonansi_obj)
1837         {
1838             # This is probably the result of a direct suffix rule.
1839             # In this case we just accept the rewrite.
1840             $object = "$base$extension";
1841             $object = "$directory/$object" if $directory ne '';
1842             $linker = '';
1843         }
1844         else
1845         {
1846             # No error message here.  Used to have one, but it was
1847             # very unpopular.
1848             # FIXME: we could potentially do more processing here,
1849             # perhaps treating the new extension as though it were a
1850             # new source extension (as above).  This would require
1851             # more restructuring than is appropriate right now.
1852             next;
1853         }
1855         err_am "object `$object' created by `$full' and `$object_map{$object}'"
1856           if (defined $object_map{$object}
1857               && $object_map{$object} ne $full);
1859         my $comp_val = (($object =~ /\.lo$/)
1860                         ? COMPILE_LIBTOOL : COMPILE_ORDINARY);
1861         (my $comp_obj = $object) =~ s/\.lo$/.\$(OBJEXT)/;
1862         if (defined $object_compilation_map{$comp_obj}
1863             && $object_compilation_map{$comp_obj} != 0
1864             # Only see the error once.
1865             && ($object_compilation_map{$comp_obj}
1866                 != (COMPILE_LIBTOOL | COMPILE_ORDINARY))
1867             && $object_compilation_map{$comp_obj} != $comp_val)
1868           {
1869             err_am "object `$comp_obj' created both with libtool and without";
1870           }
1871         $object_compilation_map{$comp_obj} |= $comp_val;
1873         if (defined $lang)
1874         {
1875             # Let the language do some special magic if required.
1876             $lang->target_hook ($aggregate, $object, $full, %transform);
1877         }
1879         if ($derived_source)
1880           {
1881             prog_error ($lang->name . " has automatic dependency tracking")
1882               if $lang->autodep ne 'no';
1883             # Make sure this new source file is handled next.  That will
1884             # make it appear to be at the right place in the list.
1885             unshift (@files, $object);
1886             # Distribute derived sources unless the source they are
1887             # derived from is not.
1888             &push_dist_common ($object)
1889               unless ($topparent =~ /^(?:nobase_)?nodist_/);
1890             next;
1891           }
1893         $linkers_used{$linker} = 1;
1895         push (@result, $object);
1897         if (! defined $object_map{$object})
1898         {
1899             my @dep_list = ();
1900             $object_map{$object} = $full;
1902             # If resulting object is in subdir, we need to make
1903             # sure the subdir exists at build time.
1904             if ($object =~ /\//)
1905             {
1906                 # FIXME: check that $DIRECTORY is somewhere in the
1907                 # project
1909                 # For Java, the way we're handling it right now, a
1910                 # `..' component doesn't make sense.
1911                 if ($lang && $lang->name eq 'java' && $object =~ /(\/|^)\.\.\//)
1912                   {
1913                     err_am "`$full' should not contain a `..' component";
1914                   }
1916                 # Make sure object is removed by `make mostlyclean'.
1917                 $compile_clean_files{$object} = MOSTLY_CLEAN;
1918                 # If we have a libtool object then we also must remove
1919                 # the ordinary .o.
1920                 if ($object =~ /\.lo$/)
1921                 {
1922                     (my $xobj = $object) =~ s,lo$,\$(OBJEXT),;
1923                     $compile_clean_files{$xobj} = MOSTLY_CLEAN;
1925                     # Remove any libtool object in this directory.
1926                     $libtool_clean_directories{$directory} = 1;
1927                 }
1929                 push (@dep_list, require_build_directory ($directory));
1931                 # If we're generating dependencies, we also want
1932                 # to make sure that the appropriate subdir of the
1933                 # .deps directory is created.
1934                 push (@dep_list,
1935                       require_build_directory ($directory . '/$(DEPDIR)'))
1936                   unless option 'no-dependencies';
1937             }
1939             &pretty_print_rule ($object . ':', "\t", @dep_list)
1940                 if scalar @dep_list > 0;
1941         }
1943         # Transform .o or $o file into .P file (for automatic
1944         # dependency code).
1945         if ($lang && $lang->autodep ne 'no')
1946         {
1947             my $depfile = $object;
1948             $depfile =~ s/\.([^.]*)$/.P$1/;
1949             $depfile =~ s/\$\(OBJEXT\)$/o/;
1950             $dep_files{dirname ($depfile) . '/$(DEPDIR)/'
1951                          . basename ($depfile)} = 1;
1952         }
1953     }
1955     return @result;
1959 # $LINKER
1960 # define_objects_from_sources ($VAR, $OBJVAR, $NODEFINE, $ONE_FILE,
1961 #                              $OBJ, $PARENT, $TOPPARENT, $WHERE, %TRANSFORM)
1962 # ---------------------------------------------------------------------------
1963 # Define an _OBJECTS variable for a _SOURCES variable (or subvariable)
1965 # Arguments are:
1966 #   $VAR is the name of the _SOURCES variable
1967 #   $OBJVAR is the name of the _OBJECTS variable if known (otherwise
1968 #     it will be generated and returned).
1969 #   $NODEFINE is a boolean: if true, $OBJVAR will not be defined (but
1970 #     work done to determine the linker will be).
1971 #   $ONE_FILE is the canonical (transformed) name of object to build
1972 #   $OBJ is the object extension (i.e. either `.o' or `.lo').
1973 #   $TOPPARENT is the _SOURCES variable being processed.
1974 #   $WHERE context into which this definition is done
1975 #   %TRANSFORM extra arguments to pass to file_contents when producing
1976 #     rules
1978 # Result is a pair ($LINKER, $OBJVAR):
1979 #    $LINKER is a boolean, true if a linker is needed to deal with the objects
1980 sub define_objects_from_sources ($$$$$$$%)
1982   my ($var, $objvar, $nodefine, $one_file,
1983       $obj, $topparent, $where, %transform) = @_;
1985   my $needlinker = "";
1987   transform_variable_recursively
1988     ($var, $objvar, 'am__objects', $nodefine, $where,
1989      # The transform code to run on each filename.
1990      sub {
1991        my ($subvar, $val, $cond, $full_cond) = @_;
1992        my @trans = handle_single_transform ($subvar, $topparent,
1993                                             $one_file, $obj, $val,
1994                                             %transform);
1995        $needlinker = "true" if @trans;
1996        return @trans;
1997      });
1999   return $needlinker;
2003 # handle_source_transform ($CANON_TARGET, $TARGET, $OBJEXT, $WHERE, %TRANSFORM)
2004 # -----------------------------------------------------------------------------
2005 # Handle SOURCE->OBJECT transform for one program or library.
2006 # Arguments are:
2007 #   canonical (transformed) name of target to build
2008 #   actual target of object to build
2009 #   object extension (i.e., either `.o' or `$o')
2010 #   location of the source variable
2011 #   extra arguments to pass to file_contents when producing rules
2012 # Return the name of the linker variable that must be used.
2013 # Empty return means just use `LINK'.
2014 sub handle_source_transform ($$$$%)
2016     # one_file is canonical name.  unxformed is given name.  obj is
2017     # object extension.
2018     my ($one_file, $unxformed, $obj, $where, %transform) = @_;
2020     my $linker = '';
2022     # No point in continuing if _OBJECTS is defined.
2023     return if reject_var ($one_file . '_OBJECTS',
2024                           $one_file . '_OBJECTS should not be defined');
2026     my %used_pfx = ();
2027     my $needlinker;
2028     %linkers_used = ();
2029     foreach my $prefix ('', 'EXTRA_', 'dist_', 'nodist_',
2030                         'dist_EXTRA_', 'nodist_EXTRA_')
2031     {
2032         my $varname = $prefix . $one_file . "_SOURCES";
2033         my $var = var $varname;
2034         next unless $var;
2036         # We are going to define _OBJECTS variables using the prefix.
2037         # Then we glom them all together.  So we can't use the null
2038         # prefix here as we need it later.
2039         my $xpfx = ($prefix eq '') ? 'am_' : $prefix;
2041         # Keep track of which prefixes we saw.
2042         $used_pfx{$xpfx} = 1
2043           unless $prefix =~ /EXTRA_/;
2045         push @sources, "\$($varname)";
2046         push @dist_sources, shadow_unconditionally ($varname, $where)
2047           unless (option ('no-dist') || $prefix =~ /^nodist_/);
2049         $needlinker |=
2050             define_objects_from_sources ($varname,
2051                                          $xpfx . $one_file . '_OBJECTS',
2052                                          $prefix =~ /EXTRA_/,
2053                                          $one_file, $obj, $varname, $where,
2054                                          DIST_SOURCE => ($prefix !~ /^nodist_/),
2055                                          %transform);
2056     }
2057     if ($needlinker)
2058     {
2059         $linker ||= &resolve_linker (%linkers_used);
2060     }
2062     my @keys = sort keys %used_pfx;
2063     if (scalar @keys == 0)
2064     {
2065         # The default source for libfoo.la is libfoo.c, but for
2066         # backward compatibility we first look at libfoo_la.c,
2067         # if no default source suffix is given.
2068         my $old_default_source = "$one_file.c";
2069         my $ext_var = var ('AM_DEFAULT_SOURCE_EXT');
2070         my $default_source_ext = $ext_var ? variable_value ($ext_var) : '.c';
2071         msg_var ('unsupported', $ext_var, $ext_var->name . " can assume at most one value")
2072           if $default_source_ext =~ /[\t ]/;
2073         (my $default_source = $unxformed) =~ s,(\.[^./\\]*)?$,$default_source_ext,;
2074         if ($old_default_source ne $default_source
2075             && !$ext_var
2076             && (rule $old_default_source
2077                 || rule '$(srcdir)/' . $old_default_source
2078                 || rule '${srcdir}/' . $old_default_source
2079                 || -f $old_default_source))
2080           {
2081             my $loc = $where->clone;
2082             $loc->pop_context;
2083             msg ('obsolete', $loc,
2084                  "the default source for `$unxformed' has been changed "
2085                  . "to `$default_source'.\n(Using `$old_default_source' for "
2086                  . "backward compatibility.)");
2087             $default_source = $old_default_source;
2088           }
2089         # If a rule exists to build this source with a $(srcdir)
2090         # prefix, use that prefix in our variables too.  This is for
2091         # the sake of BSD Make.
2092         if (rule '$(srcdir)/' . $default_source
2093             || rule '${srcdir}/' . $default_source)
2094           {
2095             $default_source = '$(srcdir)/' . $default_source;
2096           }
2098         &define_variable ($one_file . "_SOURCES", $default_source, $where);
2099         push (@sources, $default_source);
2100         push (@dist_sources, $default_source);
2102         %linkers_used = ();
2103         my (@result) =
2104           handle_single_transform ($one_file . '_SOURCES',
2105                                    $one_file . '_SOURCES',
2106                                    $one_file, $obj,
2107                                    $default_source, %transform);
2108         $linker ||= &resolve_linker (%linkers_used);
2109         define_pretty_variable ($one_file . '_OBJECTS', TRUE, $where, @result);
2110     }
2111     else
2112     {
2113         @keys = map { '$(' . $_ . $one_file . '_OBJECTS)' } @keys;
2114         define_pretty_variable ($one_file . '_OBJECTS', TRUE, $where, @keys);
2115     }
2117     # If we want to use `LINK' we must make sure it is defined.
2118     if ($linker eq '')
2119     {
2120         $need_link = 1;
2121     }
2123     return $linker;
2127 # handle_lib_objects ($XNAME, $VAR)
2128 # ---------------------------------
2129 # Special-case ALLOCA and LIBOBJS substitutions in _LDADD or _LIBADD variables.
2130 # Also, generate _DEPENDENCIES variable if appropriate.
2131 # Arguments are:
2132 #   transformed name of object being built, or empty string if no object
2133 #   name of _LDADD/_LIBADD-type variable to examine
2134 # Returns 1 if LIBOBJS seen, 0 otherwise.
2135 sub handle_lib_objects
2137   my ($xname, $varname) = @_;
2139   my $var = var ($varname);
2140   prog_error "handle_lib_objects: `$varname' undefined"
2141     unless $var;
2142   prog_error "handle_lib_objects: unexpected variable name `$varname'"
2143     unless $varname =~ /^(.*)(?:LIB|LD)ADD$/;
2144   my $prefix = $1 || 'AM_';
2146   my $seen_libobjs = 0;
2147   my $flagvar = 0;
2149   transform_variable_recursively
2150     ($varname, $xname . '_DEPENDENCIES', 'am__DEPENDENCIES',
2151      ! $xname, INTERNAL,
2152      # Transformation function, run on each filename.
2153      sub {
2154        my ($subvar, $val, $cond, $full_cond) = @_;
2156        if ($val =~ /^-/)
2157          {
2158            # Skip -lfoo and -Ldir silently; these are explicitly allowed.
2159            if ($val !~ /^-[lL]/ &&
2160                # Skip -dlopen and -dlpreopen; these are explicitly allowed
2161                # for Libtool libraries or programs.  (Actually we are a bit
2162                # laxe here since this code also applies to non-libtool
2163                # libraries or programs, for which -dlopen and -dlopreopen
2164                # are pure nonsense.  Diagnosing this doesn't seem very
2165                # important: the developer will quickly get complaints from
2166                # the linker.)
2167                $val !~ /^-dl(?:pre)?open$/ &&
2168                # Only get this error once.
2169                ! $flagvar)
2170              {
2171                $flagvar = 1;
2172                # FIXME: should display a stack of nested variables
2173                # as context when $var != $subvar.
2174                err_var ($var, "linker flags such as `$val' belong in "
2175                         . "`${prefix}LDFLAGS");
2176              }
2177            return ();
2178          }
2179        elsif ($val !~ /^\@.*\@$/)
2180          {
2181            # Assume we have a file of some sort, and output it into the
2182            # dependency variable.  Autoconf substitutions are not output;
2183            # rarely is a new dependency substituted into e.g. foo_LDADD
2184            # -- but bad things (e.g. -lX11) are routinely substituted.
2185            # Note that LIBOBJS and ALLOCA are exceptions to this rule,
2186            # and handled specially below.
2187            return $val;
2188          }
2189        elsif ($val =~ /^\@(LT)?LIBOBJS\@$/)
2190          {
2191            handle_LIBOBJS ($subvar, $cond, $1);
2192            $seen_libobjs = 1;
2193            return $val;
2194          }
2195        elsif ($val =~ /^\@(LT)?ALLOCA\@$/)
2196          {
2197            handle_ALLOCA ($subvar, $cond, $1);
2198            return $val;
2199          }
2200        else
2201          {
2202            return ();
2203          }
2204      });
2206   return $seen_libobjs;
2209 # handle_LIBOBJS_or_ALLOCA ($VAR)
2210 # -------------------------------
2211 # Definitions common to LIBOBJS and ALLOCA.
2212 # VAR should be one of LIBOBJS, LTLIBOBJS, ALLOCA, or LTALLOCA.
2213 sub handle_LIBOBJS_or_ALLOCA ($)
2215   my ($var) = @_;
2217   my $dir = '';
2219   # If LIBOBJS files must be built in another directory we have
2220   # to define LIBOBJDIR and ensure the files get cleaned.
2221   # Otherwise LIBOBJDIR can be left undefined, and the cleaning
2222   # is achieved by `rm -f *.$(OBJEXT)' in compile.am.
2223   if ($config_libobj_dir
2224       && $relative_dir ne $config_libobj_dir)
2225     {
2226       if (option 'subdir-objects')
2227         {
2228           # In the top-level Makefile we do not use $(top_builddir), because
2229           # we are already there, and since the targets are built without
2230           # a $(top_builddir), it helps BSD Make to match them with
2231           # dependencies.
2232           $dir = "$config_libobj_dir/" if $config_libobj_dir ne '.';
2233           $dir = "$topsrcdir/$dir" if $relative_dir ne '.';
2234           define_variable ('LIBOBJDIR', "$dir", INTERNAL);
2235           $clean_files{"\$($var)"} = MOSTLY_CLEAN;
2236           # If LTLIBOBJS is used, we must also clear LIBOBJS (which might
2237           # be created by libtool as a side-effect of creating LTLIBOBJS).
2238           $clean_files{"\$($var)"} = MOSTLY_CLEAN if $var =~ s/^LT//;
2239         }
2240       else
2241         {
2242           error ("`\$($var)' cannot be used outside `$config_libobj_dir' if"
2243                  . " `subdir-objects' is not set");
2244         }
2245     }
2247   return $dir;
2250 sub handle_LIBOBJS ($$$)
2252   my ($var, $cond, $lt) = @_;
2253   my $myobjext = $lt ? 'lo' : 'o';
2254   $lt ||= '';
2256   $var->requires_variables ("\@${lt}LIBOBJS\@ used", $lt . 'LIBOBJS')
2257     if ! keys %libsources;
2259   my $dir = handle_LIBOBJS_or_ALLOCA "${lt}LIBOBJS";
2261   foreach my $iter (keys %libsources)
2262     {
2263       if ($iter =~ /\.[cly]$/)
2264         {
2265           &saw_extension ($&);
2266           &saw_extension ('.c');
2267         }
2269       if ($iter =~ /\.h$/)
2270         {
2271           require_libsource_with_macro ($cond, $var, FOREIGN, $iter);
2272         }
2273       elsif ($iter ne 'alloca.c')
2274         {
2275           my $rewrite = $iter;
2276           $rewrite =~ s/\.c$/.P$myobjext/;
2277           $dep_files{$dir . '$(DEPDIR)/' . $rewrite} = 1;
2278           $rewrite = "^" . quotemeta ($iter) . "\$";
2279           # Only require the file if it is not a built source.
2280           my $bs = var ('BUILT_SOURCES');
2281           if (! $bs || ! grep (/$rewrite/, $bs->value_as_list_recursive))
2282             {
2283               require_libsource_with_macro ($cond, $var, FOREIGN, $iter);
2284             }
2285         }
2286     }
2289 sub handle_ALLOCA ($$$)
2291   my ($var, $cond, $lt) = @_;
2292   my $myobjext = $lt ? 'lo' : 'o';
2293   $lt ||= '';
2294   my $dir = handle_LIBOBJS_or_ALLOCA "${lt}ALLOCA";
2296   $var->requires_variables ("\@${lt}ALLOCA\@ used", $lt . 'ALLOCA');
2297   $dep_files{$dir . '$(DEPDIR)/alloca.P' . $myobjext} = 1;
2298   require_libsource_with_macro ($cond, $var, FOREIGN, 'alloca.c');
2299   &saw_extension ('.c');
2302 # Canonicalize the input parameter
2303 sub canonicalize
2305     my ($string) = @_;
2306     $string =~ tr/A-Za-z0-9_\@/_/c;
2307     return $string;
2310 # Canonicalize a name, and check to make sure the non-canonical name
2311 # is never used.  Returns canonical name.  Arguments are name and a
2312 # list of suffixes to check for.
2313 sub check_canonical_spelling
2315   my ($name, @suffixes) = @_;
2317   my $xname = &canonicalize ($name);
2318   if ($xname ne $name)
2319     {
2320       foreach my $xt (@suffixes)
2321         {
2322           reject_var ("$name$xt", "use `$xname$xt', not `$name$xt'");
2323         }
2324     }
2326   return $xname;
2330 # handle_compile ()
2331 # -----------------
2332 # Set up the compile suite.
2333 sub handle_compile ()
2335     return
2336       unless $get_object_extension_was_run;
2338     # Boilerplate.
2339     my $default_includes = '';
2340     if (! option 'nostdinc')
2341       {
2342         my @incs = ('-I.', subst ('am__isrc'));
2344         my $var = var 'CONFIG_HEADER';
2345         if ($var)
2346           {
2347             foreach my $hdr (split (' ', $var->variable_value))
2348               {
2349                 push @incs, '-I' . dirname ($hdr);
2350               }
2351           }
2352         # We want `-I. -I$(srcdir)', but the latter -I is redundant
2353         # and unaesthetic in non-VPATH builds.  We use `-I.@am__isrc@`
2354         # instead.  It will be replaced by '-I.' or '-I. -I$(srcdir)'.
2355         # Items in CONFIG_HEADER are never in $(srcdir) so it is safe
2356         # to just put @am__isrc@ right after `-I.', without a space.
2357         ($default_includes = ' ' . uniq (@incs)) =~ s/ @/@/;
2358       }
2360     my (@mostly_rms, @dist_rms);
2361     foreach my $item (sort keys %compile_clean_files)
2362     {
2363         if ($compile_clean_files{$item} == MOSTLY_CLEAN)
2364         {
2365             push (@mostly_rms, "\t-rm -f $item");
2366         }
2367         elsif ($compile_clean_files{$item} == DIST_CLEAN)
2368         {
2369             push (@dist_rms, "\t-rm -f $item");
2370         }
2371         else
2372         {
2373           prog_error 'invalid entry in %compile_clean_files';
2374         }
2375     }
2377     my ($coms, $vars, $rules) =
2378       &file_contents_internal (1, "$libdir/am/compile.am",
2379                                new Automake::Location,
2380                                ('DEFAULT_INCLUDES' => $default_includes,
2381                                 'MOSTLYRMS' => join ("\n", @mostly_rms),
2382                                 'DISTRMS' => join ("\n", @dist_rms)));
2383     $output_vars .= $vars;
2384     $output_rules .= "$coms$rules";
2386     # Check for automatic de-ANSI-fication.
2387     if (option 'ansi2knr')
2388       {
2389         my ($ansi2knr_filename, $ansi2knr_where) = @{option 'ansi2knr'};
2390         my $ansi2knr_dir = '';
2392         require_variables ($ansi2knr_where, "option `ansi2knr' is used",
2393                            TRUE, "ANSI2KNR", "U");
2395         # topdir is where ansi2knr should be.
2396         if ($ansi2knr_filename eq 'ansi2knr')
2397           {
2398             # Only require ansi2knr files if they should appear in
2399             # this directory.
2400             require_file ($ansi2knr_where, FOREIGN,
2401                           'ansi2knr.c', 'ansi2knr.1');
2403             # ansi2knr needs to be built before subdirs, so unshift it.
2404             unshift (@all, '$(ANSI2KNR)');
2405           }
2406         else
2407           {
2408             $ansi2knr_dir = dirname ($ansi2knr_filename);
2409           }
2411         $output_rules .= &file_contents ('ansi2knr',
2412                                          new Automake::Location,
2413                                          'ANSI2KNR-DIR' => $ansi2knr_dir);
2415     }
2418 # handle_libtool ()
2419 # -----------------
2420 # Handle libtool rules.
2421 sub handle_libtool
2423   return unless var ('LIBTOOL');
2425   # Libtool requires some files, but only at top level.
2426   # (Starting with Libtool 2.0 we do not have to bother.  These
2427   # requirements are done with AC_REQUIRE_AUX_FILE.)
2428   require_conf_file_with_macro (TRUE, 'LIBTOOL', FOREIGN, @libtool_files)
2429     if $relative_dir eq '.' && ! $libtool_new_api;
2431   my @libtool_rms;
2432   foreach my $item (sort keys %libtool_clean_directories)
2433     {
2434       my $dir = ($item eq '.') ? '' : "$item/";
2435       # .libs is for Unix, _libs for DOS.
2436       push (@libtool_rms, "\t-rm -rf ${dir}.libs ${dir}_libs");
2437     }
2439   check_user_variables 'LIBTOOLFLAGS';
2441   # Output the libtool compilation rules.
2442   $output_rules .= &file_contents ('libtool',
2443                                    new Automake::Location,
2444                                    LTRMS => join ("\n", @libtool_rms));
2447 # handle_programs ()
2448 # ------------------
2449 # Handle C programs.
2450 sub handle_programs
2452   my @proglist = &am_install_var ('progs', 'PROGRAMS',
2453                                   'bin', 'sbin', 'libexec', 'pkglib',
2454                                   'noinst', 'check');
2455   return if ! @proglist;
2457   my $seen_global_libobjs =
2458     var ('LDADD') && &handle_lib_objects ('', 'LDADD');
2460   foreach my $pair (@proglist)
2461     {
2462       my ($where, $one_file) = @$pair;
2464       my $seen_libobjs = 0;
2465       my $obj = get_object_extension '.$(OBJEXT)';
2467       # Strip any $(EXEEXT) suffix the user might have added, or this
2468       # will confuse &handle_source_transform and &check_canonical_spelling.
2469       # We'll add $(EXEEXT) back later anyway.
2470       $one_file =~ s/\$\(EXEEXT\)$//;
2472       $known_programs{$one_file} = $where;
2474       # Canonicalize names and check for misspellings.
2475       my $xname = &check_canonical_spelling ($one_file, '_LDADD', '_LDFLAGS',
2476                                              '_SOURCES', '_OBJECTS',
2477                                              '_DEPENDENCIES');
2479       $where->push_context ("while processing program `$one_file'");
2480       $where->set (INTERNAL->get);
2482       my $linker = &handle_source_transform ($xname, $one_file, $obj, $where,
2483                                              NONLIBTOOL => 1, LIBTOOL => 0);
2485       if (var ($xname . "_LDADD"))
2486         {
2487           $seen_libobjs = &handle_lib_objects ($xname, $xname . '_LDADD');
2488         }
2489       else
2490         {
2491           # User didn't define prog_LDADD override.  So do it.
2492           &define_variable ($xname . '_LDADD', '$(LDADD)', $where);
2494           # This does a bit too much work.  But we need it to
2495           # generate _DEPENDENCIES when appropriate.
2496           if (var ('LDADD'))
2497             {
2498               $seen_libobjs = &handle_lib_objects ($xname, 'LDADD');
2499             }
2500         }
2502       reject_var ($xname . '_LIBADD',
2503                   "use `${xname}_LDADD', not `${xname}_LIBADD'");
2505       set_seen ($xname . '_DEPENDENCIES');
2506       set_seen ($xname . '_LDFLAGS');
2508       # Determine program to use for link.
2509       my $xlink = &define_per_target_linker_variable ($linker, $xname);
2511       # If the resulting program lies into a subdirectory,
2512       # make sure this directory will exist.
2513       my $dirstamp = require_build_directory_maybe ($one_file);
2515       $libtool_clean_directories{dirname ($one_file)} = 1;
2517       $output_rules .= &file_contents ('program',
2518                                        $where,
2519                                        PROGRAM  => $one_file,
2520                                        XPROGRAM => $xname,
2521                                        XLINK    => $xlink,
2522                                        DIRSTAMP => $dirstamp,
2523                                        EXEEXT   => '$(EXEEXT)');
2525       if ($seen_libobjs || $seen_global_libobjs)
2526         {
2527           if (var ($xname . '_LDADD'))
2528             {
2529               &check_libobjs_sources ($xname, $xname . '_LDADD');
2530             }
2531           elsif (var ('LDADD'))
2532             {
2533               &check_libobjs_sources ($xname, 'LDADD');
2534             }
2535         }
2536     }
2540 # handle_libraries ()
2541 # -------------------
2542 # Handle libraries.
2543 sub handle_libraries
2545   my @liblist = &am_install_var ('libs', 'LIBRARIES',
2546                                  'lib', 'pkglib', 'noinst', 'check');
2547   return if ! @liblist;
2549   my @prefix = am_primary_prefixes ('LIBRARIES', 0, 'lib', 'pkglib',
2550                                     'noinst', 'check');
2552   if (@prefix)
2553     {
2554       my $var = rvar ($prefix[0] . '_LIBRARIES');
2555       $var->requires_variables ('library used', 'RANLIB');
2556     }
2558   &define_variable ('AR', 'ar', INTERNAL);
2559   &define_variable ('ARFLAGS', 'cru', INTERNAL);
2561   foreach my $pair (@liblist)
2562     {
2563       my ($where, $onelib) = @$pair;
2565       my $seen_libobjs = 0;
2566       # Check that the library fits the standard naming convention.
2567       my $bn = basename ($onelib);
2568       if ($bn !~ /^lib.*\.a$/)
2569         {
2570           $bn =~ s/^(?:lib)?(.*?)(?:\.[^.]*)?$/lib$1.a/;
2571           my $suggestion = dirname ($onelib) . "/$bn";
2572           $suggestion =~ s|^\./||g;
2573           msg ('error-gnu/warn', $where,
2574                "`$onelib' is not a standard library name\n"
2575                . "did you mean `$suggestion'?")
2576         }
2578       $where->push_context ("while processing library `$onelib'");
2579       $where->set (INTERNAL->get);
2581       my $obj = get_object_extension '.$(OBJEXT)';
2583       # Canonicalize names and check for misspellings.
2584       my $xlib = &check_canonical_spelling ($onelib, '_LIBADD', '_SOURCES',
2585                                             '_OBJECTS', '_DEPENDENCIES',
2586                                             '_AR');
2588       if (! var ($xlib . '_AR'))
2589         {
2590           &define_variable ($xlib . '_AR', '$(AR) $(ARFLAGS)', $where);
2591         }
2593       # Generate support for conditional object inclusion in
2594       # libraries.
2595       if (var ($xlib . '_LIBADD'))
2596         {
2597           if (&handle_lib_objects ($xlib, $xlib . '_LIBADD'))
2598             {
2599               $seen_libobjs = 1;
2600             }
2601         }
2602       else
2603         {
2604           &define_variable ($xlib . "_LIBADD", '', $where);
2605         }
2607       reject_var ($xlib . '_LDADD',
2608                   "use `${xlib}_LIBADD', not `${xlib}_LDADD'");
2610       # Make sure we at look at this.
2611       set_seen ($xlib . '_DEPENDENCIES');
2613       &handle_source_transform ($xlib, $onelib, $obj, $where,
2614                                 NONLIBTOOL => 1, LIBTOOL => 0);
2616       # If the resulting library lies into a subdirectory,
2617       # make sure this directory will exist.
2618       my $dirstamp = require_build_directory_maybe ($onelib);
2620       $output_rules .= &file_contents ('library',
2621                                        $where,
2622                                        LIBRARY  => $onelib,
2623                                        XLIBRARY => $xlib,
2624                                        DIRSTAMP => $dirstamp);
2626       if ($seen_libobjs)
2627         {
2628           if (var ($xlib . '_LIBADD'))
2629             {
2630               &check_libobjs_sources ($xlib, $xlib . '_LIBADD');
2631             }
2632         }
2633     }
2637 # handle_ltlibraries ()
2638 # ---------------------
2639 # Handle shared libraries.
2640 sub handle_ltlibraries
2642   my @liblist = &am_install_var ('ltlib', 'LTLIBRARIES',
2643                                  'noinst', 'lib', 'pkglib', 'check');
2644   return if ! @liblist;
2646   my @prefix = am_primary_prefixes ('LTLIBRARIES', 0, 'lib', 'pkglib',
2647                                     'noinst', 'check');
2649   if (@prefix)
2650     {
2651       my $var = rvar ($prefix[0] . '_LTLIBRARIES');
2652       $var->requires_variables ('Libtool library used', 'LIBTOOL');
2653     }
2655   my %instdirs = ();
2656   my %instsubdirs = ();
2657   my %instconds = ();
2658   my %liblocations = ();        # Location (in Makefile.am) of each library.
2660   foreach my $key (@prefix)
2661     {
2662       # Get the installation directory of each library.
2663       my $dir = $key;
2664       my $strip_subdir = 1;
2665       if ($dir =~ /^nobase_/)
2666         {
2667           $dir =~ s/^nobase_//;
2668           $strip_subdir = 0;
2669         }
2670       my $var = rvar ($key . '_LTLIBRARIES');
2672       # We reject libraries which are installed in several places
2673       # in the same condition, because we can only specify one
2674       # `-rpath' option.
2675       $var->traverse_recursively
2676         (sub
2677          {
2678            my ($var, $val, $cond, $full_cond) = @_;
2679            my $hcond = $full_cond->human;
2680            my $where = $var->rdef ($cond)->location;
2681            my $ldir = '';
2682            $ldir = '/' . dirname ($val)
2683              if (!$strip_subdir);
2684            # A library cannot be installed in different directory
2685            # in overlapping conditions.
2686            if (exists $instconds{$val})
2687              {
2688                my ($msg, $acond) =
2689                  $instconds{$val}->ambiguous_p ($val, $full_cond);
2691                if ($msg)
2692                  {
2693                    error ($where, $msg, partial => 1);
2694                    my $dirtxt = "installed " . ($strip_subdir ? "in" : "below") . " `$dir'";
2695                    $dirtxt = "built for `$dir'"
2696                      if $dir eq 'EXTRA' || $dir eq 'noinst' || $dir eq 'check';
2697                    my $dircond =
2698                      $full_cond->true ? "" : " in condition $hcond";
2700                    error ($where, "`$val' should be $dirtxt$dircond ...",
2701                           partial => 1);
2703                    my $hacond = $acond->human;
2704                    my $adir = $instdirs{$val}{$acond};
2705                    my $adirtxt = "installed in `$adir'";
2706                    $adirtxt = "built for `$adir'"
2707                      if ($adir eq 'EXTRA' || $adir eq 'noinst'
2708                          || $adir eq 'check');
2709                    my $adircond = $acond->true ? "" : " in condition $hacond";
2711                    my $onlyone = ($dir ne $adir) ?
2712                      ("\nLibtool libraries can be built for only one "
2713                       . "destination.") : "";
2715                    error ($liblocations{$val}{$acond},
2716                           "... and should also be $adirtxt$adircond.$onlyone");
2717                    return;
2718                  }
2719              }
2720            else
2721              {
2722                $instconds{$val} = new Automake::DisjConditions;
2723              }
2724            $instdirs{$val}{$full_cond} = $dir;
2725            $instsubdirs{$val}{$full_cond} = $ldir;
2726            $liblocations{$val}{$full_cond} = $where;
2727            $instconds{$val} = $instconds{$val}->merge ($full_cond);
2728          },
2729          sub
2730          {
2731            return ();
2732          },
2733          skip_ac_subst => 1);
2734     }
2736   foreach my $pair (@liblist)
2737     {
2738       my ($where, $onelib) = @$pair;
2740       my $seen_libobjs = 0;
2741       my $obj = get_object_extension '.lo';
2743       # Canonicalize names and check for misspellings.
2744       my $xlib = &check_canonical_spelling ($onelib, '_LIBADD', '_LDFLAGS',
2745                                             '_SOURCES', '_OBJECTS',
2746                                             '_DEPENDENCIES');
2748       # Check that the library fits the standard naming convention.
2749       my $libname_rx = '^lib.*\.la';
2750       my $ldvar = var ("${xlib}_LDFLAGS") || var ('AM_LDFLAGS');
2751       my $ldvar2 = var ('LDFLAGS');
2752       if (($ldvar && grep (/-module/, $ldvar->value_as_list_recursive))
2753           || ($ldvar2 && grep (/-module/, $ldvar2->value_as_list_recursive)))
2754         {
2755           # Relax name checking for libtool modules.
2756           $libname_rx = '\.la';
2757         }
2759       my $bn = basename ($onelib);
2760       if ($bn !~ /$libname_rx$/)
2761         {
2762           my $type = 'library';
2763           if ($libname_rx eq '\.la')
2764             {
2765               $bn =~ s/^(lib|)(.*?)(?:\.[^.]*)?$/$1$2.la/;
2766               $type = 'module';
2767             }
2768           else
2769             {
2770               $bn =~ s/^(?:lib)?(.*?)(?:\.[^.]*)?$/lib$1.la/;
2771             }
2772           my $suggestion = dirname ($onelib) . "/$bn";
2773           $suggestion =~ s|^\./||g;
2774           msg ('error-gnu/warn', $where,
2775                "`$onelib' is not a standard libtool $type name\n"
2776                . "did you mean `$suggestion'?")
2777         }
2779       $where->push_context ("while processing Libtool library `$onelib'");
2780       $where->set (INTERNAL->get);
2782       # Make sure we look at these.
2783       set_seen ($xlib . '_LDFLAGS');
2784       set_seen ($xlib . '_DEPENDENCIES');
2786       # Generate support for conditional object inclusion in
2787       # libraries.
2788       if (var ($xlib . '_LIBADD'))
2789         {
2790           if (&handle_lib_objects ($xlib, $xlib . '_LIBADD'))
2791             {
2792               $seen_libobjs = 1;
2793             }
2794         }
2795       else
2796         {
2797           &define_variable ($xlib . "_LIBADD", '', $where);
2798         }
2800       reject_var ("${xlib}_LDADD",
2801                   "use `${xlib}_LIBADD', not `${xlib}_LDADD'");
2804       my $linker = &handle_source_transform ($xlib, $onelib, $obj, $where,
2805                                              NONLIBTOOL => 0, LIBTOOL => 1);
2807       # Determine program to use for link.
2808       my $xlink = &define_per_target_linker_variable ($linker, $xlib);
2810       my $rpathvar = "am_${xlib}_rpath";
2811       my $rpath = "\$($rpathvar)";
2812       foreach my $rcond ($instconds{$onelib}->conds)
2813         {
2814           my $val;
2815           if ($instdirs{$onelib}{$rcond} eq 'EXTRA'
2816               || $instdirs{$onelib}{$rcond} eq 'noinst'
2817               || $instdirs{$onelib}{$rcond} eq 'check')
2818             {
2819               # It's an EXTRA_ library, so we can't specify -rpath,
2820               # because we don't know where the library will end up.
2821               # The user probably knows, but generally speaking automake
2822               # doesn't -- and in fact configure could decide
2823               # dynamically between two different locations.
2824               $val = '';
2825             }
2826           else
2827             {
2828               $val = ('-rpath $(' . $instdirs{$onelib}{$rcond} . 'dir)');
2829               $val .= $instsubdirs{$onelib}{$rcond}
2830                 if defined $instsubdirs{$onelib}{$rcond};
2831             }
2832           if ($rcond->true)
2833             {
2834               # If $rcond is true there is only one condition and
2835               # there is no point defining an helper variable.
2836               $rpath = $val;
2837             }
2838           else
2839             {
2840               define_pretty_variable ($rpathvar, $rcond, INTERNAL, $val);
2841             }
2842         }
2844       # If the resulting library lies into a subdirectory,
2845       # make sure this directory will exist.
2846       my $dirstamp = require_build_directory_maybe ($onelib);
2848       # Remember to cleanup .libs/ in this directory.
2849       my $dirname = dirname $onelib;
2850       $libtool_clean_directories{$dirname} = 1;
2852       $output_rules .= &file_contents ('ltlibrary',
2853                                        $where,
2854                                        LTLIBRARY  => $onelib,
2855                                        XLTLIBRARY => $xlib,
2856                                        RPATH      => $rpath,
2857                                        XLINK      => $xlink,
2858                                        DIRSTAMP   => $dirstamp);
2859       if ($seen_libobjs)
2860         {
2861           if (var ($xlib . '_LIBADD'))
2862             {
2863               &check_libobjs_sources ($xlib, $xlib . '_LIBADD');
2864             }
2865         }
2866     }
2869 # See if any _SOURCES variable were misspelled.
2870 sub check_typos ()
2872   # It is ok if the user sets this particular variable.
2873   set_seen 'AM_LDFLAGS';
2875   foreach my $primary ('SOURCES', 'LIBADD', 'LDADD', 'LDFLAGS', 'DEPENDENCIES')
2876     {
2877       foreach my $var (variables $primary)
2878         {
2879           my $varname = $var->name;
2880           # A configure variable is always legitimate.
2881           next if exists $configure_vars{$varname};
2883           for my $cond ($var->conditions->conds)
2884             {
2885               $varname =~ /^(?:nobase_)?(?:dist_|nodist_)?(.*)_[[:alnum:]]+$/;
2886               msg_var ('syntax', $var, "variable `$varname' is defined but no"
2887                        . " program or\nlibrary has `$1' as canonic name"
2888                        . " (possible typo)")
2889                 unless $var->rdef ($cond)->seen;
2890             }
2891         }
2892     }
2896 # Handle scripts.
2897 sub handle_scripts
2899     # NOTE we no longer automatically clean SCRIPTS, because it is
2900     # useful to sometimes distribute scripts verbatim.  This happens
2901     # e.g. in Automake itself.
2902     &am_install_var ('-candist', 'scripts', 'SCRIPTS',
2903                      'bin', 'sbin', 'libexec', 'pkgdata',
2904                      'noinst', 'check');
2910 ## ------------------------ ##
2911 ## Handling Texinfo files.  ##
2912 ## ------------------------ ##
2914 # ($OUTFILE, $VFILE, @CLEAN_FILES)
2915 # &scan_texinfo_file ($FILENAME)
2916 # ------------------------------
2917 # $OUTFILE     - name of the info file produced by $FILENAME.
2918 # $VFILE       - name of the version.texi file used (undef if none).
2919 # @CLEAN_FILES - list of byproducts (indexes etc.)
2920 sub scan_texinfo_file ($)
2922   my ($filename) = @_;
2924   # Some of the following extensions are always created, no matter
2925   # whether indexes are used or not.  Other (like cps, fns, ... pgs)
2926   # are only created when they are used.  We used to scan $FILENAME
2927   # for their use, but that is not enough: they could be used in
2928   # included files.  We can't scan included files because we don't
2929   # know the include path.  Therefore we always erase these files, no
2930   # matter whether they are used or not.
2931   #
2932   # (tmp is only created if an @macro is used and a certain e-TeX
2933   # feature is not available.)
2934   my %clean_suffixes =
2935     map { $_ => 1 } (qw(aux log toc tmp
2936                         cp cps
2937                         fn fns
2938                         ky kys
2939                         vr vrs
2940                         tp tps
2941                         pg pgs)); # grep 'new.*index' texinfo.tex
2943   my $texi = new Automake::XFile "< $filename";
2944   verb "reading $filename";
2946   my ($outfile, $vfile);
2947   while ($_ = $texi->getline)
2948     {
2949       if (/^\@setfilename +(\S+)/)
2950         {
2951           # Honor only the first @setfilename.  (It's possible to have
2952           # more occurrences later if the manual shows examples of how
2953           # to use @setfilename...)
2954           next if $outfile;
2956           $outfile = $1;
2957           if ($outfile =~ /\.([^.]+)$/ && $1 ne 'info')
2958             {
2959               error ("$filename:$.",
2960                      "output `$outfile' has unrecognized extension");
2961               return;
2962             }
2963         }
2964       # A "version.texi" file is actually any file whose name matches
2965       # "vers*.texi".
2966       elsif (/^\@include\s+(vers[^.]*\.texi)\s*$/)
2967         {
2968           $vfile = $1;
2969         }
2971       # Try to find new or unused indexes.
2973       # Creating a new category of index.
2974       elsif (/^\@def(code)?index (\w+)/)
2975         {
2976           $clean_suffixes{$2} = 1;
2977           $clean_suffixes{"$2s"} = 1;
2978         }
2980       # Merging an index into an another.
2981       elsif (/^\@syn(code)?index (\w+) (\w+)/)
2982         {
2983           delete $clean_suffixes{"$2s"};
2984           $clean_suffixes{"$3s"} = 1;
2985         }
2987     }
2989   if (! $outfile)
2990     {
2991       err_am "`$filename' missing \@setfilename";
2992       return;
2993     }
2995   my $infobase = basename ($filename);
2996   $infobase =~ s/\.te?xi(nfo)?$//;
2997   return ($outfile, $vfile,
2998           map { "$infobase.$_" } (sort keys %clean_suffixes));
3002 # ($DIRSTAMP, @CLEAN_FILES)
3003 # output_texinfo_build_rules ($SOURCE, $DEST, $INSRC, @DEPENDENCIES)
3004 # ------------------------------------------------------------------
3005 # SOURCE - the source Texinfo file
3006 # DEST - the destination Info file
3007 # INSRC - wether DEST should be built in the source tree
3008 # DEPENDENCIES - known dependencies
3009 sub output_texinfo_build_rules ($$$@)
3011   my ($source, $dest, $insrc, @deps) = @_;
3013   # Split `a.texi' into `a' and `.texi'.
3014   my ($spfx, $ssfx) = ($source =~ /^(.*?)(\.[^.]*)?$/);
3015   my ($dpfx, $dsfx) = ($dest =~ /^(.*?)(\.[^.]*)?$/);
3017   $ssfx ||= "";
3018   $dsfx ||= "";
3020   # We can output two kinds of rules: the "generic" rules use Make
3021   # suffix rules and are appropriate when $source and $dest do not lie
3022   # in a sub-directory; the "specific" rules are needed in the other
3023   # case.
3024   #
3025   # The former are output only once (this is not really apparent here,
3026   # but just remember that some logic deeper in Automake will not
3027   # output the same rule twice); while the later need to be output for
3028   # each Texinfo source.
3029   my $generic;
3030   my $makeinfoflags;
3031   my $sdir = dirname $source;
3032   if ($sdir eq '.' && dirname ($dest) eq '.')
3033     {
3034       $generic = 1;
3035       $makeinfoflags = '-I $(srcdir)';
3036     }
3037   else
3038     {
3039       $generic = 0;
3040       $makeinfoflags = "-I $sdir -I \$(srcdir)/$sdir";
3041     }
3043   # A directory can contain two kinds of info files: some built in the
3044   # source tree, and some built in the build tree.  The rules are
3045   # different in each case.  However we cannot output two different
3046   # set of generic rules.  Because in-source builds are more usual, we
3047   # use generic rules in this case and fall back to "specific" rules
3048   # for build-dir builds.  (It should not be a problem to invert this
3049   # if needed.)
3050   $generic = 0 unless $insrc;
3052   # We cannot use a suffix rule to build info files with an empty
3053   # extension.  Otherwise we would output a single suffix inference
3054   # rule, with separate dependencies, as in
3055   #
3056   #    .texi:
3057   #             $(MAKEINFO) ...
3058   #    foo.info: foo.texi
3059   #
3060   # which confuse Solaris make.  (See the Autoconf manual for
3061   # details.)  Therefore we use a specific rule in this case.  This
3062   # applies to info files only (dvi and pdf files always have an
3063   # extension).
3064   my $generic_info = ($generic && $dsfx) ? 1 : 0;
3066   # If the resulting file lie into a subdirectory,
3067   # make sure this directory will exist.
3068   my $dirstamp = require_build_directory_maybe ($dest);
3070   my $dipfx = ($insrc ? '$(srcdir)/' : '') . $dpfx;
3072   $output_rules .= file_contents ('texibuild',
3073                                   new Automake::Location,
3074                                   DEPS             => "@deps",
3075                                   DEST_PREFIX      => $dpfx,
3076                                   DEST_INFO_PREFIX => $dipfx,
3077                                   DEST_SUFFIX      => $dsfx,
3078                                   DIRSTAMP         => $dirstamp,
3079                                   GENERIC          => $generic,
3080                                   GENERIC_INFO     => $generic_info,
3081                                   INSRC            => $insrc,
3082                                   MAKEINFOFLAGS    => $makeinfoflags,
3083                                   SOURCE           => ($generic
3084                                                        ? '$<' : $source),
3085                                   SOURCE_INFO      => ($generic_info
3086                                                        ? '$<' : $source),
3087                                   SOURCE_REAL      => $source,
3088                                   SOURCE_SUFFIX    => $ssfx,
3089                                   );
3090   return ($dirstamp, "$dpfx.dvi", "$dpfx.pdf", "$dpfx.ps", "$dpfx.html");
3094 # $TEXICLEANS
3095 # handle_texinfo_helper ($info_texinfos)
3096 # --------------------------------------
3097 # Handle all Texinfo source; helper for handle_texinfo.
3098 sub handle_texinfo_helper ($)
3100   my ($info_texinfos) = @_;
3101   my (@infobase, @info_deps_list, @texi_deps);
3102   my %versions;
3103   my $done = 0;
3104   my @texi_cleans;
3106   # Build a regex matching user-cleaned files.
3107   my $d = var 'DISTCLEANFILES';
3108   my $c = var 'CLEANFILES';
3109   my @f = ();
3110   push @f, $d->value_as_list_recursive (inner_expand => 1) if $d;
3111   push @f, $c->value_as_list_recursive (inner_expand => 1) if $c;
3112   @f = map { s|[^A-Za-z_0-9*\[\]\-]|\\$&|g; s|\*|[^/]*|g; $_; } @f;
3113   my $user_cleaned_files = '^(?:' . join ('|', @f) . ')$';
3115   foreach my $texi
3116       ($info_texinfos->value_as_list_recursive (inner_expand => 1))
3117     {
3118       my $infobase = $texi;
3119       $infobase =~ s/\.(txi|texinfo|texi)$//;
3121       if ($infobase eq $texi)
3122         {
3123           # FIXME: report line number.
3124           err_am "texinfo file `$texi' has unrecognized extension";
3125           next;
3126         }
3128       push @infobase, $infobase;
3130       # If 'version.texi' is referenced by input file, then include
3131       # automatic versioning capability.
3132       my ($out_file, $vtexi, @clean_files) =
3133         scan_texinfo_file ("$relative_dir/$texi")
3134         or next;
3135       push (@texi_cleans, @clean_files);
3137       # If the Texinfo source is in a subdirectory, create the
3138       # resulting info in this subdirectory.  If it is in the current
3139       # directory, try hard to not prefix "./" because it breaks the
3140       # generic rules.
3141       my $outdir = dirname ($texi) . '/';
3142       $outdir = "" if $outdir eq './';
3143       $out_file =  $outdir . $out_file;
3145       # Until Automake 1.6.3, .info files were built in the
3146       # source tree.  This was an obstacle to the support of
3147       # non-distributed .info files, and non-distributed .texi
3148       # files.
3149       #
3150       # * Non-distributed .texi files is important in some packages
3151       #   where .texi files are built at make time, probably using
3152       #   other binaries built in the package itself, maybe using
3153       #   tools or information found on the build host.  Because
3154       #   these files are not distributed they are always rebuilt
3155       #   at make time; they should therefore not lie in the source
3156       #   directory.  One plan was to support this using
3157       #   nodist_info_TEXINFOS or something similar.  (Doing this
3158       #   requires some sanity checks.  For instance Automake should
3159       #   not allow:
3160       #      dist_info_TEXINFOS = foo.texi
3161       #      nodist_foo_TEXINFOS = included.texi
3162       #   because a distributed file should never depend on a
3163       #   non-distributed file.)
3164       #
3165       # * If .texi files are not distributed, then .info files should
3166       #   not be distributed either.  There are also cases where one
3167       #   wants to distribute .texi files, but does not want to
3168       #   distribute the .info files.  For instance the Texinfo package
3169       #   distributes the tool used to build these files; it would
3170       #   be a waste of space to distribute them.  It's not clear
3171       #   which syntax we should use to indicate that .info files should
3172       #   not be distributed.  Akim Demaille suggested that eventually
3173       #   we switch to a new syntax:
3174       #   |  Maybe we should take some inspiration from what's already
3175       #   |  done in the rest of Automake.  Maybe there is too much
3176       #   |  syntactic sugar here, and you want
3177       #   |     nodist_INFO = bar.info
3178       #   |     dist_bar_info_SOURCES = bar.texi
3179       #   |     bar_texi_DEPENDENCIES = foo.texi
3180       #   |  with a bit of magic to have bar.info represent the whole
3181       #   |  bar*info set.  That's a lot more verbose that the current
3182       #   |  situation, but it is # not new, hence the user has less
3183       #   |  to learn.
3184       #   |
3185       #   |  But there is still too much room for meaningless specs:
3186       #   |     nodist_INFO = bar.info
3187       #   |     dist_bar_info_SOURCES = bar.texi
3188       #   |     dist_PS = bar.ps something-written-by-hand.ps
3189       #   |     nodist_bar_ps_SOURCES = bar.texi
3190       #   |     bar_texi_DEPENDENCIES = foo.texi
3191       #   |  here bar.texi is dist_ in line 2, and nodist_ in 4.
3192       #
3193       # Back to the point, it should be clear that in order to support
3194       # non-distributed .info files, we need to build them in the
3195       # build tree, not in the source tree (non-distributed .texi
3196       # files are less of a problem, because we do not output build
3197       # rules for them).  In Automake 1.7 .info build rules have been
3198       # largely cleaned up so that .info files get always build in the
3199       # build tree, even when distributed.  The idea was that
3200       #   (1) if during a VPATH build the .info file was found to be
3201       #       absent or out-of-date (in the source tree or in the
3202       #       build tree), Make would rebuild it in the build tree.
3203       #       If an up-to-date source-tree of the .info file existed,
3204       #       make would not rebuild it in the build tree.
3205       #   (2) having two copies of .info files, one in the source tree
3206       #       and one (newer) in the build tree is not a problem
3207       #       because `make dist' always pick files in the build tree
3208       #       first.
3209       # However it turned out the be a bad idea for several reasons:
3210       #   * Tru64, OpenBSD, and FreeBSD (not NetBSD) Make do not behave
3211       #     like GNU Make on point (1) above.  These implementations
3212       #     of Make would always rebuild .info files in the build
3213       #     tree, even if such files were up to date in the source
3214       #     tree.  Consequently, it was impossible to perform a VPATH
3215       #     build of a package containing Texinfo files using these
3216       #     Make implementations.
3217       #     (Refer to the Autoconf Manual, section "Limitation of
3218       #     Make", paragraph "VPATH", item "target lookup", for
3219       #     an account of the differences between these
3220       #     implementations.)
3221       #   * The GNU Coding Standards require these files to be built
3222       #     in the source-tree (when they are distributed, that is).
3223       #   * Keeping a fresher copy of distributed files in the
3224       #     build tree can be annoying during development because
3225       #     - if the files is kept under CVS, you really want it
3226       #       to be updated in the source tree
3227       #     - it is confusing that `make distclean' does not erase
3228       #       all files in the build tree.
3229       #
3230       # Consequently, starting with Automake 1.8, .info files are
3231       # built in the source tree again.  Because we still plan to
3232       # support non-distributed .info files at some point, we
3233       # have a single variable ($INSRC) that controls whether
3234       # the current .info file must be built in the source tree
3235       # or in the build tree.  Actually this variable is switched
3236       # off for .info files that appear to be cleaned; this is
3237       # for backward compatibility with package such as Texinfo,
3238       # which do things like
3239       #   info_TEXINFOS = texinfo.txi info-stnd.texi info.texi
3240       #   DISTCLEANFILES = texinfo texinfo-* info*.info*
3241       #   # Do not create info files for distribution.
3242       #   dist-info:
3243       # in order not to distribute .info files.
3244       my $insrc = ($out_file =~ $user_cleaned_files) ? 0 : 1;
3246       my $soutdir = '$(srcdir)/' . $outdir;
3247       $outdir = $soutdir if $insrc;
3249       # If user specified file_TEXINFOS, then use that as explicit
3250       # dependency list.
3251       @texi_deps = ();
3252       push (@texi_deps, "$soutdir$vtexi") if $vtexi;
3254       my $canonical = canonicalize ($infobase);
3255       if (var ($canonical . "_TEXINFOS"))
3256         {
3257           push (@texi_deps, '$(' . $canonical . '_TEXINFOS)');
3258           push_dist_common ('$(' . $canonical . '_TEXINFOS)');
3259         }
3261       my ($dirstamp, @cfiles) =
3262         output_texinfo_build_rules ($texi, $out_file, $insrc, @texi_deps);
3263       push (@texi_cleans, @cfiles);
3265       push (@info_deps_list, $out_file);
3267       # If a vers*.texi file is needed, emit the rule.
3268       if ($vtexi)
3269         {
3270           err_am ("`$vtexi', included in `$texi', "
3271                   . "also included in `$versions{$vtexi}'")
3272             if defined $versions{$vtexi};
3273           $versions{$vtexi} = $texi;
3275           # We number the stamp-vti files.  This is doable since the
3276           # actual names don't matter much.  We only number starting
3277           # with the second one, so that the common case looks nice.
3278           my $vti = ($done ? $done : 'vti');
3279           ++$done;
3281           # This is ugly, but it is our historical practice.
3282           if ($config_aux_dir_set_in_configure_ac)
3283             {
3284               require_conf_file_with_macro (TRUE, 'info_TEXINFOS', FOREIGN,
3285                                             'mdate-sh');
3286             }
3287           else
3288             {
3289               require_file_with_macro (TRUE, 'info_TEXINFOS',
3290                                        FOREIGN, 'mdate-sh');
3291             }
3293           my $conf_dir;
3294           if ($config_aux_dir_set_in_configure_ac)
3295             {
3296               $conf_dir = "$am_config_aux_dir/";
3297             }
3298           else
3299             {
3300               $conf_dir = '$(srcdir)/';
3301             }
3302           $output_rules .= file_contents ('texi-vers',
3303                                           new Automake::Location,
3304                                           TEXI     => $texi,
3305                                           VTI      => $vti,
3306                                           STAMPVTI => "${soutdir}stamp-$vti",
3307                                           VTEXI    => "$soutdir$vtexi",
3308                                           MDDIR    => $conf_dir,
3309                                           DIRSTAMP => $dirstamp);
3310         }
3311     }
3313   # Handle location of texinfo.tex.
3314   my $need_texi_file = 0;
3315   my $texinfodir;
3316   if (var ('TEXINFO_TEX'))
3317     {
3318       # The user defined TEXINFO_TEX so assume he knows what he is
3319       # doing.
3320       $texinfodir = ('$(srcdir)/'
3321                      . dirname (variable_value ('TEXINFO_TEX')));
3322     }
3323   elsif (option 'cygnus')
3324     {
3325       $texinfodir = '$(top_srcdir)/../texinfo';
3326       define_variable ('TEXINFO_TEX', "$texinfodir/texinfo.tex", INTERNAL);
3327     }
3328   elsif ($config_aux_dir_set_in_configure_ac)
3329     {
3330       $texinfodir = $am_config_aux_dir;
3331       define_variable ('TEXINFO_TEX', "$texinfodir/texinfo.tex", INTERNAL);
3332       $need_texi_file = 2; # so that we require_conf_file later
3333     }
3334   else
3335     {
3336       $texinfodir = '$(srcdir)';
3337       $need_texi_file = 1;
3338     }
3339   define_variable ('am__TEXINFO_TEX_DIR', $texinfodir, INTERNAL);
3341   push (@dist_targets, 'dist-info');
3343   if (! option 'no-installinfo')
3344     {
3345       # Make sure documentation is made and installed first.  Use
3346       # $(INFO_DEPS), not 'info', because otherwise recursive makes
3347       # get run twice during "make all".
3348       unshift (@all, '$(INFO_DEPS)');
3349     }
3351   define_files_variable ("DVIS", @infobase, 'dvi', INTERNAL);
3352   define_files_variable ("PDFS", @infobase, 'pdf', INTERNAL);
3353   define_files_variable ("PSS", @infobase, 'ps', INTERNAL);
3354   define_files_variable ("HTMLS", @infobase, 'html', INTERNAL);
3356   # This next isn't strictly needed now -- the places that look here
3357   # could easily be changed to look in info_TEXINFOS.  But this is
3358   # probably better, in case noinst_TEXINFOS is ever supported.
3359   define_variable ("TEXINFOS", variable_value ('info_TEXINFOS'), INTERNAL);
3361   # Do some error checking.  Note that this file is not required
3362   # when in Cygnus mode; instead we defined TEXINFO_TEX explicitly
3363   # up above.
3364   if ($need_texi_file && ! option 'no-texinfo.tex')
3365     {
3366       if ($need_texi_file > 1)
3367         {
3368           require_conf_file_with_macro (TRUE, 'info_TEXINFOS', FOREIGN,
3369                                         'texinfo.tex');
3370         }
3371       else
3372         {
3373           require_file_with_macro (TRUE, 'info_TEXINFOS', FOREIGN,
3374                                    'texinfo.tex');
3375         }
3376     }
3378   return makefile_wrap ("", "\t  ", @texi_cleans);
3382 # handle_texinfo ()
3383 # -----------------
3384 # Handle all Texinfo source.
3385 sub handle_texinfo ()
3387   reject_var 'TEXINFOS', "`TEXINFOS' is an anachronism; use `info_TEXINFOS'";
3388   # FIXME: I think this is an obsolete future feature name.
3389   reject_var 'html_TEXINFOS', "HTML generation not yet supported";
3391   my $info_texinfos = var ('info_TEXINFOS');
3392   my $texiclean = "";
3393   if ($info_texinfos)
3394     {
3395       $texiclean = handle_texinfo_helper ($info_texinfos);
3396     }
3397   $output_rules .=  file_contents ('texinfos',
3398                                    new Automake::Location,
3399                                    TEXICLEAN     => $texiclean,
3400                                    'LOCAL-TEXIS' => !!$info_texinfos);
3404 # Handle any man pages.
3405 sub handle_man_pages
3407   reject_var 'MANS', "`MANS' is an anachronism; use `man_MANS'";
3409   # Find all the sections in use.  We do this by first looking for
3410   # "standard" sections, and then looking for any additional
3411   # sections used in man_MANS.
3412   my (%sections, %notrans_sections, %trans_sections,
3413       %notrans_vars, %trans_vars, %notrans_sect_vars, %trans_sect_vars);
3414   # We handle nodist_ for uniformity.  man pages aren't distributed
3415   # by default so it isn't actually very important.
3416   foreach my $npfx ('', 'notrans_')
3417     {
3418       foreach my $pfx ('', 'dist_', 'nodist_')
3419         {
3420           # Add more sections as needed.
3421           foreach my $section ('0'..'9', 'n', 'l')
3422             {
3423               my $varname = $npfx . $pfx . 'man' . $section . '_MANS';
3424               if (var ($varname))
3425                 {
3426                   $sections{$section} = 1;
3427                   $varname = '$(' . $varname . ')';
3428                   if ($npfx eq 'notrans_')
3429                     {
3430                       $notrans_sections{$section} = 1;
3431                       $notrans_sect_vars{$varname} = 1;
3432                     }
3433                   else
3434                     {
3435                       $trans_sections{$section} = 1;
3436                       $trans_sect_vars{$varname} = 1;
3437                     }
3439                   &push_dist_common ($varname)
3440                     if $pfx eq 'dist_';
3441                 }
3442             }
3444           my $varname = $npfx . $pfx . 'man_MANS';
3445           my $var = var ($varname);
3446           if ($var)
3447             {
3448               foreach ($var->value_as_list_recursive)
3449                 {
3450                   # A page like `foo.1c' goes into man1dir.
3451                   if (/\.([0-9a-z])([a-z]*)$/)
3452                     {
3453                       $sections{$1} = 1;
3454                       if ($npfx eq 'notrans_')
3455                         {
3456                           $notrans_sections{$1} = 1;
3457                         }
3458                       else
3459                         {
3460                           $trans_sections{$1} = 1;
3461                         }
3462                     }
3463                 }
3465               $varname = '$(' . $varname . ')';
3466               if ($npfx eq 'notrans_')
3467                 {
3468                   $notrans_vars{$varname} = 1;
3469                 }
3470               else
3471                 {
3472                   $trans_vars{$varname} = 1;
3473                 }
3474               &push_dist_common ($varname)
3475                 if $pfx eq 'dist_';
3476             }
3477         }
3478     }
3480   return unless %sections;
3482   my @unsorted_deps;
3484   # Build section independent variables.
3485   my $have_notrans = %notrans_vars;
3486   my @notrans_list = sort keys %notrans_vars;
3487   my $have_trans = %trans_vars;
3488   my @trans_list = sort keys %trans_vars;
3490   # Now for each section, generate an install and uninstall rule.
3491   # Sort sections so output is deterministic.
3492   foreach my $section (sort keys %sections)
3493     {
3494       # Build section dependent variables.
3495       my $notrans_mans = $have_notrans || exists $notrans_sections{$section};
3496       my $trans_mans = $have_trans || exists $trans_sections{$section};
3497       my (%notrans_this_sect, %trans_this_sect);
3498       my $expr = 'man' . $section . '_MANS';
3499       foreach my $varname (keys %notrans_sect_vars)
3500         {
3501           if ($varname =~ /$expr/)
3502             {
3503               $notrans_this_sect{$varname} = 1;
3504             }
3505         }
3506       foreach my $varname (keys %trans_sect_vars)
3507         {
3508           if ($varname =~ /$expr/)
3509             {
3510               $trans_this_sect{$varname} = 1;
3511             }
3512         }
3513       my @notrans_sect_list = sort keys %notrans_this_sect;
3514       my @trans_sect_list = sort keys %trans_this_sect;
3515       @unsorted_deps = (keys %notrans_vars, keys %trans_vars,
3516                         keys %notrans_this_sect, keys %trans_this_sect);
3517       my @deps = sort @unsorted_deps;
3518       $output_rules .= &file_contents ('mans',
3519                                        new Automake::Location,
3520                                        SECTION           => $section,
3521                                        DEPS              => "@deps",
3522                                        NOTRANS_MANS      => $notrans_mans,
3523                                        NOTRANS_SECT_LIST => "@notrans_sect_list",
3524                                        HAVE_NOTRANS      => $have_notrans,
3525                                        NOTRANS_LIST      => "@notrans_list",
3526                                        TRANS_MANS        => $trans_mans,
3527                                        TRANS_SECT_LIST   => "@trans_sect_list",
3528                                        HAVE_TRANS        => $have_trans,
3529                                        TRANS_LIST        => "@trans_list");
3530     }
3532   @unsorted_deps  = (keys %notrans_vars, keys %trans_vars,
3533                      keys %notrans_sect_vars, keys %trans_sect_vars);
3534   my @mans = sort @unsorted_deps;
3535   $output_vars .= file_contents ('mans-vars',
3536                                  new Automake::Location,
3537                                  MANS => "@mans");
3539   push (@all, '$(MANS)')
3540     unless option 'no-installman';
3543 # Handle DATA variables.
3544 sub handle_data
3546     &am_install_var ('-noextra', '-candist', 'data', 'DATA',
3547                      'data', 'dataroot', 'dvi', 'html', 'pdf', 'ps',
3548                      'sysconf', 'sharedstate', 'localstate',
3549                      'pkgdata', 'lisp', 'noinst', 'check');
3552 # Handle TAGS.
3553 sub handle_tags
3555     my @tag_deps = ();
3556     my @ctag_deps = ();
3557     if (var ('SUBDIRS'))
3558     {
3559         $output_rules .= ("tags-recursive:\n"
3560                           . "\tlist=\'\$(SUBDIRS)\'; for subdir in \$\$list; do \\\n"
3561                           # Never fail here if a subdir fails; it
3562                           # isn't important.
3563                           . "\t  test \"\$\$subdir\" = . || (\$(am__cd) \$\$subdir"
3564                           . " && \$(MAKE) \$(AM_MAKEFLAGS) tags); \\\n"
3565                           . "\tdone\n");
3566         push (@tag_deps, 'tags-recursive');
3567         &depend ('.PHONY', 'tags-recursive');
3569         $output_rules .= ("ctags-recursive:\n"
3570                           . "\tlist=\'\$(SUBDIRS)\'; for subdir in \$\$list; do \\\n"
3571                           # Never fail here if a subdir fails; it
3572                           # isn't important.
3573                           . "\t  test \"\$\$subdir\" = . || (\$(am__cd) \$\$subdir"
3574                           . " && \$(MAKE) \$(AM_MAKEFLAGS) ctags); \\\n"
3575                           . "\tdone\n");
3576         push (@ctag_deps, 'ctags-recursive');
3577         &depend ('.PHONY', 'ctags-recursive');
3578     }
3580     if (&saw_sources_p (1)
3581         || var ('ETAGS_ARGS')
3582         || @tag_deps)
3583     {
3584         my @config;
3585         foreach my $spec (@config_headers)
3586         {
3587             my ($out, @ins) = split_config_file_spec ($spec);
3588             foreach my $in (@ins)
3589               {
3590                 # If the config header source is in this directory,
3591                 # require it.
3592                 push @config, basename ($in)
3593                   if $relative_dir eq dirname ($in);
3594               }
3595         }
3596         $output_rules .= &file_contents ('tags',
3597                                          new Automake::Location,
3598                                          CONFIG    => "@config",
3599                                          TAGSDIRS  => "@tag_deps",
3600                                          CTAGSDIRS => "@ctag_deps");
3602         set_seen 'TAGS_DEPENDENCIES';
3603     }
3604     elsif (reject_var ('TAGS_DEPENDENCIES',
3605                        "doesn't make sense to define `TAGS_DEPENDENCIES'"
3606                        . "without\nsources or `ETAGS_ARGS'"))
3607     {
3608     }
3609     else
3610     {
3611         # Every Makefile must define some sort of TAGS rule.
3612         # Otherwise, it would be possible for a top-level "make TAGS"
3613         # to fail because some subdirectory failed.
3614         $output_rules .= "tags: TAGS\nTAGS:\n\n";
3615         # Ditto ctags.
3616         $output_rules .= "ctags: CTAGS\nCTAGS:\n\n";
3617     }
3620 # Handle multilib support.
3621 sub handle_multilib
3623   if ($seen_multilib && $relative_dir eq '.')
3624     {
3625       $output_rules .= &file_contents ('multilib', new Automake::Location);
3626       push (@all, 'all-multi');
3627     }
3631 # user_phony_rule ($NAME)
3632 # -----------------------
3633 # Return false if rule $NAME does not exist.  Otherwise,
3634 # declare it as phony, complete its definition (in case it is
3635 # conditional), and return its Automake::Rule instance.
3636 sub user_phony_rule ($)
3638   my ($name) = @_;
3639   my $rule = rule $name;
3640   if ($rule)
3641     {
3642       depend ('.PHONY', $name);
3643       # Define $NAME in all condition where it is not already defined,
3644       # so that it is always OK to depend on $NAME.
3645       for my $c ($rule->not_always_defined_in_cond (TRUE)->conds)
3646         {
3647           Automake::Rule::define ($name, 'internal', RULE_AUTOMAKE,
3648                                   $c, INTERNAL);
3649           $output_rules .= $c->subst_string . "$name:\n";
3650         }
3651     }
3652   return $rule;
3656 # $BOOLEAN
3657 # &for_dist_common ($A, $B)
3658 # -------------------------
3659 # Subroutine for &handle_dist: sort files to dist.
3661 # We put README first because it then becomes easier to make a
3662 # Usenet-compliant shar file (in these, README must be first).
3664 # FIXME: do more ordering of files here.
3665 sub for_dist_common
3667     return 0
3668         if $a eq $b;
3669     return -1
3670         if $a eq 'README';
3671     return 1
3672         if $b eq 'README';
3673     return $a cmp $b;
3676 # handle_dist
3677 # -----------
3678 # Handle 'dist' target.
3679 sub handle_dist ()
3681   # Substitutions for distdir.am
3682   my %transform;
3684   # Define DIST_SUBDIRS.  This must always be done, regardless of the
3685   # no-dist setting: target like `distclean' or `maintainer-clean' use it.
3686   my $subdirs = var ('SUBDIRS');
3687   if ($subdirs)
3688     {
3689       # If SUBDIRS is conditionally defined, then set DIST_SUBDIRS
3690       # to all possible directories, and use it.  If DIST_SUBDIRS is
3691       # defined, just use it.
3693       # Note that we check DIST_SUBDIRS first on purpose, so that
3694       # we don't call has_conditional_contents for now reason.
3695       # (In the past one project used so many conditional subdirectories
3696       # that calling has_conditional_contents on SUBDIRS caused
3697       # automake to grow to 150Mb -- this should not happen with
3698       # the current implementation of has_conditional_contents,
3699       # but it's more efficient to avoid the call anyway.)
3700       if (var ('DIST_SUBDIRS'))
3701         {
3702         }
3703       elsif ($subdirs->has_conditional_contents)
3704         {
3705           define_pretty_variable
3706             ('DIST_SUBDIRS', TRUE, INTERNAL,
3707              uniq ($subdirs->value_as_list_recursive));
3708         }
3709       else
3710         {
3711           # We always define this because that is what `distclean'
3712           # wants.
3713           define_pretty_variable ('DIST_SUBDIRS', TRUE, INTERNAL,
3714                                   '$(SUBDIRS)');
3715         }
3716     }
3718   # The remaining definitions are only required when a dist target is used.
3719   return if option 'no-dist';
3721   # At least one of the archive formats must be enabled.
3722   if ($relative_dir eq '.')
3723     {
3724       my $archive_defined = option 'no-dist-gzip' ? 0 : 1;
3725       $archive_defined ||=
3726         grep { option "dist-$_" } qw(shar zip tarZ bzip2 lzma xz);
3727       error (option 'no-dist-gzip',
3728              "no-dist-gzip specified but no dist-* specified, "
3729              . "at least one archive format must be enabled")
3730         unless $archive_defined;
3731     }
3733   # Look for common files that should be included in distribution.
3734   # If the aux dir is set, and it does not have a Makefile.am, then
3735   # we check for these files there as well.
3736   my $check_aux = 0;
3737   if ($relative_dir eq '.'
3738       && $config_aux_dir_set_in_configure_ac)
3739     {
3740       if (! &is_make_dir ($config_aux_dir))
3741         {
3742           $check_aux = 1;
3743         }
3744     }
3745   foreach my $cfile (@common_files)
3746     {
3747       if (dir_has_case_matching_file ($relative_dir, $cfile)
3748           # The file might be absent, but if it can be built it's ok.
3749           || rule $cfile)
3750         {
3751           &push_dist_common ($cfile);
3752         }
3754       # Don't use `elsif' here because a file might meaningfully
3755       # appear in both directories.
3756       if ($check_aux && dir_has_case_matching_file ($config_aux_dir, $cfile))
3757         {
3758           &push_dist_common ("$config_aux_dir/$cfile")
3759         }
3760     }
3762   # We might copy elements from $configure_dist_common to
3763   # %dist_common if we think we need to.  If the file appears in our
3764   # directory, we would have discovered it already, so we don't
3765   # check that.  But if the file is in a subdir without a Makefile,
3766   # we want to distribute it here if we are doing `.'.  Ugly!
3767   if ($relative_dir eq '.')
3768     {
3769       foreach my $file (split (' ' , $configure_dist_common))
3770         {
3771           push_dist_common ($file)
3772             unless is_make_dir (dirname ($file));
3773         }
3774     }
3776   # Files to distributed.  Don't use ->value_as_list_recursive
3777   # as it recursively expands `$(dist_pkgdata_DATA)' etc.
3778   my @dist_common = split (' ', rvar ('DIST_COMMON')->variable_value);
3779   @dist_common = uniq (sort for_dist_common (@dist_common));
3780   variable_delete 'DIST_COMMON';
3781   define_pretty_variable ('DIST_COMMON', TRUE, INTERNAL, @dist_common);
3783   # Now that we've processed DIST_COMMON, disallow further attempts
3784   # to set it.
3785   $handle_dist_run = 1;
3787   # Scan EXTRA_DIST to see if we need to distribute anything from a
3788   # subdir.  If so, add it to the list.  I didn't want to do this
3789   # originally, but there were so many requests that I finally
3790   # relented.
3791   my $extra_dist = var ('EXTRA_DIST');
3793   $transform{'DISTCHECK-HOOK'} = !! rule 'distcheck-hook';
3794   $transform{'GETTEXT'} = $seen_gettext && !$seen_gettext_external;
3796   # If the target `dist-hook' exists, make sure it is run.  This
3797   # allows users to do random weird things to the distribution
3798   # before it is packaged up.
3799   push (@dist_targets, 'dist-hook')
3800     if user_phony_rule 'dist-hook';
3801   $transform{'DIST-TARGETS'} = join (' ', @dist_targets);
3803   my $flm = option ('filename-length-max');
3804   my $filename_filter = $flm ? '.' x $flm->[1] : '';
3806   $output_rules .= &file_contents ('distdir',
3807                                    new Automake::Location,
3808                                    %transform,
3809                                    FILENAME_FILTER => $filename_filter);
3813 # check_directory ($NAME, $WHERE)
3814 # -------------------------------
3815 # Ensure $NAME is a directory, and that it uses a sane name.
3816 # Use $WHERE as a location in the diagnostic, if any.
3817 sub check_directory ($$)
3819   my ($dir, $where) = @_;
3821   error $where, "required directory $relative_dir/$dir does not exist"
3822     unless -d "$relative_dir/$dir";
3824   # If an `obj/' directory exists, BSD make will enter it before
3825   # reading `Makefile'.  Hence the `Makefile' in the current directory
3826   # will not be read.
3827   #
3828   #  % cat Makefile
3829   #  all:
3830   #          echo Hello
3831   #  % cat obj/Makefile
3832   #  all:
3833   #          echo World
3834   #  % make      # GNU make
3835   #  echo Hello
3836   #  Hello
3837   #  % pmake     # BSD make
3838   #  echo World
3839   #  World
3840   msg ('portability', $where,
3841        "naming a subdirectory `obj' causes troubles with BSD make")
3842     if $dir eq 'obj';
3844   # `aux' is probably the most important of the following forbidden name,
3845   # since it's tempting to use it as an AC_CONFIG_AUX_DIR.
3846   msg ('portability', $where,
3847        "name `$dir' is reserved on W32 and DOS platforms")
3848     if grep (/^\Q$dir\E$/i, qw/aux lpt1 lpt2 lpt3 com1 com2 com3 com4 con prn/);
3851 # check_directories_in_var ($VARIABLE)
3852 # ------------------------------------
3853 # Recursively check all items in variables $VARIABLE as directories
3854 sub check_directories_in_var ($)
3856   my ($var) = @_;
3857   $var->traverse_recursively
3858     (sub
3859      {
3860        my ($var, $val, $cond, $full_cond) = @_;
3861        check_directory ($val, $var->rdef ($cond)->location);
3862        return ();
3863      },
3864      undef,
3865      skip_ac_subst => 1);
3868 # &handle_subdirs ()
3869 # ------------------
3870 # Handle subdirectories.
3871 sub handle_subdirs ()
3873   my $subdirs = var ('SUBDIRS');
3874   return
3875     unless $subdirs;
3877   check_directories_in_var $subdirs;
3879   my $dsubdirs = var ('DIST_SUBDIRS');
3880   check_directories_in_var $dsubdirs
3881     if $dsubdirs;
3883   $output_rules .= &file_contents ('subdirs', new Automake::Location);
3884   rvar ('RECURSIVE_TARGETS')->rdef (TRUE)->{'pretty'} = VAR_SORTED; # Gross!
3888 # ($REGEN, @DEPENDENCIES)
3889 # &scan_aclocal_m4
3890 # ----------------
3891 # If aclocal.m4 creation is automated, return the list of its dependencies.
3892 sub scan_aclocal_m4 ()
3894   my $regen_aclocal = 0;
3896   set_seen 'CONFIG_STATUS_DEPENDENCIES';
3897   set_seen 'CONFIGURE_DEPENDENCIES';
3899   if (-f 'aclocal.m4')
3900     {
3901       &define_variable ("ACLOCAL_M4", '$(top_srcdir)/aclocal.m4', INTERNAL);
3903       my $aclocal = new Automake::XFile "< aclocal.m4";
3904       my $line = $aclocal->getline;
3905       $regen_aclocal = $line =~ 'generated automatically by aclocal';
3906     }
3908   my @ac_deps = ();
3910   if (set_seen ('ACLOCAL_M4_SOURCES'))
3911     {
3912       push (@ac_deps, '$(ACLOCAL_M4_SOURCES)');
3913       msg_var ('obsolete', 'ACLOCAL_M4_SOURCES',
3914                "`ACLOCAL_M4_SOURCES' is obsolete.\n"
3915                . "It should be safe to simply remove it.");
3916     }
3918   # Note that it might be possible that aclocal.m4 doesn't exist but
3919   # should be auto-generated.  This case probably isn't very
3920   # important.
3922   return ($regen_aclocal, @ac_deps);
3926 # Helper function for substitute_ac_subst_variables.
3927 sub substitute_ac_subst_variables_worker($)
3929   my ($token) = @_;
3930   return "\@$token\@" if var $token;
3931   return "\${$token\}";
3934 # substitute_ac_subst_variables ($TEXT)
3935 # -------------------------------------
3936 # Replace any occurrence of ${FOO} in $TEXT by @FOO@ if FOO is an AC_SUBST
3937 # variable.
3938 sub substitute_ac_subst_variables ($)
3940   my ($text) = @_;
3941   $text =~ s/\${([^ \t=:+{}]+)}/&substitute_ac_subst_variables_worker ($1)/ge;
3942   return $text;
3945 # @DEPENDENCIES
3946 # &prepend_srcdir (@INPUTS)
3947 # -------------------------
3948 # Prepend $(srcdir) or $(top_srcdir) to all @INPUTS.  The idea is that
3949 # if an input file has a directory part the same as the current
3950 # directory, then the directory part is simply replaced by $(srcdir).
3951 # But if the directory part is different, then $(top_srcdir) is
3952 # prepended.
3953 sub prepend_srcdir (@)
3955   my (@inputs) = @_;
3956   my @newinputs;
3958   foreach my $single (@inputs)
3959     {
3960       if (dirname ($single) eq $relative_dir)
3961         {
3962           push (@newinputs, '$(srcdir)/' . basename ($single));
3963         }
3964       else
3965         {
3966           push (@newinputs, '$(top_srcdir)/' . $single);
3967         }
3968     }
3969   return @newinputs;
3972 # @DEPENDENCIES
3973 # rewrite_inputs_into_dependencies ($OUTPUT, @INPUTS)
3974 # ---------------------------------------------------
3975 # Compute a list of dependencies appropriate for the rebuild
3976 # rule of
3977 #   AC_CONFIG_FILES($OUTPUT:$INPUT[0]:$INPUTS[1]:...)
3978 # Also distribute $INPUTs which are not built by another AC_CONFIG_FOOS.
3979 sub rewrite_inputs_into_dependencies ($@)
3981   my ($file, @inputs) = @_;
3982   my @res = ();
3984   for my $i (@inputs)
3985     {
3986       # We cannot create dependencies on shell variables.
3987       next if (substitute_ac_subst_variables $i) =~ /\$/;
3989       if (exists $ac_config_files_location{$i} && $i ne $file)
3990         {
3991           my $di = dirname $i;
3992           if ($di eq $relative_dir)
3993             {
3994               $i = basename $i;
3995             }
3996           # In the top-level Makefile we do not use $(top_builddir), because
3997           # we are already there, and since the targets are built without
3998           # a $(top_builddir), it helps BSD Make to match them with
3999           # dependencies.
4000           elsif ($relative_dir ne '.')
4001             {
4002               $i = '$(top_builddir)/' . $i;
4003             }
4004         }
4005       else
4006         {
4007           msg ('error', $ac_config_files_location{$file},
4008                "required file `$i' not found")
4009             unless $i =~ /\$/ || exists $output_files{$i} || -f $i;
4010           ($i) = prepend_srcdir ($i);
4011           push_dist_common ($i);
4012         }
4013       push @res, $i;
4014     }
4015   return @res;
4020 # &handle_configure ($MAKEFILE_AM, $MAKEFILE_IN, $MAKEFILE, @INPUTS)
4021 # ------------------------------------------------------------------
4022 # Handle remaking and configure stuff.
4023 # We need the name of the input file, to do proper remaking rules.
4024 sub handle_configure ($$$@)
4026   my ($makefile_am, $makefile_in, $makefile, @inputs) = @_;
4028   prog_error 'empty @inputs'
4029     unless @inputs;
4031   my ($rel_makefile_am, $rel_makefile_in) = prepend_srcdir ($makefile_am,
4032                                                             $makefile_in);
4033   my $rel_makefile = basename $makefile;
4035   my $colon_infile = ':' . join (':', @inputs);
4036   $colon_infile = '' if $colon_infile eq ":$makefile.in";
4037   my @rewritten = rewrite_inputs_into_dependencies ($makefile, @inputs);
4038   my ($regen_aclocal_m4, @aclocal_m4_deps) = scan_aclocal_m4;
4039   define_pretty_variable ('am__aclocal_m4_deps', TRUE, INTERNAL,
4040                           @configure_deps, @aclocal_m4_deps,
4041                           '$(top_srcdir)/' . $configure_ac);
4042   my @configuredeps = ('$(am__aclocal_m4_deps)', '$(CONFIGURE_DEPENDENCIES)');
4043   push @configuredeps, '$(ACLOCAL_M4)' if -f 'aclocal.m4';
4044   define_pretty_variable ('am__configure_deps', TRUE, INTERNAL,
4045                           @configuredeps);
4047   $output_rules .= file_contents
4048     ('configure',
4049      new Automake::Location,
4050      MAKEFILE              => $rel_makefile,
4051      'MAKEFILE-DEPS'       => "@rewritten",
4052      'CONFIG-MAKEFILE'     => ($relative_dir eq '.') ? '$@' : '$(subdir)/$@',
4053      'MAKEFILE-IN'         => $rel_makefile_in,
4054      'MAKEFILE-IN-DEPS'    => "@include_stack",
4055      'MAKEFILE-AM'         => $rel_makefile_am,
4056      STRICTNESS            => global_option 'cygnus'
4057                                 ? 'cygnus' : $strictness_name,
4058      'USE-DEPS'            => global_option 'no-dependencies'
4059                                 ? ' --ignore-deps' : '',
4060      'MAKEFILE-AM-SOURCES' => "$makefile$colon_infile",
4061      'REGEN-ACLOCAL-M4'    => $regen_aclocal_m4);
4063   if ($relative_dir eq '.')
4064     {
4065       &push_dist_common ('acconfig.h')
4066         if -f 'acconfig.h';
4067     }
4069   # If we have a configure header, require it.
4070   my $hdr_index = 0;
4071   my @distclean_config;
4072   foreach my $spec (@config_headers)
4073     {
4074       $hdr_index += 1;
4075       # $CONFIG_H_PATH: config.h from top level.
4076       my ($config_h_path, @ins) = split_config_file_spec ($spec);
4077       my $config_h_dir = dirname ($config_h_path);
4079       # If the header is in the current directory we want to build
4080       # the header here.  Otherwise, if we're at the topmost
4081       # directory and the header's directory doesn't have a
4082       # Makefile, then we also want to build the header.
4083       if ($relative_dir eq $config_h_dir
4084           || ($relative_dir eq '.' && ! &is_make_dir ($config_h_dir)))
4085         {
4086           my ($cn_sans_dir, $stamp_dir);
4087           if ($relative_dir eq $config_h_dir)
4088             {
4089               $cn_sans_dir = basename ($config_h_path);
4090               $stamp_dir = '';
4091             }
4092           else
4093             {
4094               $cn_sans_dir = $config_h_path;
4095               if ($config_h_dir eq '.')
4096                 {
4097                   $stamp_dir = '';
4098                 }
4099               else
4100                 {
4101                   $stamp_dir = $config_h_dir . '/';
4102                 }
4103             }
4105           # This will also distribute all inputs.
4106           @ins = rewrite_inputs_into_dependencies ($config_h_path, @ins);
4108           # Cannot define rebuild rules for filenames with shell variables.
4109           next if (substitute_ac_subst_variables $config_h_path) =~ /\$/;
4111           # Header defined in this directory.
4112           my @files;
4113           if (-f $config_h_path . '.top')
4114             {
4115               push (@files, "$cn_sans_dir.top");
4116             }
4117           if (-f $config_h_path . '.bot')
4118             {
4119               push (@files, "$cn_sans_dir.bot");
4120             }
4122           push_dist_common (@files);
4124           # For now, acconfig.h can only appear in the top srcdir.
4125           if (-f 'acconfig.h')
4126             {
4127               push (@files, '$(top_srcdir)/acconfig.h');
4128             }
4130           my $stamp = "${stamp_dir}stamp-h${hdr_index}";
4131           $output_rules .=
4132             file_contents ('remake-hdr',
4133                            new Automake::Location,
4134                            FILES            => "@files",
4135                            CONFIG_H         => $cn_sans_dir,
4136                            CONFIG_HIN       => $ins[0],
4137                            CONFIG_H_DEPS    => "@ins",
4138                            CONFIG_H_PATH    => $config_h_path,
4139                            STAMP            => "$stamp");
4141           push @distclean_config, $cn_sans_dir, $stamp;
4142         }
4143     }
4145   $output_rules .= file_contents ('clean-hdr',
4146                                   new Automake::Location,
4147                                   FILES => "@distclean_config")
4148     if @distclean_config;
4150   # Distribute and define mkinstalldirs only if it is already present
4151   # in the package, for backward compatibility (some people may still
4152   # use $(mkinstalldirs)).
4153   my $mkidpath = "$config_aux_dir/mkinstalldirs";
4154   if (-f $mkidpath)
4155     {
4156       # Use require_file so that any existing script gets updated
4157       # by --force-missing.
4158       require_conf_file ($mkidpath, FOREIGN, 'mkinstalldirs');
4159       define_variable ('mkinstalldirs',
4160                        "\$(SHELL) $am_config_aux_dir/mkinstalldirs", INTERNAL);
4161     }
4162   else
4163     {
4164       # Use $(install_sh), not $(MKDIR_P) because the latter requires
4165       # at least one argument, and $(mkinstalldirs) used to work
4166       # even without arguments (e.g. $(mkinstalldirs) $(conditional_dir)).
4167       define_variable ('mkinstalldirs', '$(install_sh) -d', INTERNAL);
4168     }
4170   reject_var ('CONFIG_HEADER',
4171               "`CONFIG_HEADER' is an anachronism; now determined "
4172               . "automatically\nfrom `$configure_ac'");
4174   my @config_h;
4175   foreach my $spec (@config_headers)
4176     {
4177       my ($out, @ins) = split_config_file_spec ($spec);
4178       # Generate CONFIG_HEADER define.
4179       if ($relative_dir eq dirname ($out))
4180         {
4181           push @config_h, basename ($out);
4182         }
4183       else
4184         {
4185           push @config_h, "\$(top_builddir)/$out";
4186         }
4187     }
4188   define_variable ("CONFIG_HEADER", "@config_h", INTERNAL)
4189     if @config_h;
4191   # Now look for other files in this directory which must be remade
4192   # by config.status, and generate rules for them.
4193   my @actual_other_files = ();
4194   # These get cleaned only in a VPATH build.
4195   my @actual_other_vpath_files = ();
4196   foreach my $lfile (@other_input_files)
4197     {
4198       my $file;
4199       my @inputs;
4200       if ($lfile =~ /^([^:]*):(.*)$/)
4201         {
4202           # This is the ":" syntax of AC_OUTPUT.
4203           $file = $1;
4204           @inputs = split (':', $2);
4205         }
4206       else
4207         {
4208           # Normal usage.
4209           $file = $lfile;
4210           @inputs = $file . '.in';
4211         }
4213       # Automake files should not be stored in here, but in %MAKE_LIST.
4214       prog_error ("$lfile in \@other_input_files\n"
4215                   . "\@other_input_files = (@other_input_files)")
4216         if -f $file . '.am';
4218       my $local = basename ($file);
4220       # We skip files that aren't in this directory.  However, if
4221       # the file's directory does not have a Makefile, and we are
4222       # currently doing `.', then we create a rule to rebuild the
4223       # file in the subdir.
4224       my $fd = dirname ($file);
4225       if ($fd ne $relative_dir)
4226         {
4227           if ($relative_dir eq '.' && ! &is_make_dir ($fd))
4228             {
4229               $local = $file;
4230             }
4231           else
4232             {
4233               next;
4234             }
4235         }
4237       my @rewritten_inputs = rewrite_inputs_into_dependencies ($file, @inputs);
4239       # Cannot output rules for shell variables.
4240       next if (substitute_ac_subst_variables $local) =~ /\$/;
4242       my $condstr = '';
4243       my $cond = $ac_config_files_condition{$lfile};
4244       if (defined $cond)
4245         {
4246           $condstr = $cond->subst_string;
4247           Automake::Rule::define ($local, $configure_ac, RULE_AUTOMAKE, $cond,
4248                                   $ac_config_files_location{$file});
4249         }
4250       $output_rules .= ($condstr . $local . ': '
4251                         . '$(top_builddir)/config.status '
4252                         . "@rewritten_inputs\n"
4253                         . $condstr . "\t"
4254                         . 'cd $(top_builddir) && '
4255                         . '$(SHELL) ./config.status '
4256                         . ($relative_dir eq '.' ? '' : '$(subdir)/')
4257                         . '$@'
4258                         . "\n");
4259       push (@actual_other_files, $local);
4260     }
4262   # For links we should clean destinations and distribute sources.
4263   foreach my $spec (@config_links)
4264     {
4265       my ($link, $file) = split /:/, $spec;
4266       # Some people do AC_CONFIG_LINKS($computed).  We only handle
4267       # the DEST:SRC form.
4268       next unless $file;
4269       my $where = $ac_config_files_location{$link};
4271       # Skip destinations that contain shell variables.
4272       if ((substitute_ac_subst_variables $link) !~ /\$/)
4273         {
4274           # We skip links that aren't in this directory.  However, if
4275           # the link's directory does not have a Makefile, and we are
4276           # currently doing `.', then we add the link to CONFIG_CLEAN_FILES
4277           # in `.'s Makefile.in.
4278           my $local = basename ($link);
4279           my $fd = dirname ($link);
4280           if ($fd ne $relative_dir)
4281             {
4282               if ($relative_dir eq '.' && ! &is_make_dir ($fd))
4283                 {
4284                   $local = $link;
4285                 }
4286               else
4287                 {
4288                   $local = undef;
4289                 }
4290             }
4291           if ($file ne $link)
4292             {
4293               push @actual_other_files, $local if $local;
4294             }
4295           else
4296             {
4297               push @actual_other_vpath_files, $local if $local;
4298             }
4299         }
4301       # Do not process sources that contain shell variables.
4302       if ((substitute_ac_subst_variables $file) !~ /\$/)
4303         {
4304           my $fd = dirname ($file);
4306           # We distribute files that are in this directory.
4307           # At the top-level (`.') we also distribute files whose
4308           # directory does not have a Makefile.
4309           if (($fd eq $relative_dir)
4310               || ($relative_dir eq '.' && ! &is_make_dir ($fd)))
4311             {
4312               # The following will distribute $file as a side-effect when
4313               # it is appropriate (i.e., when $file is not already an output).
4314               # We do not need the result, just the side-effect.
4315               rewrite_inputs_into_dependencies ($link, $file);
4316             }
4317         }
4318     }
4320   # These files get removed by "make distclean".
4321   define_pretty_variable ('CONFIG_CLEAN_FILES', TRUE, INTERNAL,
4322                           @actual_other_files);
4323   define_pretty_variable ('CONFIG_CLEAN_VPATH_FILES', TRUE, INTERNAL,
4324                           @actual_other_vpath_files);
4327 # Handle C headers.
4328 sub handle_headers
4330     my @r = &am_install_var ('-defaultdist', 'header', 'HEADERS', 'include',
4331                              'oldinclude', 'pkginclude',
4332                              'noinst', 'check');
4333     foreach (@r)
4334     {
4335       next unless $_->[1] =~ /\..*$/;
4336       &saw_extension ($&);
4337     }
4340 sub handle_gettext
4342   return if ! $seen_gettext || $relative_dir ne '.';
4344   my $subdirs = var 'SUBDIRS';
4346   if (! $subdirs)
4347     {
4348       err_ac "AM_GNU_GETTEXT used but SUBDIRS not defined";
4349       return;
4350     }
4352   # Perform some sanity checks to help users get the right setup.
4353   # We disable these tests when po/ doesn't exist in order not to disallow
4354   # unusual gettext setups.
4355   #
4356   # Bruno Haible:
4357   # | The idea is:
4358   # |
4359   # |  1) If a package doesn't have a directory po/ at top level, it
4360   # |     will likely have multiple po/ directories in subpackages.
4361   # |
4362   # |  2) It is useful to warn for the absence of intl/ if AM_GNU_GETTEXT
4363   # |     is used without 'external'. It is also useful to warn for the
4364   # |     presence of intl/ if AM_GNU_GETTEXT([external]) is used. Both
4365   # |     warnings apply only to the usual layout of packages, therefore
4366   # |     they should both be disabled if no po/ directory is found at
4367   # |     top level.
4369   if (-d 'po')
4370     {
4371       my @subdirs = $subdirs->value_as_list_recursive;
4373       msg_var ('syntax', $subdirs,
4374                "AM_GNU_GETTEXT used but `po' not in SUBDIRS")
4375         if ! grep ($_ eq 'po', @subdirs);
4377       # intl/ is not required when AM_GNU_GETTEXT is called with the
4378       # `external' option and AM_GNU_GETTEXT_INTL_SUBDIR is not called.
4379       msg_var ('syntax', $subdirs,
4380                "AM_GNU_GETTEXT used but `intl' not in SUBDIRS")
4381         if (! ($seen_gettext_external && ! $seen_gettext_intl)
4382             && ! grep ($_ eq 'intl', @subdirs));
4384       # intl/ should not be used with AM_GNU_GETTEXT([external]), except
4385       # if AM_GNU_GETTEXT_INTL_SUBDIR is called.
4386       msg_var ('syntax', $subdirs,
4387                "`intl' should not be in SUBDIRS when "
4388                . "AM_GNU_GETTEXT([external]) is used")
4389         if ($seen_gettext_external && ! $seen_gettext_intl
4390             && grep ($_ eq 'intl', @subdirs));
4391     }
4393   require_file ($ac_gettext_location, GNU, 'ABOUT-NLS');
4396 # Handle footer elements.
4397 sub handle_footer
4399     reject_rule ('.SUFFIXES',
4400                  "use variable `SUFFIXES', not target `.SUFFIXES'");
4402     # Note: AIX 4.1 /bin/make will fail if any suffix rule appears
4403     # before .SUFFIXES.  So we make sure that .SUFFIXES appears before
4404     # anything else, by sticking it right after the default: target.
4405     $output_header .= ".SUFFIXES:\n";
4406     my $suffixes = var 'SUFFIXES';
4407     my @suffixes = Automake::Rule::suffixes;
4408     if (@suffixes || $suffixes)
4409     {
4410         # Make sure SUFFIXES has unique elements.  Sort them to ensure
4411         # the output remains consistent.  However, $(SUFFIXES) is
4412         # always at the start of the list, unsorted.  This is done
4413         # because make will choose rules depending on the ordering of
4414         # suffixes, and this lets the user have some control.  Push
4415         # actual suffixes, and not $(SUFFIXES).  Some versions of make
4416         # do not like variable substitutions on the .SUFFIXES line.
4417         my @user_suffixes = ($suffixes
4418                              ? $suffixes->value_as_list_recursive : ());
4420         my %suffixes = map { $_ => 1 } @suffixes;
4421         delete @suffixes{@user_suffixes};
4423         $output_header .= (".SUFFIXES: "
4424                            . join (' ', @user_suffixes, sort keys %suffixes)
4425                            . "\n");
4426     }
4428     $output_trailer .= file_contents ('footer', new Automake::Location);
4432 # Generate `make install' rules.
4433 sub handle_install ()
4435   $output_rules .= &file_contents
4436     ('install',
4437      new Automake::Location,
4438      maybe_BUILT_SOURCES => (set_seen ('BUILT_SOURCES')
4439                              ? (" \$(BUILT_SOURCES)\n"
4440                                 . "\t\$(MAKE) \$(AM_MAKEFLAGS)")
4441                              : ''),
4442      'installdirs-local' => (user_phony_rule 'installdirs-local'
4443                              ? ' installdirs-local' : ''),
4444      am__installdirs => variable_value ('am__installdirs') || '');
4448 # Deal with all and all-am.
4449 sub handle_all ($)
4451     my ($makefile) = @_;
4453     # Output `all-am'.
4455     # Put this at the beginning for the sake of non-GNU makes.  This
4456     # is still wrong if these makes can run parallel jobs.  But it is
4457     # right enough.
4458     unshift (@all, basename ($makefile));
4460     foreach my $spec (@config_headers)
4461       {
4462         my ($out, @ins) = split_config_file_spec ($spec);
4463         push (@all, basename ($out))
4464           if dirname ($out) eq $relative_dir;
4465       }
4467     # Install `all' hooks.
4468     push (@all, "all-local")
4469       if user_phony_rule "all-local";
4471     &pretty_print_rule ("all-am:", "\t\t", @all);
4472     &depend ('.PHONY', 'all-am', 'all');
4475     # Output `all'.
4477     my @local_headers = ();
4478     push @local_headers, '$(BUILT_SOURCES)'
4479       if var ('BUILT_SOURCES');
4480     foreach my $spec (@config_headers)
4481       {
4482         my ($out, @ins) = split_config_file_spec ($spec);
4483         push @local_headers, basename ($out)
4484           if dirname ($out) eq $relative_dir;
4485       }
4487     if (@local_headers)
4488       {
4489         # We need to make sure config.h is built before we recurse.
4490         # We also want to make sure that built sources are built
4491         # before any ordinary `all' targets are run.  We can't do this
4492         # by changing the order of dependencies to the "all" because
4493         # that breaks when using parallel makes.  Instead we handle
4494         # things explicitly.
4495         $output_all .= ("all: @local_headers"
4496                         . "\n\t"
4497                         . '$(MAKE) $(AM_MAKEFLAGS) '
4498                         . (var ('SUBDIRS') ? 'all-recursive' : 'all-am')
4499                         . "\n\n");
4500       }
4501     else
4502       {
4503         $output_all .= "all: " . (var ('SUBDIRS')
4504                                   ? 'all-recursive' : 'all-am') . "\n\n";
4505       }
4509 # &do_check_merge_target ()
4510 # -------------------------
4511 # Handle check merge target specially.
4512 sub do_check_merge_target ()
4514   # Include user-defined local form of target.
4515   push @check_tests, 'check-local'
4516     if user_phony_rule 'check-local';
4518   # In --cygnus mode, check doesn't depend on all.
4519   if (option 'cygnus')
4520     {
4521       # Just run the local check rules.
4522       pretty_print_rule ('check-am:', "\t\t", @check);
4523     }
4524   else
4525     {
4526       # The check target must depend on the local equivalent of
4527       # `all', to ensure all the primary targets are built.  Then it
4528       # must build the local check rules.
4529       $output_rules .= "check-am: all-am\n";
4530       pretty_print_rule ("\t\$(MAKE) \$(AM_MAKEFLAGS)", "\t  ",
4531                          @check)
4532         if @check;
4533     }
4534   pretty_print_rule ("\t\$(MAKE) \$(AM_MAKEFLAGS)", "\t  ",
4535                      @check_tests)
4536     if @check_tests;
4538   depend '.PHONY', 'check', 'check-am';
4539   # Handle recursion.  We have to honor BUILT_SOURCES like for `all:'.
4540   $output_rules .= ("check: "
4541                     . (var ('BUILT_SOURCES')
4542                        ? "\$(BUILT_SOURCES)\n\t\$(MAKE) \$(AM_MAKEFLAGS) "
4543                        : '')
4544                     . (var ('SUBDIRS') ? 'check-recursive' : 'check-am')
4545                     . "\n");
4548 # handle_clean ($MAKEFILE)
4549 # ------------------------
4550 # Handle all 'clean' targets.
4551 sub handle_clean ($)
4553   my ($makefile) = @_;
4555   # Clean the files listed in user variables if they exist.
4556   $clean_files{'$(MOSTLYCLEANFILES)'} = MOSTLY_CLEAN
4557     if var ('MOSTLYCLEANFILES');
4558   $clean_files{'$(CLEANFILES)'} = CLEAN
4559     if var ('CLEANFILES');
4560   $clean_files{'$(DISTCLEANFILES)'} = DIST_CLEAN
4561     if var ('DISTCLEANFILES');
4562   $clean_files{'$(MAINTAINERCLEANFILES)'} = MAINTAINER_CLEAN
4563     if var ('MAINTAINERCLEANFILES');
4565   # Built sources are automatically removed by maintainer-clean.
4566   $clean_files{'$(BUILT_SOURCES)'} = MAINTAINER_CLEAN
4567     if var ('BUILT_SOURCES');
4569   # Compute a list of "rm"s to run for each target.
4570   my %rms = (MOSTLY_CLEAN, [],
4571              CLEAN, [],
4572              DIST_CLEAN, [],
4573              MAINTAINER_CLEAN, []);
4575   foreach my $file (keys %clean_files)
4576     {
4577       my $when = $clean_files{$file};
4578       prog_error 'invalid entry in %clean_files'
4579         unless exists $rms{$when};
4581       my $rm = "rm -f $file";
4582       # If file is a variable, make sure when don't call `rm -f' without args.
4583       $rm ="test -z \"$file\" || $rm"
4584         if ($file =~ /^\s*\$(\(.*\)|\{.*\})\s*$/);
4586       push @{$rms{$when}}, "\t-$rm\n";
4587     }
4589   $output_rules .= &file_contents
4590     ('clean',
4591      new Automake::Location,
4592      MOSTLYCLEAN_RMS      => join ('', sort @{$rms{&MOSTLY_CLEAN}}),
4593      CLEAN_RMS            => join ('', sort @{$rms{&CLEAN}}),
4594      DISTCLEAN_RMS        => join ('', sort @{$rms{&DIST_CLEAN}}),
4595      MAINTAINER_CLEAN_RMS => join ('', sort @{$rms{&MAINTAINER_CLEAN}}),
4596      MAKEFILE             => basename $makefile,
4597      );
4601 # &target_cmp ($A, $B)
4602 # --------------------
4603 # Subroutine for &handle_factored_dependencies to let `.PHONY' and
4604 # other `.TARGETS' be last.
4605 sub target_cmp
4607   return 0 if $a eq $b;
4609   my $a1 = substr ($a, 0, 1);
4610   my $b1 = substr ($b, 0, 1);
4611   if ($a1 ne $b1)
4612     {
4613       return -1 if $b1 eq '.';
4614       return 1 if $a1 eq '.';
4615     }
4616   return $a cmp $b;
4620 # &handle_factored_dependencies ()
4621 # --------------------------------
4622 # Handle everything related to gathered targets.
4623 sub handle_factored_dependencies
4625   # Reject bad hooks.
4626   foreach my $utarg ('uninstall-data-local', 'uninstall-data-hook',
4627                      'uninstall-exec-local', 'uninstall-exec-hook',
4628                      'uninstall-dvi-local',
4629                      'uninstall-html-local',
4630                      'uninstall-info-local',
4631                      'uninstall-pdf-local',
4632                      'uninstall-ps-local')
4633     {
4634       my $x = $utarg;
4635       $x =~ s/-.*-/-/;
4636       reject_rule ($utarg, "use `$x', not `$utarg'");
4637     }
4639   reject_rule ('install-local',
4640                "use `install-data-local' or `install-exec-local', "
4641                . "not `install-local'");
4643   reject_rule ('install-hook',
4644                "use `install-data-hook' or `install-exec-hook', "
4645                . "not `install-hook'");
4647   # Install the -local hooks.
4648   foreach (keys %dependencies)
4649     {
4650       # Hooks are installed on the -am targets.
4651       s/-am$// or next;
4652       depend ("$_-am", "$_-local")
4653         if user_phony_rule "$_-local";
4654     }
4656   # Install the -hook hooks.
4657   # FIXME: Why not be as liberal as we are with -local hooks?
4658   foreach ('install-exec', 'install-data', 'uninstall')
4659     {
4660       if (user_phony_rule "$_-hook")
4661         {
4662           depend ('.MAKE', "$_-am");
4663           register_action("$_-am",
4664                           ("\t\@\$(NORMAL_INSTALL)\n"
4665                            . "\t\$(MAKE) \$(AM_MAKEFLAGS) $_-hook"));
4666         }
4667     }
4669   # All the required targets are phony.
4670   depend ('.PHONY', keys %required_targets);
4672   # Actually output gathered targets.
4673   foreach (sort target_cmp keys %dependencies)
4674     {
4675       # If there is nothing about this guy, skip it.
4676       next
4677         unless (@{$dependencies{$_}}
4678                 || $actions{$_}
4679                 || $required_targets{$_});
4681       # Define gathered targets in undefined conditions.
4682       # FIXME: Right now we must handle .PHONY as an exception,
4683       # because people write things like
4684       #    .PHONY: myphonytarget
4685       # to append dependencies.  This would not work if Automake
4686       # refrained from defining its own .PHONY target as it does
4687       # with other overridden targets.
4688       # Likewise for `.MAKE'.
4689       my @undefined_conds = (TRUE,);
4690       if ($_ ne '.PHONY' && $_ ne '.MAKE')
4691         {
4692           @undefined_conds =
4693             Automake::Rule::define ($_, 'internal',
4694                                     RULE_AUTOMAKE, TRUE, INTERNAL);
4695         }
4696       my @uniq_deps = uniq (sort @{$dependencies{$_}});
4697       foreach my $cond (@undefined_conds)
4698         {
4699           my $condstr = $cond->subst_string;
4700           &pretty_print_rule ("$condstr$_:", "$condstr\t", @uniq_deps);
4701           $output_rules .= $actions{$_} if defined $actions{$_};
4702           $output_rules .= "\n";
4703         }
4704     }
4708 # &handle_tests_dejagnu ()
4709 # ------------------------
4710 sub handle_tests_dejagnu
4712     push (@check_tests, 'check-DEJAGNU');
4713     $output_rules .= file_contents ('dejagnu', new Automake::Location);
4717 # Handle TESTS variable and other checks.
4718 sub handle_tests
4720   if (option 'dejagnu')
4721     {
4722       &handle_tests_dejagnu;
4723     }
4724   else
4725     {
4726       foreach my $c ('DEJATOOL', 'RUNTEST', 'RUNTESTFLAGS')
4727         {
4728           reject_var ($c, "`$c' defined but `dejagnu' not in "
4729                       . "`AUTOMAKE_OPTIONS'");
4730         }
4731     }
4733   if (var ('TESTS'))
4734     {
4735       push (@check_tests, 'check-TESTS');
4736       $output_rules .= &file_contents ('check', new Automake::Location,
4737                                        COLOR => !! option 'color-tests');
4739       # Tests that are known programs should have $(EXEEXT) appended.
4740       # For matching purposes, we need to adjust XFAIL_TESTS as well.
4741       append_exeext { exists $known_programs{$_[0]} } 'TESTS';
4742       append_exeext { exists $known_programs{$_[0]} } 'XFAIL_TESTS'
4743         if (var ('XFAIL_TESTS'));
4744     }
4747 # Handle Emacs Lisp.
4748 sub handle_emacs_lisp
4750   my @elfiles = &am_install_var ('-candist', 'lisp', 'LISP',
4751                                  'lisp', 'noinst');
4753   return if ! @elfiles;
4755   define_pretty_variable ('am__ELFILES', TRUE, INTERNAL,
4756                           map { $_->[1] } @elfiles);
4757   define_pretty_variable ('am__ELCFILES', TRUE, INTERNAL,
4758                           '$(am__ELFILES:.el=.elc)');
4759   # This one can be overridden by users.
4760   define_pretty_variable ('ELCFILES', TRUE, INTERNAL, '$(LISP:.el=.elc)');
4762   push @all, '$(ELCFILES)';
4764   require_variables ($elfiles[0][0], "Emacs Lisp sources seen", TRUE,
4765                      'EMACS', 'lispdir');
4766   require_conf_file ($elfiles[0][0], FOREIGN, 'elisp-comp');
4767   &define_variable ('elisp_comp', "$am_config_aux_dir/elisp-comp", INTERNAL);
4770 # Handle Python
4771 sub handle_python
4773   my @pyfiles = &am_install_var ('-defaultdist', 'python', 'PYTHON',
4774                                  'noinst');
4775   return if ! @pyfiles;
4777   require_variables ($pyfiles[0][0], "Python sources seen", TRUE, 'PYTHON');
4778   require_conf_file ($pyfiles[0][0], FOREIGN, 'py-compile');
4779   &define_variable ('py_compile', "$am_config_aux_dir/py-compile", INTERNAL);
4782 # Handle Java.
4783 sub handle_java
4785     my @sourcelist = &am_install_var ('-candist',
4786                                       'java', 'JAVA',
4787                                       'java', 'noinst', 'check');
4788     return if ! @sourcelist;
4790     my @prefix = am_primary_prefixes ('JAVA', 1,
4791                                       'java', 'noinst', 'check');
4793     my $dir;
4794     foreach my $curs (@prefix)
4795       {
4796         next
4797           if $curs eq 'EXTRA';
4799         err_var "${curs}_JAVA", "multiple _JAVA primaries in use"
4800           if defined $dir;
4801         $dir = $curs;
4802       }
4805     push (@all, 'class' . $dir . '.stamp');
4809 # Handle some of the minor options.
4810 sub handle_minor_options
4812   if (option 'readme-alpha')
4813     {
4814       if ($relative_dir eq '.')
4815         {
4816           if ($package_version !~ /^$GNITS_VERSION_PATTERN$/)
4817             {
4818               msg ('error-gnits', $package_version_location,
4819                    "version `$package_version' doesn't follow " .
4820                    "Gnits standards");
4821             }
4822           if (defined $1 && -f 'README-alpha')
4823             {
4824               # This means we have an alpha release.  See
4825               # GNITS_VERSION_PATTERN for details.
4826               push_dist_common ('README-alpha');
4827             }
4828         }
4829     }
4832 ################################################################
4834 # ($OUTPUT, @INPUTS)
4835 # &split_config_file_spec ($SPEC)
4836 # -------------------------------
4837 # Decode the Autoconf syntax for config files (files, headers, links
4838 # etc.).
4839 sub split_config_file_spec ($)
4841   my ($spec) = @_;
4842   my ($output, @inputs) = split (/:/, $spec);
4844   push @inputs, "$output.in"
4845     unless @inputs;
4847   return ($output, @inputs);
4850 # $input
4851 # locate_am (@POSSIBLE_SOURCES)
4852 # -----------------------------
4853 # AC_CONFIG_FILES allow specifications such as Makefile:top.in:mid.in:bot.in
4854 # This functions returns the first *.in file for which a *.am exists.
4855 # It returns undef otherwise.
4856 sub locate_am (@)
4858   my (@rest) = @_;
4859   my $input;
4860   foreach my $file (@rest)
4861     {
4862       if (($file =~ /^(.*)\.in$/) && -f "$1.am")
4863         {
4864           $input = $file;
4865           last;
4866         }
4867     }
4868   return $input;
4871 my %make_list;
4873 # &scan_autoconf_config_files ($WHERE, $CONFIG-FILES)
4874 # ---------------------------------------------------
4875 # Study $CONFIG-FILES which is the first argument to AC_CONFIG_FILES
4876 # (or AC_OUTPUT).
4877 sub scan_autoconf_config_files ($$)
4879   my ($where, $config_files) = @_;
4881   # Look at potential Makefile.am's.
4882   foreach (split ' ', $config_files)
4883     {
4884       # Must skip empty string for Perl 4.
4885       next if $_ eq "\\" || $_ eq '';
4887       # Handle $local:$input syntax.
4888       my ($local, @rest) = split (/:/);
4889       @rest = ("$local.in",) unless @rest;
4890       msg ('portability', $where,
4891           "Omit leading `./' from config file names such as `$local',"
4892           . "\nas not all make implementations treat `file' and `./file' equally.")
4893         if ($local =~ /^\.\//);
4894       my $input = locate_am @rest;
4895       if ($input)
4896         {
4897           # We have a file that automake should generate.
4898           $make_list{$input} = join (':', ($local, @rest));
4899         }
4900       else
4901         {
4902           # We have a file that automake should cause to be
4903           # rebuilt, but shouldn't generate itself.
4904           push (@other_input_files, $_);
4905         }
4906       $ac_config_files_location{$local} = $where;
4907       $ac_config_files_condition{$local} =
4908         new Automake::Condition (@cond_stack)
4909           if (@cond_stack);
4910     }
4914 # &scan_autoconf_traces ($FILENAME)
4915 # ---------------------------------
4916 sub scan_autoconf_traces ($)
4918   my ($filename) = @_;
4920   # Macros to trace, with their minimal number of arguments.
4921   #
4922   # IMPORTANT: If you add a macro here, you should also add this macro
4923   # =========  to Automake-preselection in autoconf/lib/autom4te.in.
4924   my %traced = (
4925                 AC_CANONICAL_BUILD => 0,
4926                 AC_CANONICAL_HOST => 0,
4927                 AC_CANONICAL_TARGET => 0,
4928                 AC_CONFIG_AUX_DIR => 1,
4929                 AC_CONFIG_FILES => 1,
4930                 AC_CONFIG_HEADERS => 1,
4931                 AC_CONFIG_LIBOBJ_DIR => 1,
4932                 AC_CONFIG_LINKS => 1,
4933                 AC_FC_SRCEXT => 1,
4934                 AC_INIT => 0,
4935                 AC_LIBSOURCE => 1,
4936                 AC_REQUIRE_AUX_FILE => 1,
4937                 AC_SUBST_TRACE => 1,
4938                 AM_AUTOMAKE_VERSION => 1,
4939                 AM_CONDITIONAL => 2,
4940                 AM_ENABLE_MULTILIB => 0,
4941                 AM_GNU_GETTEXT => 0,
4942                 AM_GNU_GETTEXT_INTL_SUBDIR => 0,
4943                 AM_INIT_AUTOMAKE => 0,
4944                 AM_MAINTAINER_MODE => 0,
4945                 AM_PROG_CC_C_O => 0,
4946                 _AM_SUBST_NOTMAKE => 1,
4947                 _AM_COND_IF => 1,
4948                 _AM_COND_ELSE => 1,
4949                 _AM_COND_ENDIF => 1,
4950                 LT_SUPPORTED_TAG => 1,
4951                 _LT_AC_TAGCONFIG => 0,
4952                 m4_include => 1,
4953                 m4_sinclude => 1,
4954                 sinclude => 1,
4955               );
4957   my $traces = ($ENV{AUTOCONF} || 'autoconf') . " ";
4959   # Use a separator unlikely to be used, not `:', the default, which
4960   # has a precise meaning for AC_CONFIG_FILES and so on.
4961   $traces .= join (' ',
4962                    map { "--trace=$_" . ':\$f:\$l::\$d::\$n::\${::}%' }
4963                    (keys %traced));
4965   my $tracefh = new Automake::XFile ("$traces $filename |");
4966   verb "reading $traces";
4968   @cond_stack = ();
4969   my $where;
4971   while ($_ = $tracefh->getline)
4972     {
4973       chomp;
4974       my ($here, $depth, @args) = split (/::/);
4975       $where = new Automake::Location $here;
4976       my $macro = $args[0];
4978       prog_error ("unrequested trace `$macro'")
4979         unless exists $traced{$macro};
4981       # Skip and diagnose malformed calls.
4982       if ($#args < $traced{$macro})
4983         {
4984           msg ('syntax', $where, "not enough arguments for $macro");
4985           next;
4986         }
4988       # Alphabetical ordering please.
4989       if ($macro eq 'AC_CANONICAL_BUILD')
4990         {
4991           if ($seen_canonical <= AC_CANONICAL_BUILD)
4992             {
4993               $seen_canonical = AC_CANONICAL_BUILD;
4994               $canonical_location = $where;
4995             }
4996         }
4997       elsif ($macro eq 'AC_CANONICAL_HOST')
4998         {
4999           if ($seen_canonical <= AC_CANONICAL_HOST)
5000             {
5001               $seen_canonical = AC_CANONICAL_HOST;
5002               $canonical_location = $where;
5003             }
5004         }
5005       elsif ($macro eq 'AC_CANONICAL_TARGET')
5006         {
5007           $seen_canonical = AC_CANONICAL_TARGET;
5008           $canonical_location = $where;
5009         }
5010       elsif ($macro eq 'AC_CONFIG_AUX_DIR')
5011         {
5012           if ($seen_init_automake)
5013             {
5014               error ($where, "AC_CONFIG_AUX_DIR must be called before "
5015                      . "AM_INIT_AUTOMAKE...", partial => 1);
5016               error ($seen_init_automake, "... AM_INIT_AUTOMAKE called here");
5017             }
5018           $config_aux_dir = $args[1];
5019           $config_aux_dir_set_in_configure_ac = 1;
5020           $relative_dir = '.';
5021           check_directory ($config_aux_dir, $where);
5022         }
5023       elsif ($macro eq 'AC_CONFIG_FILES')
5024         {
5025           # Look at potential Makefile.am's.
5026           scan_autoconf_config_files ($where, $args[1]);
5027         }
5028       elsif ($macro eq 'AC_CONFIG_HEADERS')
5029         {
5030           foreach my $spec (split (' ', $args[1]))
5031             {
5032               my ($dest, @src) = split (':', $spec);
5033               $ac_config_files_location{$dest} = $where;
5034               push @config_headers, $spec;
5035             }
5036         }
5037       elsif ($macro eq 'AC_CONFIG_LIBOBJ_DIR')
5038         {
5039           $config_libobj_dir = $args[1];
5040           $relative_dir = '.';
5041           check_directory ($config_libobj_dir, $where);
5042         }
5043       elsif ($macro eq 'AC_CONFIG_LINKS')
5044         {
5045           foreach my $spec (split (' ', $args[1]))
5046             {
5047               my ($dest, $src) = split (':', $spec);
5048               $ac_config_files_location{$dest} = $where;
5049               push @config_links, $spec;
5050             }
5051         }
5052       elsif ($macro eq 'AC_FC_SRCEXT')
5053         {
5054           my $suffix = $args[1];
5055           # These flags are used as %SOURCEFLAG% in depend2.am,
5056           # where the trailing space is important.
5057           $sourceflags{'.' . $suffix} = '$(FCFLAGS_' . $suffix . ') '
5058             if ($suffix eq 'f90' || $suffix eq 'f95' || $suffix eq 'f03' || $suffix eq 'f08');
5059         }
5060       elsif ($macro eq 'AC_INIT')
5061         {
5062           if (defined $args[2])
5063             {
5064               $package_version = $args[2];
5065               $package_version_location = $where;
5066             }
5067         }
5068       elsif ($macro eq 'AC_LIBSOURCE')
5069         {
5070           $libsources{$args[1]} = $here;
5071         }
5072       elsif ($macro eq 'AC_REQUIRE_AUX_FILE')
5073         {
5074           # Only remember the first time a file is required.
5075           $required_aux_file{$args[1]} = $where
5076             unless exists $required_aux_file{$args[1]};
5077         }
5078       elsif ($macro eq 'AC_SUBST_TRACE')
5079         {
5080           # Just check for alphanumeric in AC_SUBST_TRACE.  If you do
5081           # AC_SUBST(5), then too bad.
5082           $configure_vars{$args[1]} = $where
5083             if $args[1] =~ /^\w+$/;
5084         }
5085       elsif ($macro eq 'AM_AUTOMAKE_VERSION')
5086         {
5087           error ($where,
5088                  "version mismatch.  This is Automake $VERSION,\n" .
5089                  "but the definition used by this AM_INIT_AUTOMAKE\n" .
5090                  "comes from Automake $args[1].  You should recreate\n" .
5091                  "aclocal.m4 with aclocal and run automake again.\n",
5092                  # $? = 63 is used to indicate version mismatch to missing.
5093                  exit_code => 63)
5094             if $VERSION ne $args[1];
5096           $seen_automake_version = 1;
5097         }
5098       elsif ($macro eq 'AM_CONDITIONAL')
5099         {
5100           $configure_cond{$args[1]} = $where;
5101         }
5102       elsif ($macro eq 'AM_ENABLE_MULTILIB')
5103         {
5104           $seen_multilib = $where;
5105         }
5106       elsif ($macro eq 'AM_GNU_GETTEXT')
5107         {
5108           $seen_gettext = $where;
5109           $ac_gettext_location = $where;
5110           $seen_gettext_external = grep ($_ eq 'external', @args);
5111         }
5112       elsif ($macro eq 'AM_GNU_GETTEXT_INTL_SUBDIR')
5113         {
5114           $seen_gettext_intl = $where;
5115         }
5116       elsif ($macro eq 'AM_INIT_AUTOMAKE')
5117         {
5118           $seen_init_automake = $where;
5119           if (defined $args[2])
5120             {
5121               $package_version = $args[2];
5122               $package_version_location = $where;
5123             }
5124           elsif (defined $args[1])
5125             {
5126               exit $exit_code
5127                 if (process_global_option_list ($where,
5128                                                 split (' ', $args[1])));
5129             }
5130         }
5131       elsif ($macro eq 'AM_MAINTAINER_MODE')
5132         {
5133           $seen_maint_mode = $where;
5134         }
5135       elsif ($macro eq 'AM_PROG_CC_C_O')
5136         {
5137           $seen_cc_c_o = $where;
5138         }
5139       elsif ($macro eq '_AM_COND_IF')
5140         {
5141           cond_stack_if ('', $args[1], $where);
5142           error ($where, "missing m4 quoting, macro depth $depth")
5143             if ($depth != 1);
5144         }
5145       elsif ($macro eq '_AM_COND_ELSE')
5146         {
5147           cond_stack_else ('!', $args[1], $where);
5148           error ($where, "missing m4 quoting, macro depth $depth")
5149             if ($depth != 1);
5150         }
5151       elsif ($macro eq '_AM_COND_ENDIF')
5152         {
5153           cond_stack_endif (undef, undef, $where);
5154           error ($where, "missing m4 quoting, macro depth $depth")
5155             if ($depth != 1);
5156         }
5157       elsif ($macro eq '_AM_SUBST_NOTMAKE')
5158         {
5159           $ignored_configure_vars{$args[1]} = $where;
5160         }
5161       elsif ($macro eq 'm4_include'
5162              || $macro eq 'm4_sinclude'
5163              || $macro eq 'sinclude')
5164         {
5165           # Skip missing `sinclude'd files.
5166           next if $macro ne 'm4_include' && ! -f $args[1];
5168           # Some modified versions of Autoconf don't use
5169           # frozen files.  Consequently it's possible that we see all
5170           # m4_include's performed during Autoconf's startup.
5171           # Obviously we don't want to distribute Autoconf's files
5172           # so we skip absolute filenames here.
5173           push @configure_deps, '$(top_srcdir)/' . $args[1]
5174             unless $here =~ m,^(?:\w:)?[\\/],;
5175           # Keep track of the greatest timestamp.
5176           if (-e $args[1])
5177             {
5178               my $mtime = mtime $args[1];
5179               $configure_deps_greatest_timestamp = $mtime
5180                 if $mtime > $configure_deps_greatest_timestamp;
5181             }
5182         }
5183       elsif ($macro eq 'LT_SUPPORTED_TAG')
5184         {
5185           $libtool_tags{$args[1]} = 1;
5186           $libtool_new_api = 1;
5187         }
5188       elsif ($macro eq '_LT_AC_TAGCONFIG')
5189         {
5190           # _LT_AC_TAGCONFIG is an old macro present in Libtool 1.5.
5191           # We use it to detect whether tags are supported.  Our
5192           # preferred interface is LT_SUPPORTED_TAG, but it was
5193           # introduced in Libtool 1.6.
5194           if (0 == keys %libtool_tags)
5195             {
5196               # Hardcode the tags supported by Libtool 1.5.
5197               %libtool_tags = (CC => 1, CXX => 1, GCJ => 1, F77 => 1);
5198             }
5199         }
5200     }
5202   error ($where, "condition stack not properly closed")
5203     if (@cond_stack);
5205   $tracefh->close;
5209 # &scan_autoconf_files ()
5210 # -----------------------
5211 # Check whether we use `configure.ac' or `configure.in'.
5212 # Scan it (and possibly `aclocal.m4') for interesting things.
5213 # We must scan aclocal.m4 because there might be AC_SUBSTs and such there.
5214 sub scan_autoconf_files ()
5216   # Reinitialize libsources here.  This isn't really necessary,
5217   # since we currently assume there is only one configure.ac.  But
5218   # that won't always be the case.
5219   %libsources = ();
5221   # Keep track of the youngest configure dependency.
5222   $configure_deps_greatest_timestamp = mtime $configure_ac;
5223   if (-e 'aclocal.m4')
5224     {
5225       my $mtime = mtime 'aclocal.m4';
5226       $configure_deps_greatest_timestamp = $mtime
5227         if $mtime > $configure_deps_greatest_timestamp;
5228     }
5230   scan_autoconf_traces ($configure_ac);
5232   @configure_input_files = sort keys %make_list;
5233   # Set input and output files if not specified by user.
5234   if (! @input_files)
5235     {
5236       @input_files = @configure_input_files;
5237       %output_files = %make_list;
5238     }
5241   if (! $seen_init_automake)
5242     {
5243       err_ac ("no proper invocation of AM_INIT_AUTOMAKE was found.\nYou "
5244               . "should verify that $configure_ac invokes AM_INIT_AUTOMAKE,"
5245               . "\nthat aclocal.m4 is present in the top-level directory,\n"
5246               . "and that aclocal.m4 was recently regenerated "
5247               . "(using aclocal).");
5248     }
5249   else
5250     {
5251       if (! $seen_automake_version)
5252         {
5253           if (-f 'aclocal.m4')
5254             {
5255               error ($seen_init_automake,
5256                      "your implementation of AM_INIT_AUTOMAKE comes from " .
5257                      "an\nold Automake version.  You should recreate " .
5258                      "aclocal.m4\nwith aclocal and run automake again.\n",
5259                      # $? = 63 is used to indicate version mismatch to missing.
5260                      exit_code => 63);
5261             }
5262           else
5263             {
5264               error ($seen_init_automake,
5265                      "no proper implementation of AM_INIT_AUTOMAKE was " .
5266                      "found,\nprobably because aclocal.m4 is missing...\n" .
5267                      "You should run aclocal to create this file, then\n" .
5268                      "run automake again.\n");
5269             }
5270         }
5271     }
5273   locate_aux_dir ();
5275   # Reorder @input_files so that the Makefile that distributes aux
5276   # files is processed last.  This is important because each directory
5277   # can require auxiliary scripts and we should wait until they have
5278   # been installed before distributing them.
5280   # The Makefile.in that distribute the aux files is the one in
5281   # $config_aux_dir or the top-level Makefile.
5282   my $auxdirdist = is_make_dir ($config_aux_dir) ? $config_aux_dir : '.';
5283   my @new_input_files = ();
5284   while (@input_files)
5285     {
5286       my $in = pop @input_files;
5287       my @ins = split (/:/, $output_files{$in});
5288       if (dirname ($ins[0]) eq $auxdirdist)
5289         {
5290           push @new_input_files, $in;
5291           $automake_will_process_aux_dir = 1;
5292         }
5293       else
5294         {
5295           unshift @new_input_files, $in;
5296         }
5297     }
5298   @input_files = @new_input_files;
5300   # If neither the auxdir/Makefile nor the ./Makefile are generated
5301   # by Automake, we won't distribute the aux files anyway.  Assume
5302   # the user know what (s)he does, and pretend we will distribute
5303   # them to disable the error in require_file_internal.
5304   $automake_will_process_aux_dir = 1 if ! is_make_dir ($auxdirdist);
5306   # Look for some files we need.  Always check for these.  This
5307   # check must be done for every run, even those where we are only
5308   # looking at a subdir Makefile.  We must set relative_dir for
5309   # maybe_push_required_file to work.
5310   # Sort the files for stable verbose output.
5311   $relative_dir = '.';
5312   foreach my $file (sort keys %required_aux_file)
5313     {
5314       require_conf_file ($required_aux_file{$file}->get, FOREIGN, $file)
5315     }
5316   err_am "`install.sh' is an anachronism; use `install-sh' instead"
5317     if -f $config_aux_dir . '/install.sh';
5319   # Preserve dist_common for later.
5320   $configure_dist_common = variable_value ('DIST_COMMON') || '';
5324 ################################################################
5326 # Set up for Cygnus mode.
5327 sub check_cygnus
5329   my $cygnus = option 'cygnus';
5330   return unless $cygnus;
5332   set_strictness ('foreign');
5333   set_option ('no-installinfo', $cygnus);
5334   set_option ('no-dependencies', $cygnus);
5335   set_option ('no-dist', $cygnus);
5337   err_ac "`AM_MAINTAINER_MODE' required when --cygnus specified"
5338     if !$seen_maint_mode;
5341 # Do any extra checking for GNU standards.
5342 sub check_gnu_standards
5344   if ($relative_dir eq '.')
5345     {
5346       # In top level (or only) directory.
5347       require_file ("$am_file.am", GNU,
5348                     qw/INSTALL NEWS README AUTHORS ChangeLog/);
5350       # Accept one of these three licenses; default to COPYING.
5351       # Make sure we do not overwrite an existing license.
5352       my $license;
5353       foreach (qw /COPYING COPYING.LIB COPYING.LESSER/)
5354         {
5355           if (-f $_)
5356             {
5357               $license = $_;
5358               last;
5359             }
5360         }
5361       require_file ("$am_file.am", GNU, 'COPYING')
5362         unless $license;
5363     }
5365   for my $opt ('no-installman', 'no-installinfo')
5366     {
5367       msg ('error-gnu', option $opt,
5368            "option `$opt' disallowed by GNU standards")
5369         if option $opt;
5370     }
5373 # Do any extra checking for GNITS standards.
5374 sub check_gnits_standards
5376   if ($relative_dir eq '.')
5377     {
5378       # In top level (or only) directory.
5379       require_file ("$am_file.am", GNITS, 'THANKS');
5380     }
5383 ################################################################
5385 # Functions to handle files of each language.
5387 # Each `lang_X_rewrite($DIRECTORY, $BASE, $EXT)' function follows a
5388 # simple formula: Return value is LANG_SUBDIR if the resulting object
5389 # file should be in a subdir if the source file is, LANG_PROCESS if
5390 # file is to be dealt with, LANG_IGNORE otherwise.
5392 # Much of the actual processing is handled in
5393 # handle_single_transform.  These functions exist so that
5394 # auxiliary information can be recorded for a later cleanup pass.
5395 # Note that the calls to these functions are computed, so don't bother
5396 # searching for their precise names in the source.
5398 # This is just a convenience function that can be used to determine
5399 # when a subdir object should be used.
5400 sub lang_sub_obj
5402     return option 'subdir-objects' ? LANG_SUBDIR : LANG_PROCESS;
5405 # Rewrite a single C source file.
5406 sub lang_c_rewrite
5408   my ($directory, $base, $ext, $nonansi_obj, $have_per_exec_flags, $var) = @_;
5410   if (option 'ansi2knr' && $base =~ /_$/)
5411     {
5412       # FIXME: include line number in error.
5413       err_am "C source file `$base.c' would be deleted by ansi2knr rules";
5414     }
5416   my $r = LANG_PROCESS;
5417   if (option 'subdir-objects')
5418     {
5419       $r = LANG_SUBDIR;
5420       if ($directory && $directory ne '.')
5421         {
5422           $base = $directory . '/' . $base;
5424           # libtool is always able to put the object at the proper place,
5425           # so we do not have to require AM_PROG_CC_C_O when building .lo files.
5426           msg_var ('portability', $var,
5427                    "compiling `$base.c' in subdir requires "
5428                    . "`AM_PROG_CC_C_O' in `$configure_ac'",
5429                    uniq_scope => US_GLOBAL,
5430                    uniq_part => 'AM_PROG_CC_C_O subdir')
5431             unless $seen_cc_c_o || $nonansi_obj eq '.lo';
5432         }
5434       # In this case we already have the directory information, so
5435       # don't add it again.
5436       $de_ansi_files{$base} = '';
5437     }
5438   else
5439     {
5440       $de_ansi_files{$base} = (($directory eq '.' || $directory eq '')
5441                                ? ''
5442                                : "$directory/");
5443     }
5445   if (! $seen_cc_c_o
5446       && $have_per_exec_flags
5447       && ! option 'subdir-objects'
5448       && $nonansi_obj ne '.lo')
5449     {
5450       msg_var ('portability',
5451                $var, "compiling `$base.c' with per-target flags requires "
5452                . "`AM_PROG_CC_C_O' in `$configure_ac'",
5453                uniq_scope => US_GLOBAL,
5454                uniq_part => 'AM_PROG_CC_C_O per-target')
5455     }
5457     return $r;
5460 # Rewrite a single C++ source file.
5461 sub lang_cxx_rewrite
5463     return &lang_sub_obj;
5466 # Rewrite a single header file.
5467 sub lang_header_rewrite
5469     # Header files are simply ignored.
5470     return LANG_IGNORE;
5473 # Rewrite a single yacc file.
5474 sub lang_yacc_rewrite
5476     my ($directory, $base, $ext) = @_;
5478     my $r = &lang_sub_obj;
5479     (my $newext = $ext) =~ tr/y/c/;
5480     return ($r, $newext);
5483 # Rewrite a single yacc++ file.
5484 sub lang_yaccxx_rewrite
5486     my ($directory, $base, $ext) = @_;
5488     my $r = &lang_sub_obj;
5489     (my $newext = $ext) =~ tr/y/c/;
5490     return ($r, $newext);
5493 # Rewrite a single lex file.
5494 sub lang_lex_rewrite
5496     my ($directory, $base, $ext) = @_;
5498     my $r = &lang_sub_obj;
5499     (my $newext = $ext) =~ tr/l/c/;
5500     return ($r, $newext);
5503 # Rewrite a single lex++ file.
5504 sub lang_lexxx_rewrite
5506     my ($directory, $base, $ext) = @_;
5508     my $r = &lang_sub_obj;
5509     (my $newext = $ext) =~ tr/l/c/;
5510     return ($r, $newext);
5513 # Rewrite a single assembly file.
5514 sub lang_asm_rewrite
5516     return &lang_sub_obj;
5519 # Rewrite a single preprocessed assembly file.
5520 sub lang_cppasm_rewrite
5522     return &lang_sub_obj;
5525 # Rewrite a single Fortran 77 file.
5526 sub lang_f77_rewrite
5528     return &lang_sub_obj;
5531 # Rewrite a single Fortran file.
5532 sub lang_fc_rewrite
5534     return &lang_sub_obj;
5537 # Rewrite a single preprocessed Fortran file.
5538 sub lang_ppfc_rewrite
5540     return &lang_sub_obj;
5543 # Rewrite a single preprocessed Fortran 77 file.
5544 sub lang_ppf77_rewrite
5546     return &lang_sub_obj;
5549 # Rewrite a single ratfor file.
5550 sub lang_ratfor_rewrite
5552     return &lang_sub_obj;
5555 # Rewrite a single Objective C file.
5556 sub lang_objc_rewrite
5558     return &lang_sub_obj;
5561 # Rewrite a single Unified Parallel C file.
5562 sub lang_upc_rewrite
5564     return &lang_sub_obj;
5567 # Rewrite a single Java file.
5568 sub lang_java_rewrite
5570     return LANG_SUBDIR;
5573 # The lang_X_finish functions are called after all source file
5574 # processing is done.  Each should handle defining rules for the
5575 # language, etc.  A finish function is only called if a source file of
5576 # the appropriate type has been seen.
5578 sub lang_c_finish
5580     # Push all libobjs files onto de_ansi_files.  We actually only
5581     # push files which exist in the current directory, and which are
5582     # genuine source files.
5583     foreach my $file (keys %libsources)
5584     {
5585         if ($file =~ /^(.*)\.[cly]$/ && -f "$relative_dir/$file")
5586         {
5587             $de_ansi_files{$1} = ''
5588         }
5589     }
5591     if (option 'ansi2knr' && keys %de_ansi_files)
5592     {
5593         # Make all _.c files depend on their corresponding .c files.
5594         my @objects;
5595         foreach my $base (sort keys %de_ansi_files)
5596         {
5597             # Each _.c file must depend on ansi2knr; otherwise it
5598             # might be used in a parallel build before it is built.
5599             # We need to support files in the srcdir and in the build
5600             # dir (because these files might be auto-generated.  But
5601             # we can't use $< -- some makes only define $< during a
5602             # suffix rule.
5603             my $ansfile = $de_ansi_files{$base} . $base . '.c';
5604             $output_rules .= ($base . "_.c: $ansfile \$(ANSI2KNR)\n\t"
5605                               . '$(CPP) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) '
5606                               . '`if test -f $(srcdir)/' . $ansfile
5607                               . '; then echo $(srcdir)/' . $ansfile
5608                               . '; else echo ' . $ansfile . '; fi` '
5609                               . "| sed 's/^# \\([0-9]\\)/#line \\1/' "
5610                               . '| $(ANSI2KNR) > $@'
5611                               # If ansi2knr fails then we shouldn't
5612                               # create the _.c file
5613                               . " || rm -f \$\@\n");
5614             push (@objects, $base . '_.$(OBJEXT)');
5615             push (@objects, $base . '_.lo')
5616               if var ('LIBTOOL');
5618             # Explicitly clean the _.c files if they are in a
5619             # subdirectory. (In the current directory they get erased
5620             # by a `rm -f *_.c' rule.)
5621             $clean_files{$base . '_.c'} = MOSTLY_CLEAN
5622               if dirname ($base) ne '.';
5623         }
5625         # Make all _.o (and _.lo) files depend on ansi2knr.
5626         # Use a sneaky little hack to make it print nicely.
5627         &pretty_print_rule ('', '', @objects, ':', '$(ANSI2KNR)');
5628     }
5631 # This is a yacc helper which is called whenever we have decided to
5632 # compile a yacc file.
5633 sub lang_yacc_target_hook
5635     my ($self, $aggregate, $output, $input, %transform) = @_;
5637     my $flag = $aggregate . "_YFLAGS";
5638     my $flagvar = var $flag;
5639     my $YFLAGSvar = var 'YFLAGS';
5640     if (($flagvar && $flagvar->variable_value =~ /$DASH_D_PATTERN/o)
5641         || ($YFLAGSvar && $YFLAGSvar->variable_value =~ /$DASH_D_PATTERN/o))
5642     {
5643         (my $output_base = $output) =~ s/$KNOWN_EXTENSIONS_PATTERN$//;
5644         my $header = $output_base . '.h';
5646         # Found a `-d' that applies to the compilation of this file.
5647         # Add a dependency for the generated header file, and arrange
5648         # for that file to be included in the distribution.
5649         foreach my $cond (Automake::Rule::define (${header}, 'internal',
5650                                                   RULE_AUTOMAKE, TRUE,
5651                                                   INTERNAL))
5652           {
5653             my $condstr = $cond->subst_string;
5654             $output_rules .=
5655               "$condstr${header}: $output\n"
5656               # Recover from removal of $header
5657               . "$condstr\t\@if test ! -f \$@; then \\\n"
5658               . "$condstr\t  rm -f $output; \\\n"
5659               . "$condstr\t  \$(MAKE) \$(AM_MAKEFLAGS) $output; \\\n"
5660               . "$condstr\telse :; fi\n";
5661           }
5662         # Distribute the generated file, unless its .y source was
5663         # listed in a nodist_ variable.  (&handle_source_transform
5664         # will set DIST_SOURCE.)
5665         &push_dist_common ($header)
5666           if $transform{'DIST_SOURCE'};
5668         # If the files are built in the build directory, then we want
5669         # to remove them with `make clean'.  If they are in srcdir
5670         # they shouldn't be touched.  However, we can't determine this
5671         # statically, and the GNU rules say that yacc/lex output files
5672         # should be removed by maintainer-clean.  So that's what we
5673         # do.
5674         $clean_files{$header} = MAINTAINER_CLEAN;
5675     }
5676     # Erase $OUTPUT on `make maintainer-clean' (by GNU standards).
5677     # See the comment above for $HEADER.
5678     $clean_files{$output} = MAINTAINER_CLEAN;
5681 # This is a lex helper which is called whenever we have decided to
5682 # compile a lex file.
5683 sub lang_lex_target_hook
5685     my ($self, $aggregate, $output, $input) = @_;
5686     # If the files are built in the build directory, then we want to
5687     # remove them with `make clean'.  If they are in srcdir they
5688     # shouldn't be touched.  However, we can't determine this
5689     # statically, and the GNU rules say that yacc/lex output files
5690     # should be removed by maintainer-clean.  So that's what we do.
5691     $clean_files{$output} = MAINTAINER_CLEAN;
5694 # This is a helper for both lex and yacc.
5695 sub yacc_lex_finish_helper
5697   return if defined $language_scratch{'lex-yacc-done'};
5698   $language_scratch{'lex-yacc-done'} = 1;
5700   # FIXME: for now, no line number.
5701   require_conf_file ($configure_ac, FOREIGN, 'ylwrap');
5702   &define_variable ('YLWRAP', "$am_config_aux_dir/ylwrap", INTERNAL);
5705 sub lang_yacc_finish
5707   return if defined $language_scratch{'yacc-done'};
5708   $language_scratch{'yacc-done'} = 1;
5710   reject_var 'YACCFLAGS', "`YACCFLAGS' obsolete; use `YFLAGS' instead";
5712   yacc_lex_finish_helper;
5716 sub lang_lex_finish
5718   return if defined $language_scratch{'lex-done'};
5719   $language_scratch{'lex-done'} = 1;
5721   yacc_lex_finish_helper;
5725 # Given a hash table of linker names, pick the name that has the most
5726 # precedence.  This is lame, but something has to have global
5727 # knowledge in order to eliminate the conflict.  Add more linkers as
5728 # required.
5729 sub resolve_linker
5731     my (%linkers) = @_;
5733     foreach my $l (qw(GCJLINK CXXLINK F77LINK FCLINK OBJCLINK UPCLINK))
5734     {
5735         return $l if defined $linkers{$l};
5736     }
5737     return 'LINK';
5740 # Called to indicate that an extension was used.
5741 sub saw_extension
5743     my ($ext) = @_;
5744     if (! defined $extension_seen{$ext})
5745     {
5746         $extension_seen{$ext} = 1;
5747     }
5748     else
5749     {
5750         ++$extension_seen{$ext};
5751     }
5754 # Return the number of files seen for a given language.  Knows about
5755 # special cases we care about.  FIXME: this is hideous.  We need
5756 # something that involves real language objects.  For instance yacc
5757 # and yaccxx could both derive from a common yacc class which would
5758 # know about the strange ylwrap requirement.  (Or better yet we could
5759 # just not support legacy yacc!)
5760 sub count_files_for_language
5762     my ($name) = @_;
5764     my @names;
5765     if ($name eq 'yacc' || $name eq 'yaccxx')
5766     {
5767         @names = ('yacc', 'yaccxx');
5768     }
5769     elsif ($name eq 'lex' || $name eq 'lexxx')
5770     {
5771         @names = ('lex', 'lexxx');
5772     }
5773     else
5774     {
5775         @names = ($name);
5776     }
5778     my $r = 0;
5779     foreach $name (@names)
5780     {
5781         my $lang = $languages{$name};
5782         foreach my $ext (@{$lang->extensions})
5783         {
5784             $r += $extension_seen{$ext}
5785                 if defined $extension_seen{$ext};
5786         }
5787     }
5789     return $r
5792 # Called to ask whether source files have been seen . If HEADERS is 1,
5793 # headers can be included.
5794 sub saw_sources_p
5796     my ($headers) = @_;
5798     # count all the sources
5799     my $count = 0;
5800     foreach my $val (values %extension_seen)
5801     {
5802         $count += $val;
5803     }
5805     if (!$headers)
5806     {
5807         $count -= count_files_for_language ('header');
5808     }
5810     return $count > 0;
5814 # register_language (%ATTRIBUTE)
5815 # ------------------------------
5816 # Register a single language.
5817 # Each %ATTRIBUTE is of the form ATTRIBUTE => VALUE.
5818 sub register_language (%)
5820   my (%option) = @_;
5822   # Set the defaults.
5823   $option{'ansi'} = 0
5824     unless defined $option{'ansi'};
5825   $option{'autodep'} = 'no'
5826     unless defined $option{'autodep'};
5827   $option{'linker'} = ''
5828     unless defined $option{'linker'};
5829   $option{'flags'} = []
5830     unless defined $option{'flags'};
5831   $option{'output_extensions'} = sub { return ( '.$(OBJEXT)', '.lo' ) }
5832     unless defined $option{'output_extensions'};
5833   $option{'nodist_specific'} = 0
5834     unless defined $option{'nodist_specific'};
5836   my $lang = new Language (%option);
5838   # Fill indexes.
5839   $extension_map{$_} = $lang->name foreach @{$lang->extensions};
5840   $languages{$lang->name} = $lang;
5841   my $link = $lang->linker;
5842   if ($link)
5843     {
5844       if (exists $link_languages{$link})
5845         {
5846           prog_error ("`$link' has different definitions in "
5847                       . $lang->name . " and " . $link_languages{$link}->name)
5848             if $lang->link ne $link_languages{$link}->link;
5849         }
5850       else
5851         {
5852           $link_languages{$link} = $lang;
5853         }
5854     }
5856   # Update the pattern of known extensions.
5857   accept_extensions (@{$lang->extensions});
5859   # Upate the $suffix_rule map.
5860   foreach my $suffix (@{$lang->extensions})
5861     {
5862       foreach my $dest (&{$lang->output_extensions} ($suffix))
5863         {
5864           register_suffix_rule (INTERNAL, $suffix, $dest);
5865         }
5866     }
5869 # derive_suffix ($EXT, $OBJ)
5870 # --------------------------
5871 # This function is used to find a path from a user-specified suffix $EXT
5872 # to $OBJ or to some other suffix we recognize internally, e.g. `cc'.
5873 sub derive_suffix ($$)
5875   my ($source_ext, $obj) = @_;
5877   while (! $extension_map{$source_ext}
5878          && $source_ext ne $obj
5879          && exists $suffix_rules->{$source_ext}
5880          && exists $suffix_rules->{$source_ext}{$obj})
5881     {
5882       $source_ext = $suffix_rules->{$source_ext}{$obj}[0];
5883     }
5885   return $source_ext;
5889 ################################################################
5891 # Pretty-print something and append to output_rules.
5892 sub pretty_print_rule
5894     $output_rules .= &makefile_wrap (@_);
5898 ################################################################
5901 ## -------------------------------- ##
5902 ## Handling the conditional stack.  ##
5903 ## -------------------------------- ##
5906 # $STRING
5907 # make_conditional_string ($NEGATE, $COND)
5908 # ----------------------------------------
5909 sub make_conditional_string ($$)
5911   my ($negate, $cond) = @_;
5912   $cond = "${cond}_TRUE"
5913     unless $cond =~ /^TRUE|FALSE$/;
5914   $cond = Automake::Condition::conditional_negate ($cond)
5915     if $negate;
5916   return $cond;
5920 my %_am_macro_for_cond =
5921   (
5922   AMDEP => "one of the compiler tests\n"
5923            . "    AC_PROG_CC, AC_PROG_CXX, AC_PROG_CXX, AC_PROG_OBJC,\n"
5924            . "    AM_PROG_AS, AM_PROG_GCJ, AM_PROG_UPC",
5925   am__fastdepCC => 'AC_PROG_CC',
5926   am__fastdepCCAS => 'AM_PROG_AS',
5927   am__fastdepCXX => 'AC_PROG_CXX',
5928   am__fastdepGCJ => 'AM_PROG_GCJ',
5929   am__fastdepOBJC => 'AC_PROG_OBJC',
5930   am__fastdepUPC => 'AM_PROG_UPC'
5931   );
5933 # $COND
5934 # cond_stack_if ($NEGATE, $COND, $WHERE)
5935 # --------------------------------------
5936 sub cond_stack_if ($$$)
5938   my ($negate, $cond, $where) = @_;
5940   if (! $configure_cond{$cond} && $cond !~ /^TRUE|FALSE$/)
5941     {
5942       my $text = "$cond does not appear in AM_CONDITIONAL";
5943       my $scope = US_LOCAL;
5944       if (exists $_am_macro_for_cond{$cond})
5945         {
5946           my $mac = $_am_macro_for_cond{$cond};
5947           $text .= "\n  The usual way to define `$cond' is to add ";
5948           $text .= ($mac =~ / /) ? $mac : "`$mac'";
5949           $text .= "\n  to `$configure_ac' and run `aclocal' and `autoconf' again.";
5950           # These warnings appear in Automake files (depend2.am),
5951           # so there is no need to display them more than once:
5952           $scope = US_GLOBAL;
5953         }
5954       error $where, $text, uniq_scope => $scope;
5955     }
5957   push (@cond_stack, make_conditional_string ($negate, $cond));
5959   return new Automake::Condition (@cond_stack);
5963 # $COND
5964 # cond_stack_else ($NEGATE, $COND, $WHERE)
5965 # ----------------------------------------
5966 sub cond_stack_else ($$$)
5968   my ($negate, $cond, $where) = @_;
5970   if (! @cond_stack)
5971     {
5972       error $where, "else without if";
5973       return FALSE;
5974     }
5976   $cond_stack[$#cond_stack] =
5977     Automake::Condition::conditional_negate ($cond_stack[$#cond_stack]);
5979   # If $COND is given, check against it.
5980   if (defined $cond)
5981     {
5982       $cond = make_conditional_string ($negate, $cond);
5984       error ($where, "else reminder ($negate$cond) incompatible with "
5985              . "current conditional: $cond_stack[$#cond_stack]")
5986         if $cond_stack[$#cond_stack] ne $cond;
5987     }
5989   return new Automake::Condition (@cond_stack);
5993 # $COND
5994 # cond_stack_endif ($NEGATE, $COND, $WHERE)
5995 # -----------------------------------------
5996 sub cond_stack_endif ($$$)
5998   my ($negate, $cond, $where) = @_;
5999   my $old_cond;
6001   if (! @cond_stack)
6002     {
6003       error $where, "endif without if";
6004       return TRUE;
6005     }
6007   # If $COND is given, check against it.
6008   if (defined $cond)
6009     {
6010       $cond = make_conditional_string ($negate, $cond);
6012       error ($where, "endif reminder ($negate$cond) incompatible with "
6013              . "current conditional: $cond_stack[$#cond_stack]")
6014         if $cond_stack[$#cond_stack] ne $cond;
6015     }
6017   pop @cond_stack;
6019   return new Automake::Condition (@cond_stack);
6026 ## ------------------------ ##
6027 ## Handling the variables.  ##
6028 ## ------------------------ ##
6031 # &define_pretty_variable ($VAR, $COND, $WHERE, @VALUE)
6032 # -----------------------------------------------------
6033 # Like define_variable, but the value is a list, and the variable may
6034 # be defined conditionally.  The second argument is the condition
6035 # under which the value should be defined; this should be the empty
6036 # string to define the variable unconditionally.  The third argument
6037 # is a list holding the values to use for the variable.  The value is
6038 # pretty printed in the output file.
6039 sub define_pretty_variable ($$$@)
6041     my ($var, $cond, $where, @value) = @_;
6043     if (! vardef ($var, $cond))
6044     {
6045         Automake::Variable::define ($var, VAR_AUTOMAKE, '', $cond, "@value",
6046                                     '', $where, VAR_PRETTY);
6047         rvar ($var)->rdef ($cond)->set_seen;
6048     }
6052 # define_variable ($VAR, $VALUE, $WHERE)
6053 # --------------------------------------
6054 # Define a new Automake Makefile variable VAR to VALUE, but only if
6055 # not already defined.
6056 sub define_variable ($$$)
6058     my ($var, $value, $where) = @_;
6059     define_pretty_variable ($var, TRUE, $where, $value);
6063 # define_files_variable ($VAR, \@BASENAME, $EXTENSION, $WHERE)
6064 # -----------------------------------------------------------
6065 # Define the $VAR which content is the list of file names composed of
6066 # a @BASENAME and the $EXTENSION.
6067 sub define_files_variable ($\@$$)
6069   my ($var, $basename, $extension, $where) = @_;
6070   define_variable ($var,
6071                    join (' ', map { "$_.$extension" } @$basename),
6072                    $where);
6076 # Like define_variable, but define a variable to be the configure
6077 # substitution by the same name.
6078 sub define_configure_variable ($)
6080   my ($var) = @_;
6082   my $pretty = VAR_ASIS;
6083   my $owner = VAR_CONFIGURE;
6085   # Some variables we do not want to output.  For instance it
6086   # would be a bad idea to output `U = @U@` when `@U@` can be
6087   # substituted as `\`.
6088   $pretty = VAR_SILENT if exists $ignored_configure_vars{$var};
6090   # ANSI2KNR is a variable that Automake wants to redefine, so
6091   # it must be owned by Automake.  (It is also used as a proof
6092   # that AM_C_PROTOTYPES has been run, that's why we do not simply
6093   # omit the AC_SUBST.)
6094   $owner = VAR_AUTOMAKE if $var eq 'ANSI2KNR';
6096   Automake::Variable::define ($var, $owner, '', TRUE, subst $var,
6097                               '', $configure_vars{$var}, $pretty);
6101 # define_compiler_variable ($LANG)
6102 # --------------------------------
6103 # Define a compiler variable.  We also handle defining the `LT'
6104 # version of the command when using libtool.
6105 sub define_compiler_variable ($)
6107     my ($lang) = @_;
6109     my ($var, $value) = ($lang->compiler, $lang->compile);
6110     my $libtool_tag = '';
6111     $libtool_tag = '--tag=' . $lang->libtool_tag . ' '
6112       if $lang->libtool_tag && exists $libtool_tags{$lang->libtool_tag};
6113     &define_variable ($var, $value, INTERNAL);
6114     &define_variable ("LT$var",
6115                       "\$(LIBTOOL) $libtool_tag\$(AM_LIBTOOLFLAGS) "
6116                       . "\$(LIBTOOLFLAGS) --mode=compile $value",
6117                       INTERNAL)
6118       if var ('LIBTOOL');
6122 # define_linker_variable ($LANG)
6123 # ------------------------------
6124 # Define linker variables.
6125 sub define_linker_variable ($)
6127     my ($lang) = @_;
6129     my $libtool_tag = '';
6130     $libtool_tag = '--tag=' . $lang->libtool_tag . ' '
6131       if $lang->libtool_tag && exists $libtool_tags{$lang->libtool_tag};
6132     # CCLD = $(CC).
6133     &define_variable ($lang->lder, $lang->ld, INTERNAL);
6134     # CCLINK = $(CCLD) blah blah...
6135     &define_variable ($lang->linker,
6136                       ((var ('LIBTOOL') ?
6137                         "\$(LIBTOOL) $libtool_tag\$(AM_LIBTOOLFLAGS) "
6138                         . "\$(LIBTOOLFLAGS) --mode=link " : '')
6139                        . $lang->link),
6140                       INTERNAL);
6143 sub define_per_target_linker_variable ($$)
6145   my ($linker, $target) = @_;
6147   # If the user wrote a custom link command, we don't define ours.
6148   return "${target}_LINK"
6149     if set_seen "${target}_LINK";
6151   my $xlink = $linker ? $linker : 'LINK';
6153   my $lang = $link_languages{$xlink};
6154   prog_error "Unknown language for linker variable `$xlink'"
6155     unless $lang;
6157   my $link_command = $lang->link;
6158   if (var 'LIBTOOL')
6159     {
6160       my $libtool_tag = '';
6161       $libtool_tag = '--tag=' . $lang->libtool_tag . ' '
6162         if $lang->libtool_tag && exists $libtool_tags{$lang->libtool_tag};
6164       $link_command =
6165         "\$(LIBTOOL) $libtool_tag\$(AM_LIBTOOLFLAGS) \$(LIBTOOLFLAGS) "
6166         . "--mode=link " . $link_command;
6167     }
6169   # Rewrite each occurrence of `AM_$flag' in the link
6170   # command into `${derived}_$flag' if it exists.
6171   my $orig_command = $link_command;
6172   my @flags = (@{$lang->flags}, 'LDFLAGS');
6173   push @flags, 'LIBTOOLFLAGS' if var 'LIBTOOL';
6174   for my $flag (@flags)
6175     {
6176       my $val = "${target}_$flag";
6177       $link_command =~ s/\(AM_$flag\)/\($val\)/
6178         if set_seen ($val);
6179     }
6181   # If the computed command is the same as the generic command, use
6182   # the command linker variable.
6183   return $lang->linker
6184     if $link_command eq $orig_command;
6186   &define_variable ("${target}_LINK", $link_command, INTERNAL);
6187   return "${target}_LINK";
6190 ################################################################
6192 # &check_trailing_slash ($WHERE, $LINE)
6193 # --------------------------------------
6194 # Return 1 iff $LINE ends with a slash.
6195 # Might modify $LINE.
6196 sub check_trailing_slash ($\$)
6198   my ($where, $line) = @_;
6200   # Ignore `##' lines.
6201   return 0 if $$line =~ /$IGNORE_PATTERN/o;
6203   # Catch and fix a common error.
6204   msg "syntax", $where, "whitespace following trailing backslash"
6205     if $$line =~ s/\\\s+\n$/\\\n/;
6207   return $$line =~ /\\$/;
6211 # &read_am_file ($AMFILE, $WHERE)
6212 # -------------------------------
6213 # Read Makefile.am and set up %contents.  Simultaneously copy lines
6214 # from Makefile.am into $output_trailer, or define variables as
6215 # appropriate.  NOTE we put rules in the trailer section.  We want
6216 # user rules to come after our generated stuff.
6217 sub read_am_file ($$)
6219     my ($amfile, $where) = @_;
6221     my $am_file = new Automake::XFile ("< $amfile");
6222     verb "reading $amfile";
6224     # Keep track of the youngest output dependency.
6225     my $mtime = mtime $amfile;
6226     $output_deps_greatest_timestamp = $mtime
6227       if $mtime > $output_deps_greatest_timestamp;
6229     my $spacing = '';
6230     my $comment = '';
6231     my $blank = 0;
6232     my $saw_bk = 0;
6233     my $var_look = VAR_ASIS;
6235     use constant IN_VAR_DEF => 0;
6236     use constant IN_RULE_DEF => 1;
6237     use constant IN_COMMENT => 2;
6238     my $prev_state = IN_RULE_DEF;
6240     while ($_ = $am_file->getline)
6241     {
6242         $where->set ("$amfile:$.");
6243         if (/$IGNORE_PATTERN/o)
6244         {
6245             # Merely delete comments beginning with two hashes.
6246         }
6247         elsif (/$WHITE_PATTERN/o)
6248         {
6249             error $where, "blank line following trailing backslash"
6250               if $saw_bk;
6251             # Stick a single white line before the incoming macro or rule.
6252             $spacing = "\n";
6253             $blank = 1;
6254             # Flush all comments seen so far.
6255             if ($comment ne '')
6256             {
6257                 $output_vars .= $comment;
6258                 $comment = '';
6259             }
6260         }
6261         elsif (/$COMMENT_PATTERN/o)
6262         {
6263             # Stick comments before the incoming macro or rule.  Make
6264             # sure a blank line precedes the first block of comments.
6265             $spacing = "\n" unless $blank;
6266             $blank = 1;
6267             $comment .= $spacing . $_;
6268             $spacing = '';
6269             $prev_state = IN_COMMENT;
6270         }
6271         else
6272         {
6273             last;
6274         }
6275         $saw_bk = check_trailing_slash ($where, $_);
6276     }
6278     # We save the conditional stack on entry, and then check to make
6279     # sure it is the same on exit.  This lets us conditionally include
6280     # other files.
6281     my @saved_cond_stack = @cond_stack;
6282     my $cond = new Automake::Condition (@cond_stack);
6284     my $last_var_name = '';
6285     my $last_var_type = '';
6286     my $last_var_value = '';
6287     my $last_where;
6288     # FIXME: shouldn't use $_ in this loop; it is too big.
6289     while ($_)
6290     {
6291         $where->set ("$amfile:$.");
6293         # Make sure the line is \n-terminated.
6294         chomp;
6295         $_ .= "\n";
6297         # Don't look at MAINTAINER_MODE_TRUE here.  That shouldn't be
6298         # used by users.  @MAINT@ is an anachronism now.
6299         $_ =~ s/\@MAINT\@//g
6300             unless $seen_maint_mode;
6302         my $new_saw_bk = check_trailing_slash ($where, $_);
6304         if (/$IGNORE_PATTERN/o)
6305         {
6306             # Merely delete comments beginning with two hashes.
6308             # Keep any backslash from the previous line.
6309             $new_saw_bk = $saw_bk;
6310         }
6311         elsif (/$WHITE_PATTERN/o)
6312         {
6313             # Stick a single white line before the incoming macro or rule.
6314             $spacing = "\n";
6315             error $where, "blank line following trailing backslash"
6316               if $saw_bk;
6317         }
6318         elsif (/$COMMENT_PATTERN/o)
6319         {
6320             error $where, "comment following trailing backslash"
6321               if $saw_bk && $comment eq '';
6323             # Stick comments before the incoming macro or rule.
6324             $comment .= $spacing . $_;
6325             $spacing = '';
6326             $prev_state = IN_COMMENT;
6327         }
6328         elsif ($saw_bk)
6329         {
6330             if ($prev_state == IN_RULE_DEF)
6331             {
6332               my $cond = new Automake::Condition @cond_stack;
6333               $output_trailer .= $cond->subst_string;
6334               $output_trailer .= $_;
6335             }
6336             elsif ($prev_state == IN_COMMENT)
6337             {
6338                 # If the line doesn't start with a `#', add it.
6339                 # We do this because a continued comment like
6340                 #   # A = foo \
6341                 #         bar \
6342                 #         baz
6343                 # is not portable.  BSD make doesn't honor
6344                 # escaped newlines in comments.
6345                 s/^#?/#/;
6346                 $comment .= $spacing . $_;
6347             }
6348             else # $prev_state == IN_VAR_DEF
6349             {
6350               $last_var_value .= ' '
6351                 unless $last_var_value =~ /\s$/;
6352               $last_var_value .= $_;
6354               if (!/\\$/)
6355                 {
6356                   Automake::Variable::define ($last_var_name, VAR_MAKEFILE,
6357                                               $last_var_type, $cond,
6358                                               $last_var_value, $comment,
6359                                               $last_where, VAR_ASIS)
6360                     if $cond != FALSE;
6361                   $comment = $spacing = '';
6362                 }
6363             }
6364         }
6366         elsif (/$IF_PATTERN/o)
6367           {
6368             $cond = cond_stack_if ($1, $2, $where);
6369           }
6370         elsif (/$ELSE_PATTERN/o)
6371           {
6372             $cond = cond_stack_else ($1, $2, $where);
6373           }
6374         elsif (/$ENDIF_PATTERN/o)
6375           {
6376             $cond = cond_stack_endif ($1, $2, $where);
6377           }
6379         elsif (/$RULE_PATTERN/o)
6380         {
6381             # Found a rule.
6382             $prev_state = IN_RULE_DEF;
6384             # For now we have to output all definitions of user rules
6385             # and can't diagnose duplicates (see the comment in
6386             # Automake::Rule::define). So we go on and ignore the return value.
6387             Automake::Rule::define ($1, $amfile, RULE_USER, $cond, $where);
6389             check_variable_expansions ($_, $where);
6391             $output_trailer .= $comment . $spacing;
6392             my $cond = new Automake::Condition @cond_stack;
6393             $output_trailer .= $cond->subst_string;
6394             $output_trailer .= $_;
6395             $comment = $spacing = '';
6396         }
6397         elsif (/$ASSIGNMENT_PATTERN/o)
6398         {
6399             # Found a macro definition.
6400             $prev_state = IN_VAR_DEF;
6401             $last_var_name = $1;
6402             $last_var_type = $2;
6403             $last_var_value = $3;
6404             $last_where = $where->clone;
6405             if ($3 ne '' && substr ($3, -1) eq "\\")
6406               {
6407                 # We preserve the `\' because otherwise the long lines
6408                 # that are generated will be truncated by broken
6409                 # `sed's.
6410                 $last_var_value = $3 . "\n";
6411               }
6412             # Normally we try to output variable definitions in the
6413             # same format they were input.  However, POSIX compliant
6414             # systems are not required to support lines longer than
6415             # 2048 bytes (most notably, some sed implementation are
6416             # limited to 4000 bytes, and sed is used by config.status
6417             # to rewrite Makefile.in into Makefile).  Moreover nobody
6418             # would really write such long lines by hand since it is
6419             # hardly maintainable.  So if a line is longer that 1000
6420             # bytes (an arbitrary limit), assume it has been
6421             # automatically generated by some tools, and flatten the
6422             # variable definition.  Otherwise, keep the variable as it
6423             # as been input.
6424             $var_look = VAR_PRETTY if length ($last_var_value) >= 1000;
6426             if (!/\\$/)
6427               {
6428                 Automake::Variable::define ($last_var_name, VAR_MAKEFILE,
6429                                             $last_var_type, $cond,
6430                                             $last_var_value, $comment,
6431                                             $last_where, $var_look)
6432                   if $cond != FALSE;
6433                 $comment = $spacing = '';
6434                 $var_look = VAR_ASIS;
6435               }
6436         }
6437         elsif (/$INCLUDE_PATTERN/o)
6438         {
6439             my $path = $1;
6441             if ($path =~ s/^\$\(top_srcdir\)\///)
6442               {
6443                 push (@include_stack, "\$\(top_srcdir\)/$path");
6444                 # Distribute any included file.
6446                 # Always use the $(top_srcdir) prefix in DIST_COMMON,
6447                 # otherwise OSF make will implicitly copy the included
6448                 # file in the build tree during `make distdir' to satisfy
6449                 # the dependency.
6450                 # (subdircond2.test and subdircond3.test will fail.)
6451                 push_dist_common ("\$\(top_srcdir\)/$path");
6452               }
6453             else
6454               {
6455                 $path =~ s/\$\(srcdir\)\///;
6456                 push (@include_stack, "\$\(srcdir\)/$path");
6457                 # Always use the $(srcdir) prefix in DIST_COMMON,
6458                 # otherwise OSF make will implicitly copy the included
6459                 # file in the build tree during `make distdir' to satisfy
6460                 # the dependency.
6461                 # (subdircond2.test and subdircond3.test will fail.)
6462                 push_dist_common ("\$\(srcdir\)/$path");
6463                 $path = $relative_dir . "/" . $path if $relative_dir ne '.';
6464               }
6465             $where->push_context ("`$path' included from here");
6466             &read_am_file ($path, $where);
6467             $where->pop_context;
6468         }
6469         else
6470         {
6471             # This isn't an error; it is probably a continued rule.
6472             # In fact, this is what we assume.
6473             $prev_state = IN_RULE_DEF;
6474             check_variable_expansions ($_, $where);
6475             $output_trailer .= $comment . $spacing;
6476             my $cond = new Automake::Condition @cond_stack;
6477             $output_trailer .= $cond->subst_string;
6478             $output_trailer .= $_;
6479             $comment = $spacing = '';
6480             error $where, "`#' comment at start of rule is unportable"
6481               if $_ =~ /^\t\s*\#/;
6482         }
6484         $saw_bk = $new_saw_bk;
6485         $_ = $am_file->getline;
6486     }
6488     $output_trailer .= $comment;
6490     error ($where, "trailing backslash on last line")
6491       if $saw_bk;
6493     error ($where, (@cond_stack ? "unterminated conditionals: @cond_stack"
6494                     : "too many conditionals closed in include file"))
6495       if "@saved_cond_stack" ne "@cond_stack";
6499 # define_standard_variables ()
6500 # ----------------------------
6501 # A helper for read_main_am_file which initializes configure variables
6502 # and variables from header-vars.am.
6503 sub define_standard_variables
6505   my $saved_output_vars = $output_vars;
6506   my ($comments, undef, $rules) =
6507     file_contents_internal (1, "$libdir/am/header-vars.am",
6508                             new Automake::Location);
6510   foreach my $var (sort keys %configure_vars)
6511     {
6512       &define_configure_variable ($var);
6513     }
6515   $output_vars .= $comments . $rules;
6518 # Read main am file.
6519 sub read_main_am_file
6521     my ($amfile) = @_;
6523     # This supports the strange variable tricks we are about to play.
6524     prog_error (macros_dump () . "variable defined before read_main_am_file")
6525       if (scalar (variables) > 0);
6527     # Generate copyright header for generated Makefile.in.
6528     # We do discard the output of predefined variables, handled below.
6529     $output_vars = ("# $in_file_name generated by automake "
6530                    . $VERSION . " from $am_file_name.\n");
6531     $output_vars .= '# ' . subst ('configure_input') . "\n";
6532     $output_vars .= $gen_copyright;
6534     # We want to predefine as many variables as possible.  This lets
6535     # the user set them with `+=' in Makefile.am.
6536     &define_standard_variables;
6538     # Read user file, which might override some of our values.
6539     &read_am_file ($amfile, new Automake::Location);
6544 ################################################################
6546 # $FLATTENED
6547 # &flatten ($STRING)
6548 # ------------------
6549 # Flatten the $STRING and return the result.
6550 sub flatten
6552   $_ = shift;
6554   s/\\\n//somg;
6555   s/\s+/ /g;
6556   s/^ //;
6557   s/ $//;
6559   return $_;
6563 # transform_token ($TOKEN, \%PAIRS, $KEY)
6564 # =======================================
6565 # Return the value associated to $KEY in %PAIRS, as used on $TOKEN
6566 # (which should be ?KEY? or any of the special %% requests)..
6567 sub transform_token ($$$)
6569   my ($token, $transform, $key) = @_;
6570   my $res = $transform->{$key};
6571   prog_error "Unknown key `$key' in `$token'" unless defined $res;
6572   return $res;
6576 # transform ($TOKEN, \%PAIRS)
6577 # ===========================
6578 # If ($TOKEN, $VAL) is in %PAIRS:
6579 #   - replaces %KEY% with $VAL,
6580 #   - enables/disables ?KEY? and ?!KEY?,
6581 #   - replaces %?KEY% with TRUE or FALSE.
6582 #   - replaces %KEY?IFTRUE%, %KEY:IFFALSE%, and %KEY?IFTRUE:IFFALSE% with
6583 #     IFTRUE / IFFALSE, as appropriate.
6584 sub transform ($$)
6586   my ($token, $transform) = @_;
6588   # %KEY%.
6589   # Must be before the following pattern to exclude the case
6590   # when there is neither IFTRUE nor IFFALSE.
6591   if ($token =~ /^%([\w\-]+)%$/)
6592     {
6593       return transform_token ($token, $transform, $1);
6594     }
6595   # %KEY?IFTRUE%, %KEY:IFFALSE%, and %KEY?IFTRUE:IFFALSE%.
6596   elsif ($token =~ /^%([\w\-]+)(?:\?([^?:%]+))?(?::([^?:%]+))?%$/)
6597     {
6598       return transform_token ($token, $transform, $1) ? ($2 || '') : ($3 || '');
6599     }
6600   # %?KEY%.
6601   elsif ($token =~ /^%\?([\w\-]+)%$/)
6602     {
6603       return transform_token ($token, $transform, $1) ? 'TRUE' : 'FALSE';
6604     }
6605   # ?KEY? and ?!KEY?.
6606   elsif ($token =~ /^ \? (!?) ([\w\-]+) \? $/x)
6607     {
6608       my $neg = ($1 eq '!') ? 1 : 0;
6609       my $val = transform_token ($token, $transform, $2);
6610       return (!!$val == $neg) ? '##%' : '';
6611     }
6612   else
6613     {
6614       prog_error "Unknown request format: $token";
6615     }
6619 # @PARAGRAPHS
6620 # &make_paragraphs ($MAKEFILE, [%TRANSFORM])
6621 # ------------------------------------------
6622 # Load a $MAKEFILE, apply the %TRANSFORM, and return it as a list of
6623 # paragraphs.
6624 sub make_paragraphs ($%)
6626   my ($file, %transform) = @_;
6628   # Complete %transform with global options.
6629   # Note that %transform goes last, so it overrides global options.
6630   %transform = ('CYGNUS'      => !! option 'cygnus',
6631                  'MAINTAINER-MODE'
6632                  => $seen_maint_mode ? subst ('MAINTAINER_MODE_TRUE') : '',
6634                  'XZ'          => !! option 'dist-xz',
6635                  'LZMA'        => !! option 'dist-lzma',
6636                  'BZIP2'       => !! option 'dist-bzip2',
6637                  'COMPRESS'    => !! option 'dist-tarZ',
6638                  'GZIP'        =>  ! option 'no-dist-gzip',
6639                  'SHAR'        => !! option 'dist-shar',
6640                  'ZIP'         => !! option 'dist-zip',
6642                  'INSTALL-INFO' =>  ! option 'no-installinfo',
6643                  'INSTALL-MAN'  =>  ! option 'no-installman',
6644                  'HAVE-MANS'    => !! var ('MANS'),
6645                  'CK-NEWS'      => !! option 'check-news',
6647                  'SUBDIRS'      => !! var ('SUBDIRS'),
6648                  'TOPDIR_P'     => $relative_dir eq '.',
6650                  'BUILD'    => ($seen_canonical >= AC_CANONICAL_BUILD),
6651                  'HOST'     => ($seen_canonical >= AC_CANONICAL_HOST),
6652                  'TARGET'   => ($seen_canonical >= AC_CANONICAL_TARGET),
6654                  'LIBTOOL'      => !! var ('LIBTOOL'),
6655                  'NONLIBTOOL'   => 1,
6656                  'FIRST'        => ! $transformed_files{$file},
6657                 %transform);
6659   $transformed_files{$file} = 1;
6660   $_ = $am_file_cache{$file};
6662   if (! defined $_)
6663     {
6664       verb "reading $file";
6665       # Swallow the whole file.
6666       my $fc_file = new Automake::XFile "< $file";
6667       my $saved_dollar_slash = $/;
6668       undef $/;
6669       $_ = $fc_file->getline;
6670       $/ = $saved_dollar_slash;
6671       $fc_file->close;
6673       # Remove ##-comments.
6674       # Besides we don't need more than two consecutive new-lines.
6675       s/(?:$IGNORE_PATTERN|(?<=\n\n)\n+)//gom;
6677       $am_file_cache{$file} = $_;
6678     }
6680   # Substitute Automake template tokens.
6681   s/(?: % \?? [\w\-]+ %
6682       | % [\w\-]+ (?:\?[^?:%]+)? (?::[^?:%]+)? %
6683       | \? !? [\w\-]+ \?
6684     )/transform($&, \%transform)/gex;
6685   # transform() may have added some ##%-comments to strip.
6686   # (we use `##%' instead of `##' so we can distinguish ##%##%##% from
6687   # ####### and do not remove the latter.)
6688   s/^[ \t]*(?:##%)+.*\n//gm;
6690   # Split at unescaped new lines.
6691   my @lines = split (/(?<!\\)\n/, $_);
6692   my @res;
6694   while (defined ($_ = shift @lines))
6695     {
6696       my $paragraph = $_;
6697       # If we are a rule, eat as long as we start with a tab.
6698       if (/$RULE_PATTERN/smo)
6699         {
6700           while (defined ($_ = shift @lines) && $_ =~ /^\t/)
6701             {
6702               $paragraph .= "\n$_";
6703             }
6704           unshift (@lines, $_);
6705         }
6707       # If we are a comments, eat as much comments as you can.
6708       elsif (/$COMMENT_PATTERN/smo)
6709         {
6710           while (defined ($_ = shift @lines)
6711                  && $_ =~ /$COMMENT_PATTERN/smo)
6712             {
6713               $paragraph .= "\n$_";
6714             }
6715           unshift (@lines, $_);
6716         }
6718       push @res, $paragraph;
6719     }
6721   return @res;
6726 # ($COMMENT, $VARIABLES, $RULES)
6727 # &file_contents_internal ($IS_AM, $FILE, $WHERE, [%TRANSFORM])
6728 # -------------------------------------------------------------
6729 # Return contents of a file from $libdir/am, automatically skipping
6730 # macros or rules which are already known. $IS_AM iff the caller is
6731 # reading an Automake file (as opposed to the user's Makefile.am).
6732 sub file_contents_internal ($$$%)
6734     my ($is_am, $file, $where, %transform) = @_;
6736     $where->set ($file);
6738     my $result_vars = '';
6739     my $result_rules = '';
6740     my $comment = '';
6741     my $spacing = '';
6743     # The following flags are used to track rules spanning across
6744     # multiple paragraphs.
6745     my $is_rule = 0;            # 1 if we are processing a rule.
6746     my $discard_rule = 0;       # 1 if the current rule should not be output.
6748     # We save the conditional stack on entry, and then check to make
6749     # sure it is the same on exit.  This lets us conditionally include
6750     # other files.
6751     my @saved_cond_stack = @cond_stack;
6752     my $cond = new Automake::Condition (@cond_stack);
6754     foreach (make_paragraphs ($file, %transform))
6755     {
6756         # FIXME: no line number available.
6757         $where->set ($file);
6759         # Sanity checks.
6760         error $where, "blank line following trailing backslash:\n$_"
6761           if /\\$/;
6762         error $where, "comment following trailing backslash:\n$_"
6763           if /\\#/;
6765         if (/^$/)
6766         {
6767             $is_rule = 0;
6768             # Stick empty line before the incoming macro or rule.
6769             $spacing = "\n";
6770         }
6771         elsif (/$COMMENT_PATTERN/mso)
6772         {
6773             $is_rule = 0;
6774             # Stick comments before the incoming macro or rule.
6775             $comment = "$_\n";
6776         }
6778         # Handle inclusion of other files.
6779         elsif (/$INCLUDE_PATTERN/o)
6780         {
6781             if ($cond != FALSE)
6782               {
6783                 my $file = ($is_am ? "$libdir/am/" : '') . $1;
6784                 $where->push_context ("`$file' included from here");
6785                 # N-ary `.=' fails.
6786                 my ($com, $vars, $rules)
6787                   = file_contents_internal ($is_am, $file, $where, %transform);
6788                 $where->pop_context;
6789                 $comment .= $com;
6790                 $result_vars .= $vars;
6791                 $result_rules .= $rules;
6792               }
6793         }
6795         # Handling the conditionals.
6796         elsif (/$IF_PATTERN/o)
6797           {
6798             $cond = cond_stack_if ($1, $2, $file);
6799           }
6800         elsif (/$ELSE_PATTERN/o)
6801           {
6802             $cond = cond_stack_else ($1, $2, $file);
6803           }
6804         elsif (/$ENDIF_PATTERN/o)
6805           {
6806             $cond = cond_stack_endif ($1, $2, $file);
6807           }
6809         # Handling rules.
6810         elsif (/$RULE_PATTERN/mso)
6811         {
6812           $is_rule = 1;
6813           $discard_rule = 0;
6814           # Separate relationship from optional actions: the first
6815           # `new-line tab" not preceded by backslash (continuation
6816           # line).
6817           my $paragraph = $_;
6818           /^(.*?)(?:(?<!\\)\n(\t.*))?$/s;
6819           my ($relationship, $actions) = ($1, $2 || '');
6821           # Separate targets from dependencies: the first colon.
6822           $relationship =~ /^([^:]+\S+) *: *(.*)$/som;
6823           my ($targets, $dependencies) = ($1, $2);
6824           # Remove the escaped new lines.
6825           # I don't know why, but I have to use a tmp $flat_deps.
6826           my $flat_deps = &flatten ($dependencies);
6827           my @deps = split (' ', $flat_deps);
6829           foreach (split (' ', $targets))
6830             {
6831               # FIXME: 1. We are not robust to people defining several targets
6832               # at once, only some of them being in %dependencies.  The
6833               # actions from the targets in %dependencies are usually generated
6834               # from the content of %actions, but if some targets in $targets
6835               # are not in %dependencies the ELSE branch will output
6836               # a rule for all $targets (i.e. the targets which are both
6837               # in %dependencies and $targets will have two rules).
6839               # FIXME: 2. The logic here is not able to output a
6840               # multi-paragraph rule several time (e.g. for each condition
6841               # it is defined for) because it only knows the first paragraph.
6843               # FIXME: 3. We are not robust to people defining a subset
6844               # of a previously defined "multiple-target" rule.  E.g.
6845               # `foo:' after `foo bar:'.
6847               # Output only if not in FALSE.
6848               if (defined $dependencies{$_} && $cond != FALSE)
6849                 {
6850                   &depend ($_, @deps);
6851                   register_action ($_, $actions);
6852                 }
6853               else
6854                 {
6855                   # Free-lance dependency.  Output the rule for all the
6856                   # targets instead of one by one.
6857                   my @undefined_conds =
6858                     Automake::Rule::define ($targets, $file,
6859                                             $is_am ? RULE_AUTOMAKE : RULE_USER,
6860                                             $cond, $where);
6861                   for my $undefined_cond (@undefined_conds)
6862                     {
6863                       my $condparagraph = $paragraph;
6864                       $condparagraph =~ s/^/$undefined_cond->subst_string/gme;
6865                       $result_rules .= "$spacing$comment$condparagraph\n";
6866                     }
6867                   if (scalar @undefined_conds == 0)
6868                     {
6869                       # Remember to discard next paragraphs
6870                       # if they belong to this rule.
6871                       # (but see also FIXME: #2 above.)
6872                       $discard_rule = 1;
6873                     }
6874                   $comment = $spacing = '';
6875                   last;
6876                 }
6877             }
6878         }
6880         elsif (/$ASSIGNMENT_PATTERN/mso)
6881         {
6882             my ($var, $type, $val) = ($1, $2, $3);
6883             error $where, "variable `$var' with trailing backslash"
6884               if /\\$/;
6886             $is_rule = 0;
6888             Automake::Variable::define ($var,
6889                                         $is_am ? VAR_AUTOMAKE : VAR_MAKEFILE,
6890                                         $type, $cond, $val, $comment, $where,
6891                                         VAR_ASIS)
6892               if $cond != FALSE;
6894             $comment = $spacing = '';
6895         }
6896         else
6897         {
6898             # This isn't an error; it is probably some tokens which
6899             # configure is supposed to replace, such as `@SET-MAKE@',
6900             # or some part of a rule cut by an if/endif.
6901             if (! $cond->false && ! ($is_rule && $discard_rule))
6902               {
6903                 s/^/$cond->subst_string/gme;
6904                 $result_rules .= "$spacing$comment$_\n";
6905               }
6906             $comment = $spacing = '';
6907         }
6908     }
6910     error ($where, @cond_stack ?
6911            "unterminated conditionals: @cond_stack" :
6912            "too many conditionals closed in include file")
6913       if "@saved_cond_stack" ne "@cond_stack";
6915     return ($comment, $result_vars, $result_rules);
6919 # $CONTENTS
6920 # &file_contents ($BASENAME, $WHERE, [%TRANSFORM])
6921 # ------------------------------------------------
6922 # Return contents of a file from $libdir/am, automatically skipping
6923 # macros or rules which are already known.
6924 sub file_contents ($$%)
6926     my ($basename, $where, %transform) = @_;
6927     my ($comments, $variables, $rules) =
6928       file_contents_internal (1, "$libdir/am/$basename.am", $where,
6929                               %transform);
6930     return "$comments$variables$rules";
6934 # @PREFIX
6935 # &am_primary_prefixes ($PRIMARY, $CAN_DIST, @PREFIXES)
6936 # -----------------------------------------------------
6937 # Find all variable prefixes that are used for install directories.  A
6938 # prefix `zar' qualifies iff:
6940 # * `zardir' is a variable.
6941 # * `zar_PRIMARY' is a variable.
6943 # As a side effect, it looks for misspellings.  It is an error to have
6944 # a variable ending in a "reserved" suffix whose prefix is unknown, e.g.
6945 # "bni_PROGRAMS".  However, unusual prefixes are allowed if a variable
6946 # of the same name (with "dir" appended) exists.  For instance, if the
6947 # variable "zardir" is defined, then "zar_PROGRAMS" becomes valid.
6948 # This is to provide a little extra flexibility in those cases which
6949 # need it.
6950 sub am_primary_prefixes ($$@)
6952   my ($primary, $can_dist, @prefixes) = @_;
6954   local $_;
6955   my %valid = map { $_ => 0 } @prefixes;
6956   $valid{'EXTRA'} = 0;
6957   foreach my $var (variables $primary)
6958     {
6959       # Automake is allowed to define variables that look like primaries
6960       # but which aren't.  E.g. INSTALL_sh_DATA.
6961       # Autoconf can also define variables like INSTALL_DATA, so
6962       # ignore all configure variables (at least those which are not
6963       # redefined in Makefile.am).
6964       # FIXME: We should make sure that these variables are not
6965       # conditionally defined (or else adjust the condition below).
6966       my $def = $var->def (TRUE);
6967       next if $def && $def->owner != VAR_MAKEFILE;
6969       my $varname = $var->name;
6971       if ($varname =~ /^(nobase_)?(dist_|nodist_)?(.*)_[[:alnum:]]+$/)
6972         {
6973           my ($base, $dist, $X) = ($1 || '', $2 || '', $3 || '');
6974           if ($dist ne '' && ! $can_dist)
6975             {
6976               err_var ($var,
6977                        "invalid variable `$varname': `dist' is forbidden");
6978             }
6979           # Standard directories must be explicitly allowed.
6980           elsif (! defined $valid{$X} && exists $standard_prefix{$X})
6981             {
6982               err_var ($var,
6983                        "`${X}dir' is not a legitimate directory " .
6984                        "for `$primary'");
6985             }
6986           # A not explicitly valid directory is allowed if Xdir is defined.
6987           elsif (! defined $valid{$X} &&
6988                  $var->requires_variables ("`$varname' is used", "${X}dir"))
6989             {
6990               # Nothing to do.  Any error message has been output
6991               # by $var->requires_variables.
6992             }
6993           else
6994             {
6995               # Ensure all extended prefixes are actually used.
6996               $valid{"$base$dist$X"} = 1;
6997             }
6998         }
6999       else
7000         {
7001           prog_error "unexpected variable name: $varname";
7002         }
7003     }
7005   # Return only those which are actually defined.
7006   return sort grep { var ($_ . '_' . $primary) } keys %valid;
7010 # Handle `where_HOW' variable magic.  Does all lookups, generates
7011 # install code, and possibly generates code to define the primary
7012 # variable.  The first argument is the name of the .am file to munge,
7013 # the second argument is the primary variable (e.g. HEADERS), and all
7014 # subsequent arguments are possible installation locations.
7016 # Returns list of [$location, $value] pairs, where
7017 # $value's are the values in all where_HOW variable, and $location
7018 # there associated location (the place here their parent variables were
7019 # defined).
7021 # FIXME: this should be rewritten to be cleaner.  It should be broken
7022 # up into multiple functions.
7024 # Usage is: am_install_var (OPTION..., file, HOW, where...)
7025 sub am_install_var
7027   my (@args) = @_;
7029   my $do_require = 1;
7030   my $can_dist = 0;
7031   my $default_dist = 0;
7032   while (@args)
7033     {
7034       if ($args[0] eq '-noextra')
7035         {
7036           $do_require = 0;
7037         }
7038       elsif ($args[0] eq '-candist')
7039         {
7040           $can_dist = 1;
7041         }
7042       elsif ($args[0] eq '-defaultdist')
7043         {
7044           $default_dist = 1;
7045           $can_dist = 1;
7046         }
7047       elsif ($args[0] !~ /^-/)
7048         {
7049           last;
7050         }
7051       shift (@args);
7052     }
7054   my ($file, $primary, @prefix) = @args;
7056   # Now that configure substitutions are allowed in where_HOW
7057   # variables, it is an error to actually define the primary.  We
7058   # allow `JAVA', as it is customarily used to mean the Java
7059   # interpreter.  This is but one of several Java hacks.  Similarly,
7060   # `PYTHON' is customarily used to mean the Python interpreter.
7061   reject_var $primary, "`$primary' is an anachronism"
7062     unless $primary eq 'JAVA' || $primary eq 'PYTHON';
7064   # Get the prefixes which are valid and actually used.
7065   @prefix = am_primary_prefixes ($primary, $can_dist, @prefix);
7067   # If a primary includes a configure substitution, then the EXTRA_
7068   # form is required.  Otherwise we can't properly do our job.
7069   my $require_extra;
7071   my @used = ();
7072   my @result = ();
7074   foreach my $X (@prefix)
7075     {
7076       my $nodir_name = $X;
7077       my $one_name = $X . '_' . $primary;
7078       my $one_var = var $one_name;
7080       my $strip_subdir = 1;
7081       # If subdir prefix should be preserved, do so.
7082       if ($nodir_name =~ /^nobase_/)
7083         {
7084           $strip_subdir = 0;
7085           $nodir_name =~ s/^nobase_//;
7086         }
7088       # If files should be distributed, do so.
7089       my $dist_p = 0;
7090       if ($can_dist)
7091         {
7092           $dist_p = (($default_dist && $nodir_name !~ /^nodist_/)
7093                      || (! $default_dist && $nodir_name =~ /^dist_/));
7094           $nodir_name =~ s/^(dist|nodist)_//;
7095         }
7098       # Use the location of the currently processed variable.
7099       # We are not processing a particular condition, so pick the first
7100       # available.
7101       my $tmpcond = $one_var->conditions->one_cond;
7102       my $where = $one_var->rdef ($tmpcond)->location->clone;
7104       # Append actual contents of where_PRIMARY variable to
7105       # @result, skipping @substitutions@.
7106       foreach my $locvals ($one_var->value_as_list_recursive (location => 1))
7107         {
7108           my ($loc, $value) = @$locvals;
7109           # Skip configure substitutions.
7110           if ($value =~ /^\@.*\@$/)
7111             {
7112               if ($nodir_name eq 'EXTRA')
7113                 {
7114                   error ($where,
7115                          "`$one_name' contains configure substitution, "
7116                          . "but shouldn't");
7117                 }
7118               # Check here to make sure variables defined in
7119               # configure.ac do not imply that EXTRA_PRIMARY
7120               # must be defined.
7121               elsif (! defined $configure_vars{$one_name})
7122                 {
7123                   $require_extra = $one_name
7124                     if $do_require;
7125                 }
7126             }
7127           else
7128             {
7129               push (@result, $locvals);
7130             }
7131         }
7132       # A blatant hack: we rewrite each _PROGRAMS primary to include
7133       # EXEEXT.
7134       append_exeext { 1 } $one_name
7135         if $primary eq 'PROGRAMS';
7136       # "EXTRA" shouldn't be used when generating clean targets,
7137       # all, or install targets.  We used to warn if EXTRA_FOO was
7138       # defined uselessly, but this was annoying.
7139       next
7140         if $nodir_name eq 'EXTRA';
7142       if ($nodir_name eq 'check')
7143         {
7144           push (@check, '$(' . $one_name . ')');
7145         }
7146       else
7147         {
7148           push (@used, '$(' . $one_name . ')');
7149         }
7151       # Is this to be installed?
7152       my $install_p = $nodir_name ne 'noinst' && $nodir_name ne 'check';
7154       # If so, with install-exec? (or install-data?).
7155       my $exec_p = ($nodir_name =~ /$EXEC_DIR_PATTERN/o);
7157       my $check_options_p = $install_p && !! option 'std-options';
7159       # Use the location of the currently processed variable as context.
7160       $where->push_context ("while processing `$one_name'");
7162       # The variable containing all files to distribute.
7163       my $distvar = "\$($one_name)";
7164       $distvar = shadow_unconditionally ($one_name, $where)
7165         if ($dist_p && $one_var->has_conditional_contents);
7167       # Singular form of $PRIMARY.
7168       (my $one_primary = $primary) =~ s/S$//;
7169       $output_rules .= &file_contents ($file, $where,
7170                                        PRIMARY     => $primary,
7171                                        ONE_PRIMARY => $one_primary,
7172                                        DIR         => $X,
7173                                        NDIR        => $nodir_name,
7174                                        BASE        => $strip_subdir,
7176                                        EXEC      => $exec_p,
7177                                        INSTALL   => $install_p,
7178                                        DIST      => $dist_p,
7179                                        DISTVAR   => $distvar,
7180                                        'CK-OPTS' => $check_options_p);
7181     }
7183   # The JAVA variable is used as the name of the Java interpreter.
7184   # The PYTHON variable is used as the name of the Python interpreter.
7185   if (@used && $primary ne 'JAVA' && $primary ne 'PYTHON')
7186     {
7187       # Define it.
7188       define_pretty_variable ($primary, TRUE, INTERNAL, @used);
7189       $output_vars .= "\n";
7190     }
7192   err_var ($require_extra,
7193            "`$require_extra' contains configure substitution,\n"
7194            . "but `EXTRA_$primary' not defined")
7195     if ($require_extra && ! var ('EXTRA_' . $primary));
7197   # Push here because PRIMARY might be configure time determined.
7198   push (@all, '$(' . $primary . ')')
7199     if @used && $primary ne 'JAVA' && $primary ne 'PYTHON';
7201   # Make the result unique.  This lets the user use conditionals in
7202   # a natural way, but still lets us program lazily -- we don't have
7203   # to worry about handling a particular object more than once.
7204   # We will keep only one location per object.
7205   my %result = ();
7206   for my $pair (@result)
7207     {
7208       my ($loc, $val) = @$pair;
7209       $result{$val} = $loc;
7210     }
7211   my @l = sort keys %result;
7212   return map { [$result{$_}->clone, $_] } @l;
7216 ################################################################
7218 # Each key in this hash is the name of a directory holding a
7219 # Makefile.in.  These variables are local to `is_make_dir'.
7220 my %make_dirs = ();
7221 my $make_dirs_set = 0;
7223 sub is_make_dir
7225     my ($dir) = @_;
7226     if (! $make_dirs_set)
7227     {
7228         foreach my $iter (@configure_input_files)
7229         {
7230             $make_dirs{dirname ($iter)} = 1;
7231         }
7232         # We also want to notice Makefile.in's.
7233         foreach my $iter (@other_input_files)
7234         {
7235             if ($iter =~ /Makefile\.in$/)
7236             {
7237                 $make_dirs{dirname ($iter)} = 1;
7238             }
7239         }
7240         $make_dirs_set = 1;
7241     }
7242     return defined $make_dirs{$dir};
7245 ################################################################
7247 # Find the aux dir.  This should match the algorithm used by
7248 # ./configure. (See the Autoconf documentation for for
7249 # AC_CONFIG_AUX_DIR.)
7250 sub locate_aux_dir ()
7252   if (! $config_aux_dir_set_in_configure_ac)
7253     {
7254       # The default auxiliary directory is the first
7255       # of ., .., or ../.. that contains install-sh.
7256       # Assume . if install-sh doesn't exist yet.
7257       for my $dir (qw (. .. ../..))
7258         {
7259           if (-f "$dir/install-sh")
7260             {
7261               $config_aux_dir = $dir;
7262               last;
7263             }
7264         }
7265       $config_aux_dir = '.' unless $config_aux_dir;
7266     }
7267   # Avoid unsightly '/.'s.
7268   $am_config_aux_dir =
7269     '$(top_srcdir)' . ($config_aux_dir eq '.' ? "" : "/$config_aux_dir");
7270   $am_config_aux_dir =~ s,/*$,,;
7274 # &maybe_push_required_file ($DIR, $FILE, $FULLFILE)
7275 # --------------------------------------------------
7276 # See if we want to push this file onto dist_common.  This function
7277 # encodes the rules for deciding when to do so.
7278 sub maybe_push_required_file
7280   my ($dir, $file, $fullfile) = @_;
7282   if ($dir eq $relative_dir)
7283     {
7284       push_dist_common ($file);
7285       return 1;
7286     }
7287   elsif ($relative_dir eq '.' && ! &is_make_dir ($dir))
7288     {
7289       # If we are doing the topmost directory, and the file is in a
7290       # subdir which does not have a Makefile, then we distribute it
7291       # here.
7293       # If a required file is above the source tree, it is important
7294       # to prefix it with `$(srcdir)' so that no VPATH search is
7295       # performed.  Otherwise problems occur with Make implementations
7296       # that rewrite and simplify rules whose dependencies are found in a
7297       # VPATH location.  Here is an example with OSF1/Tru64 Make.
7298       #
7299       #   % cat Makefile
7300       #   VPATH = sub
7301       #   distdir: ../a
7302       #           echo ../a
7303       #   % ls
7304       #   Makefile a
7305       #   % make
7306       #   echo a
7307       #   a
7308       #
7309       # Dependency `../a' was found in `sub/../a', but this make
7310       # implementation simplified it as `a'.  (Note that the sub/
7311       # directory does not even exist.)
7312       #
7313       # This kind of VPATH rewriting seems hard to cancel.  The
7314       # distdir.am hack against VPATH rewriting works only when no
7315       # simplification is done, i.e., for dependencies which are in
7316       # subdirectories, not in enclosing directories.  Hence, in
7317       # the latter case we use a full path to make sure no VPATH
7318       # search occurs.
7319       $fullfile = '$(srcdir)/' . $fullfile
7320         if $dir =~ m,^\.\.(?:$|/),;
7322       push_dist_common ($fullfile);
7323       return 1;
7324     }
7325   return 0;
7329 # If a file name appears as a key in this hash, then it has already
7330 # been checked for.  This allows us not to report the same error more
7331 # than once.
7332 my %required_file_not_found = ();
7334 # &require_file_internal ($WHERE, $MYSTRICT, $DIRECTORY, @FILES)
7335 # --------------------------------------------------------------
7336 # Verify that the file must exist in $DIRECTORY, or install it.
7337 # $MYSTRICT is the strictness level at which this file becomes required.
7338 sub require_file_internal ($$$@)
7340   my ($where, $mystrict, $dir, @files) = @_;
7342   foreach my $file (@files)
7343     {
7344       my $fullfile = "$dir/$file";
7345       my $found_it = 0;
7346       my $dangling_sym = 0;
7348       if (-l $fullfile && ! -f $fullfile)
7349         {
7350           $dangling_sym = 1;
7351         }
7352       elsif (dir_has_case_matching_file ($dir, $file))
7353         {
7354           $found_it = 1;
7355           maybe_push_required_file ($dir, $file, $fullfile);
7356         }
7358       # `--force-missing' only has an effect if `--add-missing' is
7359       # specified.
7360       if ($found_it && (! $add_missing || ! $force_missing))
7361         {
7362           next;
7363         }
7364       else
7365         {
7366           # If we've already looked for it, we're done.  You might
7367           # wonder why we don't do this before searching for the
7368           # file.  If we do that, then something like
7369           # AC_OUTPUT(subdir/foo foo) will fail to put foo.in into
7370           # DIST_COMMON.
7371           if (! $found_it)
7372             {
7373               next if defined $required_file_not_found{$fullfile};
7374               $required_file_not_found{$fullfile} = 1;
7375             }
7377           if ($strictness >= $mystrict)
7378             {
7379               if ($dangling_sym && $add_missing)
7380                 {
7381                   unlink ($fullfile);
7382                 }
7384               my $trailer = '';
7385               my $trailer2 = '';
7386               my $suppress = 0;
7388               # Only install missing files according to our desired
7389               # strictness level.
7390               my $message = "required file `$fullfile' not found";
7391               if ($add_missing)
7392                 {
7393                   if (-f "$libdir/$file")
7394                     {
7395                       $suppress = 1;
7397                       # Install the missing file.  Symlink if we
7398                       # can, copy if we must.  Note: delete the file
7399                       # first, in case it is a dangling symlink.
7400                       $message = "installing `$fullfile'";
7402                       # The license file should not be volatile.
7403                       if ($file eq "COPYING")
7404                         {
7405                           $message .= " using GNU General Public License v3 file";
7406                           $trailer2 = "\n    Consider adding the COPYING file"
7407                                     . " to the version control system"
7408                                     . "\n    for your code, to avoid questions"
7409                                     . " about which license your project uses.";
7410                         }
7412                       # Windows Perl will hang if we try to delete a
7413                       # file that doesn't exist.
7414                       unlink ($fullfile) if -f $fullfile;
7415                       if ($symlink_exists && ! $copy_missing)
7416                         {
7417                           if (! symlink ("$libdir/$file", $fullfile))
7418                             {
7419                               $suppress = 0;
7420                               $trailer = "; error while making link: $!";
7421                             }
7422                         }
7423                       elsif (system ('cp', "$libdir/$file", $fullfile))
7424                         {
7425                           $suppress = 0;
7426                           $trailer = "\n    error while copying";
7427                         }
7428                       set_dir_cache_file ($dir, $file);
7429                     }
7431                   if (! maybe_push_required_file (dirname ($fullfile),
7432                                                   $file, $fullfile))
7433                     {
7434                       if (! $found_it && ! $automake_will_process_aux_dir)
7435                         {
7436                           # We have added the file but could not push it
7437                           # into DIST_COMMON, probably because this is
7438                           # an auxiliary file and we are not processing
7439                           # the top level Makefile.  Furthermore Automake
7440                           # hasn't been asked to create the Makefile.in
7441                           # that distributes the aux dir files.
7442                           error ($where, 'Please make a full run of automake'
7443                                  . " so $fullfile gets distributed.");
7444                         }
7445                     }
7446                 }
7447               else
7448                 {
7449                   $trailer = "\n  `automake --add-missing' can install `$file'"
7450                     if -f "$libdir/$file";
7451                 }
7453               # If --force-missing was specified, and we have
7454               # actually found the file, then do nothing.
7455               next
7456                 if $found_it && $force_missing;
7458               # If we couldn't install the file, but it is a target in
7459               # the Makefile, don't print anything.  This allows files
7460               # like README, AUTHORS, or THANKS to be generated.
7461               next
7462                 if !$suppress && rule $file;
7464               msg ($suppress ? 'note' : 'error', $where, "$message$trailer$trailer2");
7465             }
7466         }
7467     }
7470 # &require_file ($WHERE, $MYSTRICT, @FILES)
7471 # -----------------------------------------
7472 sub require_file ($$@)
7474     my ($where, $mystrict, @files) = @_;
7475     require_file_internal ($where, $mystrict, $relative_dir, @files);
7478 # &require_file_with_macro ($COND, $MACRO, $MYSTRICT, @FILES)
7479 # -----------------------------------------------------------
7480 sub require_file_with_macro ($$$@)
7482     my ($cond, $macro, $mystrict, @files) = @_;
7483     $macro = rvar ($macro) unless ref $macro;
7484     require_file ($macro->rdef ($cond)->location, $mystrict, @files);
7487 # &require_libsource_with_macro ($COND, $MACRO, $MYSTRICT, @FILES)
7488 # ----------------------------------------------------------------
7489 # Require an AC_LIBSOURCEd file.  If AC_CONFIG_LIBOBJ_DIR was called, it
7490 # must be in that directory.  Otherwise expect it in the current directory.
7491 sub require_libsource_with_macro ($$$@)
7493     my ($cond, $macro, $mystrict, @files) = @_;
7494     $macro = rvar ($macro) unless ref $macro;
7495     if ($config_libobj_dir)
7496       {
7497         require_file_internal ($macro->rdef ($cond)->location, $mystrict,
7498                                $config_libobj_dir, @files);
7499       }
7500     else
7501       {
7502         require_file ($macro->rdef ($cond)->location, $mystrict, @files);
7503       }
7506 # Queue to push require_conf_file requirements to.
7507 my $required_conf_file_queue;
7509 # &queue_required_conf_file ($QUEUE, $KEY, $DIR, $WHERE, $MYSTRICT, @FILES)
7510 # -------------------------------------------------------------------------
7511 sub queue_required_conf_file ($$$$@)
7513     my ($queue, $key, $dir, $where, $mystrict, @files) = @_;
7514     my @serial_loc;
7515     if (ref $where)
7516       {
7517         @serial_loc = (QUEUE_LOCATION, $where->serialize ());
7518       }
7519     else
7520       {
7521         @serial_loc = (QUEUE_STRING, $where);
7522       }
7523     $queue->enqueue ($key, $dir, @serial_loc, $mystrict, 0 + @files, @files);
7526 # &require_queued_conf_file ($QUEUE)
7527 # ----------------------------------
7528 sub require_queued_conf_file ($)
7530     my ($queue) = @_;
7531     my $where;
7532     my $dir = $queue->dequeue ();
7533     my $loc_key = $queue->dequeue ();
7534     if ($loc_key eq QUEUE_LOCATION)
7535       {
7536         $where = Automake::Location::deserialize ($queue);
7537       }
7538     elsif ($loc_key eq QUEUE_STRING)
7539       {
7540         $where = $queue->dequeue ();
7541       }
7542     else
7543       {
7544         prog_error "unexpected key $loc_key";
7545       }
7546     my $mystrict = $queue->dequeue ();
7547     my $nfiles = $queue->dequeue ();
7548     my @files;
7549     push @files, $queue->dequeue ()
7550       foreach (1 .. $nfiles);
7552     # Dequeuing happens outside of per-makefile context, so we have to
7553     # set the variables used by require_file_internal and the functions
7554     # it calls.  Gross!
7555     $relative_dir = $dir;
7556     require_file_internal ($where, $mystrict, $config_aux_dir, @files);
7559 # &require_conf_file ($WHERE, $MYSTRICT, @FILES)
7560 # ----------------------------------------------
7561 # Looks in configuration path, as specified by AC_CONFIG_AUX_DIR;
7562 # worker threads may queue up the action to be serialized by the master.
7564 # FIXME: this seriously relies on the semantics of require_file_internal
7565 # and maybe_push_required_file, in that we exploit the fact that only the
7566 # contents of the last handled output file may be impacted (which in turn
7567 # is dealt with by the master thread).
7568 sub require_conf_file ($$@)
7570     my ($where, $mystrict, @files) = @_;
7571     if (defined $required_conf_file_queue)
7572       {
7573         queue_required_conf_file ($required_conf_file_queue, QUEUE_CONF_FILE,
7574                                   $relative_dir, $where, $mystrict, @files);
7575       }
7576     else
7577       {
7578         require_file_internal ($where, $mystrict, $config_aux_dir, @files);
7579       }
7583 # &require_conf_file_with_macro ($COND, $MACRO, $MYSTRICT, @FILES)
7584 # ----------------------------------------------------------------
7585 sub require_conf_file_with_macro ($$$@)
7587     my ($cond, $macro, $mystrict, @files) = @_;
7588     require_conf_file (rvar ($macro)->rdef ($cond)->location,
7589                        $mystrict, @files);
7592 ################################################################
7594 # &require_build_directory ($DIRECTORY)
7595 # ------------------------------------
7596 # Emit rules to create $DIRECTORY if needed, and return
7597 # the file that any target requiring this directory should be made
7598 # dependent upon.
7599 # We don't want to emit the rule twice, and want to reuse it
7600 # for directories with equivalent names (e.g., `foo/bar' and `./foo//bar').
7601 sub require_build_directory ($)
7603   my $directory = shift;
7605   return $directory_map{$directory} if exists $directory_map{$directory};
7607   my $cdir = File::Spec->canonpath ($directory);
7609   if (exists $directory_map{$cdir})
7610     {
7611       my $stamp = $directory_map{$cdir};
7612       $directory_map{$directory} = $stamp;
7613       return $stamp;
7614     }
7616   my $dirstamp = "$cdir/\$(am__dirstamp)";
7618   $directory_map{$directory} = $dirstamp;
7619   $directory_map{$cdir} = $dirstamp;
7621   # Set a variable for the dirstamp basename.
7622   define_pretty_variable ('am__dirstamp', TRUE, INTERNAL,
7623                           '$(am__leading_dot)dirstamp');
7625   # Directory must be removed by `make distclean'.
7626   $clean_files{$dirstamp} = DIST_CLEAN;
7628   $output_rules .= ("$dirstamp:\n"
7629                     . "\t\@\$(MKDIR_P) $directory\n"
7630                     . "\t\@: > $dirstamp\n");
7632   return $dirstamp;
7635 # &require_build_directory_maybe ($FILE)
7636 # --------------------------------------
7637 # If $FILE lies in a subdirectory, emit a rule to create this
7638 # directory and return the file that $FILE should be made
7639 # dependent upon.  Otherwise, just return the empty string.
7640 sub require_build_directory_maybe ($)
7642     my $file = shift;
7643     my $directory = dirname ($file);
7645     if ($directory ne '.')
7646     {
7647         return require_build_directory ($directory);
7648     }
7649     else
7650     {
7651         return '';
7652     }
7655 ################################################################
7657 # Push a list of files onto dist_common.
7658 sub push_dist_common
7660   prog_error "push_dist_common run after handle_dist"
7661     if $handle_dist_run;
7662   Automake::Variable::define ('DIST_COMMON', VAR_AUTOMAKE, '+', TRUE, "@_",
7663                               '', INTERNAL, VAR_PRETTY);
7667 ################################################################
7669 # generate_makefile ($MAKEFILE_AM, $MAKEFILE_IN)
7670 # ----------------------------------------------
7671 # Generate a Makefile.in given the name of the corresponding Makefile and
7672 # the name of the file output by config.status.
7673 sub generate_makefile ($$)
7675   my ($makefile_am, $makefile_in) = @_;
7677   # Reset all the Makefile.am related variables.
7678   initialize_per_input;
7680   # AUTOMAKE_OPTIONS can contains -W flags to disable or enable
7681   # warnings for this file.  So hold any warning issued before
7682   # we have processed AUTOMAKE_OPTIONS.
7683   buffer_messages ('warning');
7685   # Name of input file ("Makefile.am") and output file
7686   # ("Makefile.in").  These have no directory components.
7687   $am_file_name = basename ($makefile_am);
7688   $in_file_name = basename ($makefile_in);
7690   # $OUTPUT is encoded.  If it contains a ":" then the first element
7691   # is the real output file, and all remaining elements are input
7692   # files.  We don't scan or otherwise deal with these input files,
7693   # other than to mark them as dependencies.  See
7694   # &scan_autoconf_files for details.
7695   my ($makefile, @inputs) = split (/:/, $output_files{$makefile_in});
7697   $relative_dir = dirname ($makefile);
7698   $am_relative_dir = dirname ($makefile_am);
7699   $topsrcdir = backname ($relative_dir);
7701   read_main_am_file ($makefile_am);
7702   if (handle_options)
7703     {
7704       # Process buffered warnings.
7705       flush_messages;
7706       # Fatal error.  Just return, so we can continue with next file.
7707       return;
7708     }
7709   # Process buffered warnings.
7710   flush_messages;
7712   # There are a few install-related variables that you should not define.
7713   foreach my $var ('PRE_INSTALL', 'POST_INSTALL', 'NORMAL_INSTALL')
7714     {
7715       my $v = var $var;
7716       if ($v)
7717         {
7718           my $def = $v->def (TRUE);
7719           prog_error "$var not defined in condition TRUE"
7720             unless $def;
7721           reject_var $var, "`$var' should not be defined"
7722             if $def->owner != VAR_AUTOMAKE;
7723         }
7724     }
7726   # Catch some obsolete variables.
7727   msg_var ('obsolete', 'INCLUDES',
7728            "`INCLUDES' is the old name for `AM_CPPFLAGS' (or `*_CPPFLAGS')")
7729     if var ('INCLUDES');
7731   # Must do this after reading .am file.
7732   define_variable ('subdir', $relative_dir, INTERNAL);
7734   # If DIST_SUBDIRS is defined, make sure SUBDIRS is, so that
7735   # recursive rules are enabled.
7736   define_pretty_variable ('SUBDIRS', TRUE, INTERNAL, '')
7737     if var 'DIST_SUBDIRS' && ! var 'SUBDIRS';
7739   # Check first, because we might modify some state.
7740   check_cygnus;
7741   check_gnu_standards;
7742   check_gnits_standards;
7744   handle_configure ($makefile_am, $makefile_in, $makefile, @inputs);
7745   handle_gettext;
7746   handle_libraries;
7747   handle_ltlibraries;
7748   handle_programs;
7749   handle_scripts;
7751   # These must be run after all the sources are scanned.  They
7752   # use variables defined by &handle_libraries, &handle_ltlibraries,
7753   # or &handle_programs.
7754   handle_compile;
7755   handle_languages;
7756   handle_libtool;
7758   # Variables used by distdir.am and tags.am.
7759   define_pretty_variable ('SOURCES', TRUE, INTERNAL, @sources);
7760   if (! option 'no-dist')
7761     {
7762       define_pretty_variable ('DIST_SOURCES', TRUE, INTERNAL, @dist_sources);
7763     }
7765   handle_multilib;
7766   handle_texinfo;
7767   handle_emacs_lisp;
7768   handle_python;
7769   handle_java;
7770   handle_man_pages;
7771   handle_data;
7772   handle_headers;
7773   handle_subdirs;
7774   handle_tags;
7775   handle_minor_options;
7776   # Must come after handle_programs so that %known_programs is up-to-date.
7777   handle_tests;
7779   # This must come after most other rules.
7780   handle_dist;
7782   handle_footer;
7783   do_check_merge_target;
7784   handle_all ($makefile);
7786   # FIXME: Gross!
7787   if (var ('lib_LTLIBRARIES') && var ('bin_PROGRAMS'))
7788     {
7789       $output_rules .= "install-binPROGRAMS: install-libLTLIBRARIES\n\n";
7790     }
7791   if (var ('nobase_lib_LTLIBRARIES') && var ('bin_PROGRAMS'))
7792     {
7793       $output_rules .= "install-binPROGRAMS: install-nobase_libLTLIBRARIES\n\n";
7794     }
7796   handle_install;
7797   handle_clean ($makefile);
7798   handle_factored_dependencies;
7800   # Comes last, because all the above procedures may have
7801   # defined or overridden variables.
7802   $output_vars .= output_variables;
7804   check_typos;
7806   my ($out_file) = $output_directory . '/' . $makefile_in;
7808   if ($exit_code != 0)
7809     {
7810       verb "not writing $out_file because of earlier errors";
7811       return;
7812     }
7814   if (! -d ($output_directory . '/' . $am_relative_dir))
7815     {
7816       mkdir ($output_directory . '/' . $am_relative_dir, 0755);
7817     }
7819   # We make sure that `all:' is the first target.
7820   my $output =
7821     "$output_vars$output_all$output_header$output_rules$output_trailer";
7823   # Decide whether we must update the output file or not.
7824   # We have to update in the following situations.
7825   #  * $force_generation is set.
7826   #  * any of the output dependencies is younger than the output
7827   #  * the contents of the output is different (this can happen
7828   #    if the project has been populated with a file listed in
7829   #    @common_files since the last run).
7830   # Output's dependencies are split in two sets:
7831   #  * dependencies which are also configure dependencies
7832   #    These do not change between each Makefile.am
7833   #  * other dependencies, specific to the Makefile.am being processed
7834   #    (such as the Makefile.am itself, or any Makefile fragment
7835   #    it includes).
7836   my $timestamp = mtime $out_file;
7837   if (! $force_generation
7838       && $configure_deps_greatest_timestamp < $timestamp
7839       && $output_deps_greatest_timestamp < $timestamp
7840       && $output eq contents ($out_file))
7841     {
7842       verb "$out_file unchanged";
7843       # No need to update.
7844       return;
7845     }
7847   if (-e $out_file)
7848     {
7849       unlink ($out_file)
7850         or fatal "cannot remove $out_file: $!\n";
7851     }
7853   my $gm_file = new Automake::XFile "> $out_file";
7854   verb "creating $out_file";
7855   print $gm_file $output;
7858 ################################################################
7863 ################################################################
7865 # Print usage information.
7866 sub usage ()
7868     print "Usage: $0 [OPTION] ... [Makefile]...
7870 Generate Makefile.in for configure from Makefile.am.
7872 Operation modes:
7873       --help               print this help, then exit
7874       --version            print version number, then exit
7875   -v, --verbose            verbosely list files processed
7876       --no-force           only update Makefile.in's that are out of date
7877   -W, --warnings=CATEGORY  report the warnings falling in CATEGORY
7879 Dependency tracking:
7880   -i, --ignore-deps      disable dependency tracking code
7881       --include-deps     enable dependency tracking code
7883 Flavors:
7884       --cygnus           assume program is part of Cygnus-style tree
7885       --foreign          set strictness to foreign
7886       --gnits            set strictness to gnits
7887       --gnu              set strictness to gnu
7889 Library files:
7890   -a, --add-missing      add missing standard files to package
7891       --libdir=DIR       directory storing library files
7892   -c, --copy             with -a, copy missing files (default is symlink)
7893   -f, --force-missing    force update of standard files
7896     Automake::ChannelDefs::usage;
7898     my ($last, @lcomm);
7899     $last = '';
7900     foreach my $iter (sort ((@common_files, @common_sometimes)))
7901     {
7902         push (@lcomm, $iter) unless $iter eq $last;
7903         $last = $iter;
7904     }
7906     my @four;
7907     print "\nFiles which are automatically distributed, if found:\n";
7908     format USAGE_FORMAT =
7909   @<<<<<<<<<<<<<<<<   @<<<<<<<<<<<<<<<<   @<<<<<<<<<<<<<<<<   @<<<<<<<<<<<<<<<<
7910   $four[0],           $four[1],           $four[2],           $four[3]
7912     $~ = "USAGE_FORMAT";
7914     my $cols = 4;
7915     my $rows = int(@lcomm / $cols);
7916     my $rest = @lcomm % $cols;
7918     if ($rest)
7919     {
7920         $rows++;
7921     }
7922     else
7923     {
7924         $rest = $cols;
7925     }
7927     for (my $y = 0; $y < $rows; $y++)
7928     {
7929         @four = ("", "", "", "");
7930         for (my $x = 0; $x < $cols; $x++)
7931         {
7932             last if $y + 1 == $rows && $x == $rest;
7934             my $idx = (($x > $rest)
7935                        ?  ($rows * $rest + ($rows - 1) * ($x - $rest))
7936                        : ($rows * $x));
7938             $idx += $y;
7939             $four[$x] = $lcomm[$idx];
7940         }
7941         write;
7942     }
7944     print "\nReport bugs to <bug-automake\@gnu.org>.\n";
7946     # --help always returns 0 per GNU standards.
7947     exit 0;
7951 # &version ()
7952 # -----------
7953 # Print version information
7954 sub version ()
7956   print <<EOF;
7957 automake (GNU $PACKAGE) $VERSION
7958 Copyright (C) 2008 Free Software Foundation, Inc.
7959 License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
7960 This is free software: you are free to change and redistribute it.
7961 There is NO WARRANTY, to the extent permitted by law.
7963 Written by Tom Tromey <tromey\@redhat.com>
7964        and Alexandre Duret-Lutz <adl\@gnu.org>.
7966   # --version always returns 0 per GNU standards.
7967   exit 0;
7970 ################################################################
7972 # Parse command line.
7973 sub parse_arguments ()
7975   # Start off as gnu.
7976   set_strictness ('gnu');
7978   my $cli_where = new Automake::Location;
7979   my %cli_options =
7980     (
7981      'libdir=s' => \$libdir,
7982      'gnu'              => sub { set_strictness ('gnu'); },
7983      'gnits'            => sub { set_strictness ('gnits'); },
7984      'cygnus'           => sub { set_global_option ('cygnus', $cli_where); },
7985      'foreign'          => sub { set_strictness ('foreign'); },
7986      'include-deps'     => sub { unset_global_option ('no-dependencies'); },
7987      'i|ignore-deps'    => sub { set_global_option ('no-dependencies',
7988                                                     $cli_where); },
7989      'no-force' => sub { $force_generation = 0; },
7990      'f|force-missing'  => \$force_missing,
7991      'o|output-dir=s'   => \$output_directory,
7992      'a|add-missing'    => \$add_missing,
7993      'c|copy'           => \$copy_missing,
7994      'v|verbose'        => sub { setup_channel 'verb', silent => 0; },
7995      'W|warnings=s'     => \&parse_warnings,
7996      # These long options (--Werror and --Wno-error) for backward
7997      # compatibility.  Use -Werror and -Wno-error today.
7998      'Werror'           => sub { parse_warnings 'W', 'error'; },
7999      'Wno-error'        => sub { parse_warnings 'W', 'no-error'; },
8000      );
8001   use Getopt::Long;
8002   Getopt::Long::config ("bundling", "pass_through");
8004   # See if --version or --help is used.  We want to process these before
8005   # anything else because the GNU Coding Standards require us to
8006   # `exit 0' after processing these options, and we can't guarantee this
8007   # if we treat other options first.  (Handling other options first
8008   # could produce error diagnostics, and in this condition it is
8009   # confusing if Automake does `exit 0'.)
8010   my %cli_options_1st_pass =
8011     (
8012      'version' => \&version,
8013      'help'    => \&usage,
8014      # Recognize all other options (and their arguments) but do nothing.
8015      map { $_ => sub {} } (keys %cli_options)
8016      );
8017   my @ARGV_backup = @ARGV;
8018   Getopt::Long::GetOptions %cli_options_1st_pass
8019     or exit 1;
8020   @ARGV = @ARGV_backup;
8022   # Now *really* process the options.  This time we know that --help
8023   # and --version are not present, but we specify them nonetheless so
8024   # that ambiguous abbreviation are diagnosed.
8025   Getopt::Long::GetOptions %cli_options, 'version' => sub {}, 'help' => sub {}
8026     or exit 1;
8028   if (defined $output_directory)
8029     {
8030       msg 'obsolete', "`--output-dir' is deprecated\n";
8031     }
8032   else
8033     {
8034       # In the next release we'll remove this entirely.
8035       $output_directory = '.';
8036     }
8038   return unless @ARGV;
8040   if ($ARGV[0] =~ /^-./)
8041     {
8042       my %argopts;
8043       for my $k (keys %cli_options)
8044         {
8045           if ($k =~ /(.*)=s$/)
8046             {
8047               map { $argopts{(length ($_) == 1)
8048                              ? "-$_" : "--$_" } = 1; } (split (/\|/, $1));
8049             }
8050         }
8051       if ($ARGV[0] eq '--')
8052         {
8053           shift @ARGV;
8054         }
8055       elsif (exists $argopts{$ARGV[0]})
8056         {
8057           fatal ("option `$ARGV[0]' requires an argument\n"
8058                  . "Try `$0 --help' for more information.");
8059         }
8060       else
8061         {
8062           fatal ("unrecognized option `$ARGV[0]'.\n"
8063                  . "Try `$0 --help' for more information.");
8064         }
8065     }
8067   my $errspec = 0;
8068   foreach my $arg (@ARGV)
8069     {
8070       fatal ("empty argument\nTry `$0 --help' for more information.")
8071         if ($arg eq '');
8073       # Handle $local:$input syntax.
8074       my ($local, @rest) = split (/:/, $arg);
8075       @rest = ("$local.in",) unless @rest;
8076       my $input = locate_am @rest;
8077       if ($input)
8078         {
8079           push @input_files, $input;
8080           $output_files{$input} = join (':', ($local, @rest));
8081         }
8082       else
8083         {
8084           error "no Automake input file found for `$arg'";
8085           $errspec = 1;
8086         }
8087     }
8088   fatal "no input file found among supplied arguments"
8089     if $errspec && ! @input_files;
8093 # handle_makefile ($MAKEFILE_IN)
8094 # ------------------------------
8095 # Deal with $MAKEFILE_IN.
8096 sub handle_makefile ($)
8098   my ($file) =  @_;
8099   ($am_file = $file) =~ s/\.in$//;
8100   if (! -f ($am_file . '.am'))
8101     {
8102       error "`$am_file.am' does not exist";
8103     }
8104   else
8105     {
8106       # Any warning setting now local to this Makefile.am.
8107       dup_channel_setup;
8109       generate_makefile ($am_file . '.am', $file);
8111       # Back out any warning setting.
8112       drop_channel_setup;
8113     }
8116 # handle_makefiles_serial ()
8117 # --------------------------
8118 # Deal with all makefiles, without threads.
8119 sub handle_makefiles_serial ()
8121   foreach my $file (@input_files)
8122     {
8123       handle_makefile ($file);
8124     }
8127 # get_number_of_threads ()
8128 # ------------------------
8129 # Logic for deciding how many worker threads to use.
8130 sub get_number_of_threads
8132   my $nthreads = $ENV{'AUTOMAKE_JOBS'} || 0;
8134   $nthreads = 0
8135     unless $nthreads =~ /^[0-9]+$/;
8137   # It doesn't make sense to use more threads than makefiles,
8138   my $max_threads = @input_files;
8140   # but a single worker thread is helpful for exposing bugs.
8141   if ($automake_will_process_aux_dir && $max_threads > 1)
8142     {
8143       $max_threads--;
8144     }
8145   if ($nthreads > $max_threads)
8146     {
8147       $nthreads = $max_threads;
8148     }
8149   return $nthreads;
8152 # handle_makefiles_threaded ($NTHREADS)
8153 # -------------------------------------
8154 # Deal with all makefiles, using threads.  The general strategy is to
8155 # spawn NTHREADS worker threads, dispatch makefiles to them, and let the
8156 # worker threads push back everything that needs serialization:
8157 # * warning and (normal) error messages, for stable stderr output
8158 #   order and content (avoiding duplicates, for example),
8159 # * races when installing aux files (and respective messages),
8160 # * races when collecting aux files for distribution.
8162 # The latter requires that the makefile that deals with the aux dir
8163 # files be handled last, done by the master thread.
8164 sub handle_makefiles_threaded ($)
8166   my ($nthreads) = @_;
8168   my @queued_input_files = @input_files;
8169   my $last_input_file = undef;
8170   if ($automake_will_process_aux_dir)
8171     {
8172       $last_input_file = pop @queued_input_files;
8173     }
8175   # The file queue distributes all makefiles, the message queues
8176   # collect all serializations needed for respective files.
8177   my $file_queue = Thread::Queue->new;
8178   my %msg_queues;
8179   foreach my $file (@queued_input_files)
8180     {
8181       $msg_queues{$file} = Thread::Queue->new;
8182     }
8184   verb "spawning $nthreads worker threads";
8185   my @threads = (1 .. $nthreads);
8186   foreach my $t (@threads)
8187     {
8188       $t = threads->new (sub
8189         {
8190           while (my $file = $file_queue->dequeue)
8191             {
8192               verb "handling $file";
8193               my $queue = $msg_queues{$file};
8194               setup_channel_queue ($queue, QUEUE_MESSAGE);
8195               $required_conf_file_queue = $queue;
8196               handle_makefile ($file);
8197               $queue->enqueue (undef);
8198               setup_channel_queue (undef, undef);
8199               $required_conf_file_queue = undef;
8200             }
8201           return $exit_code;
8202         });
8203     }
8205   # Queue all normal makefiles.
8206   verb "queuing " . @queued_input_files . " input files";
8207   $file_queue->enqueue (@queued_input_files, (undef) x @threads);
8209   # Collect and process serializations.
8210   foreach my $file (@queued_input_files)
8211     {
8212       verb "dequeuing messages for " . $file;
8213       reset_local_duplicates ();
8214       my $queue = $msg_queues{$file};
8215       while (my $key = $queue->dequeue)
8216         {
8217           if ($key eq QUEUE_MESSAGE)
8218             {
8219               pop_channel_queue ($queue);
8220             }
8221           elsif ($key eq QUEUE_CONF_FILE)
8222             {
8223               require_queued_conf_file ($queue);
8224             }
8225           else
8226             {
8227               prog_error "unexpected key $key";
8228             }
8229         }
8230     }
8232   foreach my $t (@threads)
8233     {
8234       my @exit_thread = $t->join;
8235       $exit_code = $exit_thread[0]
8236         if ($exit_thread[0] > $exit_code);
8237     }
8239   # The master processes the last file.
8240   if ($automake_will_process_aux_dir)
8241     {
8242       verb "processing last input file";
8243       handle_makefile ($last_input_file);
8244     }
8247 ################################################################
8249 # Parse the WARNINGS environment variable.
8250 parse_WARNINGS;
8252 # Parse command line.
8253 parse_arguments;
8255 $configure_ac = require_configure_ac;
8257 # Do configure.ac scan only once.
8258 scan_autoconf_files;
8260 if (! @input_files)
8261   {
8262     my $msg = '';
8263     $msg = "\nDid you forget AC_CONFIG_FILES([Makefile]) in $configure_ac?"
8264       if -f 'Makefile.am';
8265     fatal ("no `Makefile.am' found for any configure output$msg");
8266   }
8268 my $nthreads = get_number_of_threads ();
8270 if ($perl_threads && $nthreads >= 1)
8271   {
8272     handle_makefiles_threaded ($nthreads);
8273   }
8274 else
8275   {
8276     handle_makefiles_serial ();
8277   }
8279 exit $exit_code;
8282 ### Setup "GNU" style for perl-mode and cperl-mode.
8283 ## Local Variables:
8284 ## perl-indent-level: 2
8285 ## perl-continued-statement-offset: 2
8286 ## perl-continued-brace-offset: 0
8287 ## perl-brace-offset: 0
8288 ## perl-brace-imaginary-offset: 0
8289 ## perl-label-offset: -2
8290 ## cperl-indent-level: 2
8291 ## cperl-brace-offset: 0
8292 ## cperl-continued-brace-offset: 0
8293 ## cperl-label-offset: -2
8294 ## cperl-extra-newline-before-brace: t
8295 ## cperl-merge-trailing-else: nil
8296 ## cperl-continued-statement-offset: 2
8297 ## End: