parallel-tests: New target recheck-html.
[automake.git] / automake.in
blobce20cce21caf2c58bbf22ef877f246b7d1941db7
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, 2009  Free Software Foundation,
11 # Inc.
13 # This program is free software; you can redistribute it and/or modify
14 # it under the terms of the GNU General Public License as published by
15 # the Free Software Foundation; either version 3, or (at your option)
16 # any later version.
18 # This program is distributed in the hope that it will be useful,
19 # but WITHOUT ANY WARRANTY; without even the implied warranty of
20 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
21 # GNU General Public License for more details.
23 # You should have received a copy of the GNU General Public License
24 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
26 # Originally written by David Mackenzie <djm@gnu.ai.mit.edu>.
27 # Perl reimplementation by Tom Tromey <tromey@redhat.com>, and
28 # Alexandre Duret-Lutz <adl@gnu.org>.
30 package Language;
32 BEGIN
34   my $perllibdir = $ENV{'perllibdir'} || '@datadir@/@PACKAGE@-@APIVERSION@';
35   unshift @INC, (split '@PATH_SEPARATOR@', $perllibdir);
37   # Override SHELL.  This is required on DJGPP so that system() uses
38   # bash, not COMMAND.COM which doesn't quote arguments properly.
39   # Other systems aren't expected to use $SHELL when Automake
40   # runs, but it should be safe to drop the `if DJGPP' guard if
41   # it turns up other systems need the same thing.  After all,
42   # if SHELL is used, ./configure's SHELL is always better than
43   # the user's SHELL (which may be something like tcsh).
44   $ENV{'SHELL'} = '@SHELL@' if exists $ENV{'DJGPP'};
47 use Automake::Struct;
48 struct (# Short name of the language (c, f77...).
49         'name' => "\$",
50         # Nice name of the language (C, Fortran 77...).
51         'Name' => "\$",
53         # List of configure variables which must be defined.
54         'config_vars' => '@',
56         'ansi'    => "\$",
57         # `pure' is `1' or `'.  A `pure' language is one where, if
58         # all the files in a directory are of that language, then we
59         # do not require the C compiler or any code to call it.
60         'pure'   => "\$",
62         'autodep' => "\$",
64         # Name of the compiling variable (COMPILE).
65         'compiler'  => "\$",
66         # Content of the compiling variable.
67         'compile'  => "\$",
68         # Flag to require compilation without linking (-c).
69         'compile_flag' => "\$",
70         'extensions' => '@',
71         # A subroutine to compute a list of possible extensions of
72         # the product given the input extensions.
73         # (defaults to a subroutine which returns ('.$(OBJEXT)', '.lo'))
74         'output_extensions' => "\$",
75         # A list of flag variables used in 'compile'.
76         # (defaults to [])
77         'flags' => "@",
79         # Any tag to pass to libtool while compiling.
80         'libtool_tag' => "\$",
82         # The file to use when generating rules for this language.
83         # The default is 'depend2'.
84         'rule_file' => "\$",
86         # Name of the linking variable (LINK).
87         'linker' => "\$",
88         # Content of the linking variable.
89         'link' => "\$",
91         # Name of the linker variable (LD).
92         'lder' => "\$",
93         # Content of the linker variable ($(CC)).
94         'ld' => "\$",
96         # Flag to specify the output file (-o).
97         'output_flag' => "\$",
98         '_finish' => "\$",
100         # This is a subroutine which is called whenever we finally
101         # determine the context in which a source file will be
102         # compiled.
103         '_target_hook' => "\$",
105         # If TRUE, nodist_ sources will be compiled using specific rules
106         # (i.e. not inference rules).  The default is FALSE.
107         'nodist_specific' => "\$");
110 sub finish ($)
112   my ($self) = @_;
113   if (defined $self->_finish)
114     {
115       &{$self->_finish} ();
116     }
119 sub target_hook ($$$$%)
121     my ($self) = @_;
122     if (defined $self->_target_hook)
123     {
124         &{$self->_target_hook} (@_);
125     }
128 package Automake;
130 use strict;
131 use Automake::Config;
132 BEGIN
134   if ($perl_threads)
135     {
136       require threads;
137       import threads;
138       require Thread::Queue;
139       import Thread::Queue;
140     }
142 use Automake::General;
143 use Automake::XFile;
144 use Automake::Channels;
145 use Automake::ChannelDefs;
146 use Automake::Configure_ac;
147 use Automake::FileUtils;
148 use Automake::Location;
149 use Automake::Condition qw/TRUE FALSE/;
150 use Automake::DisjConditions;
151 use Automake::Options;
152 use Automake::Version;
153 use Automake::Variable;
154 use Automake::VarDef;
155 use Automake::Rule;
156 use Automake::RuleDef;
157 use Automake::Wrap 'makefile_wrap';
158 use File::Basename;
159 use File::Spec;
160 use Carp;
162 ## ----------- ##
163 ## Constants.  ##
164 ## ----------- ##
166 # Some regular expressions.  One reason to put them here is that it
167 # makes indentation work better in Emacs.
169 # Writing singled-quoted-$-terminated regexes is a pain because
170 # perl-mode thinks of $' as the ${'} variable (instead of a $ followed
171 # by a closing quote.  Letting perl-mode think the quote is not closed
172 # leads to all sort of misindentations.  On the other hand, defining
173 # regexes as double-quoted strings is far less readable.  So usually
174 # we will write:
176 #  $REGEX = '^regex_value' . "\$";
178 my $IGNORE_PATTERN = '^\s*##([^#\n].*)?\n';
179 my $WHITE_PATTERN = '^\s*' . "\$";
180 my $COMMENT_PATTERN = '^#';
181 my $TARGET_PATTERN='[$a-zA-Z0-9_.@%][-.a-zA-Z0-9_(){}/$+@%]*';
182 # A rule has three parts: a list of targets, a list of dependencies,
183 # and optionally actions.
184 my $RULE_PATTERN =
185   "^($TARGET_PATTERN(?:(?:\\\\\n|\\s)+$TARGET_PATTERN)*) *:([^=].*|)\$";
187 # Only recognize leading spaces, not leading tabs.  If we recognize
188 # leading tabs here then we need to make the reader smarter, because
189 # otherwise it will think rules like `foo=bar; \' are errors.
190 my $ASSIGNMENT_PATTERN = '^ *([^ \t=:+]*)\s*([:+]?)=\s*(.*)' . "\$";
191 # This pattern recognizes a Gnits version id and sets $1 if the
192 # release is an alpha release.  We also allow a suffix which can be
193 # used to extend the version number with a "fork" identifier.
194 my $GNITS_VERSION_PATTERN = '\d+\.\d+([a-z]|\.\d+)?(-[A-Za-z0-9]+)?';
196 my $IF_PATTERN = '^if\s+(!?)\s*([A-Za-z][A-Za-z0-9_]*)\s*(?:#.*)?' . "\$";
197 my $ELSE_PATTERN =
198   '^else(?:\s+(!?)\s*([A-Za-z][A-Za-z0-9_]*))?\s*(?:#.*)?' . "\$";
199 my $ENDIF_PATTERN =
200   '^endif(?:\s+(!?)\s*([A-Za-z][A-Za-z0-9_]*))?\s*(?:#.*)?' . "\$";
201 my $PATH_PATTERN = '(\w|[+/.-])+';
202 # This will pass through anything not of the prescribed form.
203 my $INCLUDE_PATTERN = ('^include\s+'
204                        . '((\$\(top_srcdir\)/' . $PATH_PATTERN . ')'
205                        . '|(\$\(srcdir\)/' . $PATH_PATTERN . ')'
206                        . '|([^/\$]' . $PATH_PATTERN . '))\s*(#.*)?' . "\$");
208 # Match `-d' as a command-line argument in a string.
209 my $DASH_D_PATTERN = "(^|\\s)-d(\\s|\$)";
210 # Directories installed during 'install-exec' phase.
211 my $EXEC_DIR_PATTERN =
212   '^(?:bin|sbin|libexec|sysconf|localstate|lib|pkglib|.*exec.*)' . "\$";
214 # Values for AC_CANONICAL_*
215 use constant AC_CANONICAL_BUILD  => 1;
216 use constant AC_CANONICAL_HOST   => 2;
217 use constant AC_CANONICAL_TARGET => 3;
219 # Values indicating when something should be cleaned.
220 use constant MOSTLY_CLEAN     => 0;
221 use constant CLEAN            => 1;
222 use constant DIST_CLEAN       => 2;
223 use constant MAINTAINER_CLEAN => 3;
225 # Libtool files.
226 my @libtool_files = qw(ltmain.sh config.guess config.sub);
227 # ltconfig appears here for compatibility with old versions of libtool.
228 my @libtool_sometimes = qw(ltconfig ltcf-c.sh ltcf-cxx.sh ltcf-gcj.sh);
230 # Commonly found files we look for and automatically include in
231 # DISTFILES.
232 my @common_files =
233     (qw(ABOUT-GNU ABOUT-NLS AUTHORS BACKLOG COPYING COPYING.DOC COPYING.LIB
234         COPYING.LESSER ChangeLog INSTALL NEWS README THANKS TODO
235         ansi2knr.1 ansi2knr.c compile config.guess config.rpath config.sub
236         depcomp elisp-comp install-sh libversion.in mdate-sh missing
237         mkinstalldirs py-compile texinfo.tex ylwrap),
238      @libtool_files, @libtool_sometimes);
240 # Commonly used files we auto-include, but only sometimes.  This list
241 # is used for the --help output only.
242 my @common_sometimes =
243   qw(aclocal.m4 acconfig.h config.h.top config.h.bot configure
244      configure.ac configure.in stamp-vti);
246 # Standard directories from the GNU Coding Standards, and additional
247 # pkg* directories from Automake.  Stored in a hash for fast member check.
248 my %standard_prefix =
249     map { $_ => 1 } (qw(bin data dataroot dvi exec html include info
250                         lib libexec lisp localstate man man1 man2 man3
251                         man4 man5 man6 man7 man8 man9 oldinclude pdf
252                         pkgdatadir pkgincludedir pkglibdir pkglibexecdir
253                         ps sbin sharedstate sysconf));
255 # Copyright on generated Makefile.ins.
256 my $gen_copyright = "\
257 # Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002,
258 # 2003, 2004, 2005, 2006, 2007, 2008, 2009  Free Software Foundation,
259 # Inc.
260 # This Makefile.in is free software; the Free Software Foundation
261 # gives unlimited permission to copy and/or distribute it,
262 # with or without modifications, as long as this notice is preserved.
264 # This program is distributed in the hope that it will be useful,
265 # but WITHOUT ANY WARRANTY, to the extent permitted by law; without
266 # even the implied warranty of MERCHANTABILITY or FITNESS FOR A
267 # PARTICULAR PURPOSE.
270 # These constants are returned by the lang_*_rewrite functions.
271 # LANG_SUBDIR means that the resulting object file should be in a
272 # subdir if the source file is.  In this case the file name cannot
273 # have `..' components.
274 use constant LANG_IGNORE  => 0;
275 use constant LANG_PROCESS => 1;
276 use constant LANG_SUBDIR  => 2;
278 # These are used when keeping track of whether an object can be built
279 # by two different paths.
280 use constant COMPILE_LIBTOOL  => 1;
281 use constant COMPILE_ORDINARY => 2;
283 # We can't always associate a location to a variable or a rule,
284 # when it's defined by Automake.  We use INTERNAL in this case.
285 use constant INTERNAL => new Automake::Location;
287 # Serialization keys for message queues.
288 use constant QUEUE_MESSAGE   => "msg";
289 use constant QUEUE_CONF_FILE => "conf file";
290 use constant QUEUE_LOCATION  => "location";
291 use constant 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    'html-am'         => 1,
460    'dvi-am'          => 1,
461    'pdf-am'          => 1,
462    'ps-am'           => 1,
463    'info-am'         => 1,
464    'install-data-am' => 1,
465    'install-exec-am' => 1,
466    'install-html-am' => 1,
467    'install-dvi-am'  => 1,
468    'install-pdf-am'  => 1,
469    'install-ps-am'   => 1,
470    'install-info-am' => 1,
471    'installcheck-am' => 1,
472    'uninstall-am' => 1,
474    'install-man' => 1,
475   );
477 # Set to 1 if this run will create the Makefile.in that distributes
478 # the files in config_aux_dir.
479 my $automake_will_process_aux_dir = 0;
481 # The name of the Makefile currently being processed.
482 my $am_file = 'BUG';
485 ################################################################
487 ## ------------------------------------------ ##
488 ## Variables reset by &initialize_per_input.  ##
489 ## ------------------------------------------ ##
491 # Basename and relative dir of the input file.
492 my $am_file_name;
493 my $am_relative_dir;
495 # Same but wrt Makefile.in.
496 my $in_file_name;
497 my $relative_dir;
499 # Relative path to the top directory.
500 my $topsrcdir;
502 # Greatest timestamp of the output's dependencies (excluding
503 # configure's dependencies).
504 my $output_deps_greatest_timestamp;
506 # These variables are used when generating each Makefile.in.
507 # They hold the Makefile.in until it is ready to be printed.
508 my $output_vars;
509 my $output_all;
510 my $output_header;
511 my $output_rules;
512 my $output_trailer;
514 # This is the conditional stack, updated on if/else/endif, and
515 # used to build Condition objects.
516 my @cond_stack;
518 # This holds the set of included files.
519 my @include_stack;
521 # List of dependencies for the obvious targets.
522 my @all;
523 my @check;
524 my @check_tests;
526 # Keys in this hash table are files to delete.  The associated
527 # value tells when this should happen (MOSTLY_CLEAN, DIST_CLEAN, etc.)
528 my %clean_files;
530 # Keys in this hash table are object files or other files in
531 # subdirectories which need to be removed.  This only holds files
532 # which are created by compilations.  The value in the hash indicates
533 # when the file should be removed.
534 my %compile_clean_files;
536 # Keys in this hash table are directories where we expect to build a
537 # libtool object.  We use this information to decide what directories
538 # to delete.
539 my %libtool_clean_directories;
541 # Value of `$(SOURCES)', used by tags.am.
542 my @sources;
543 # Sources which go in the distribution.
544 my @dist_sources;
546 # This hash maps object file names onto their corresponding source
547 # file names.  This is used to ensure that each object is created
548 # by a single source file.
549 my %object_map;
551 # This hash maps object file names onto an integer value representing
552 # whether this object has been built via ordinary compilation or
553 # libtool compilation (the COMPILE_* constants).
554 my %object_compilation_map;
557 # This keeps track of the directories for which we've already
558 # created dirstamp code.  Keys are directories, values are stamp files.
559 # Several keys can share the same stamp files if they are equivalent
560 # (as are `.//foo' and `foo').
561 my %directory_map;
563 # All .P files.
564 my %dep_files;
566 # This is a list of all targets to run during "make dist".
567 my @dist_targets;
569 # Keep track of all programs declared in this Makefile, without
570 # $(EXEEXT).  @substitutions@ are not listed.
571 my %known_programs;
573 # Keys in this hash are the basenames of files which must depend on
574 # ansi2knr.  Values are either the empty string, or the directory in
575 # which the ANSI source file appears; the directory must have a
576 # trailing `/'.
577 my %de_ansi_files;
579 # This keeps track of which extensions we've seen (that we care
580 # about).
581 my %extension_seen;
583 # This is random scratch space for the language finish functions.
584 # Don't randomly overwrite it; examine other uses of keys first.
585 my %language_scratch;
587 # We keep track of which objects need special (per-executable)
588 # handling on a per-language basis.
589 my %lang_specific_files;
591 # This is set when `handle_dist' has finished.  Once this happens,
592 # we should no longer push on dist_common.
593 my $handle_dist_run;
595 # Used to store a set of linkers needed to generate the sources currently
596 # under consideration.
597 my %linkers_used;
599 # True if we need `LINK' defined.  This is a hack.
600 my $need_link;
602 # Was get_object_extension run?
603 # FIXME: This is a hack. a better switch should be found.
604 my $get_object_extension_was_run;
606 # Record each file processed by make_paragraphs.
607 my %transformed_files;
610 ################################################################
612 ## ---------------------------------------------- ##
613 ## Variables not reset by &initialize_per_input.  ##
614 ## ---------------------------------------------- ##
616 # Cache each file processed by make_paragraphs.
617 # (This is different from %transformed_files because
618 # %transformed_files is reset for each file while %am_file_cache
619 # it global to the run.)
620 my %am_file_cache;
622 ################################################################
624 # var_SUFFIXES_trigger ($TYPE, $VALUE)
625 # ------------------------------------
626 # This is called by Automake::Variable::define() when SUFFIXES
627 # is defined ($TYPE eq '') or appended ($TYPE eq '+').
628 # The work here needs to be performed as a side-effect of the
629 # macro_define() call because SUFFIXES definitions impact
630 # on $KNOWN_EXTENSIONS_PATTERN which is used used when parsing
631 # the input am file.
632 sub var_SUFFIXES_trigger ($$)
634     my ($type, $value) = @_;
635     accept_extensions (split (' ', $value));
637 Automake::Variable::hook ('SUFFIXES', \&var_SUFFIXES_trigger);
639 ################################################################
641 ## --------------------------------- ##
642 ## Forward subroutine declarations.  ##
643 ## --------------------------------- ##
644 sub register_language (%);
645 sub file_contents_internal ($$$%);
646 sub define_files_variable ($\@$$);
649 # &initialize_per_input ()
650 # ------------------------
651 # (Re)-Initialize per-Makefile.am variables.
652 sub initialize_per_input ()
654     reset_local_duplicates ();
656     $am_file_name = undef;
657     $am_relative_dir = undef;
659     $in_file_name = undef;
660     $relative_dir = undef;
661     $topsrcdir = undef;
663     $output_deps_greatest_timestamp = 0;
665     $output_vars = '';
666     $output_all = '';
667     $output_header = '';
668     $output_rules = '';
669     $output_trailer = '';
671     Automake::Options::reset;
672     Automake::Variable::reset;
673     Automake::Rule::reset;
675     @cond_stack = ();
677     @include_stack = ();
679     @all = ();
680     @check = ();
681     @check_tests = ();
683     %clean_files = ();
684     %compile_clean_files = ();
686     # We always include `.'.  This isn't strictly correct.
687     %libtool_clean_directories = ('.' => 1);
689     @sources = ();
690     @dist_sources = ();
692     %object_map = ();
693     %object_compilation_map = ();
695     %directory_map = ();
697     %dep_files = ();
699     @dist_targets = ();
701     %known_programs = ();
703     %de_ansi_files = ();
705     %extension_seen = ();
707     %language_scratch = ();
709     %lang_specific_files = ();
711     $handle_dist_run = 0;
713     $need_link = 0;
715     $get_object_extension_was_run = 0;
717     %transformed_files = ();
721 ################################################################
723 # Initialize our list of languages that are internally supported.
725 # C.
726 register_language ('name' => 'c',
727                    'Name' => 'C',
728                    'config_vars' => ['CC'],
729                    'ansi' => 1,
730                    'autodep' => '',
731                    'flags' => ['CFLAGS', 'CPPFLAGS'],
732                    'compiler' => 'COMPILE',
733                    'compile' => '$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS)',
734                    'lder' => 'CCLD',
735                    'ld' => '$(CC)',
736                    'linker' => 'LINK',
737                    'link' => '$(CCLD) $(AM_CFLAGS) $(CFLAGS) $(AM_LDFLAGS) $(LDFLAGS) -o $@',
738                    'compile_flag' => '-c',
739                    'libtool_tag' => 'CC',
740                    'extensions' => ['.c'],
741                    '_finish' => \&lang_c_finish);
743 # C++.
744 register_language ('name' => 'cxx',
745                    'Name' => 'C++',
746                    'config_vars' => ['CXX'],
747                    'linker' => 'CXXLINK',
748                    'link' => '$(CXXLD) $(AM_CXXFLAGS) $(CXXFLAGS) $(AM_LDFLAGS) $(LDFLAGS) -o $@',
749                    'autodep' => 'CXX',
750                    'flags' => ['CXXFLAGS', 'CPPFLAGS'],
751                    'compile' => '$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS)',
752                    'compiler' => 'CXXCOMPILE',
753                    'compile_flag' => '-c',
754                    'output_flag' => '-o',
755                    'libtool_tag' => 'CXX',
756                    'lder' => 'CXXLD',
757                    'ld' => '$(CXX)',
758                    'pure' => 1,
759                    'extensions' => ['.c++', '.cc', '.cpp', '.cxx', '.C']);
761 # Objective C.
762 register_language ('name' => 'objc',
763                    'Name' => 'Objective C',
764                    'config_vars' => ['OBJC'],
765                    'linker' => 'OBJCLINK',
766                    'link' => '$(OBJCLD) $(AM_OBJCFLAGS) $(OBJCFLAGS) $(AM_LDFLAGS) $(LDFLAGS) -o $@',
767                    'autodep' => 'OBJC',
768                    'flags' => ['OBJCFLAGS', 'CPPFLAGS'],
769                    'compile' => '$(OBJC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_OBJCFLAGS) $(OBJCFLAGS)',
770                    'compiler' => 'OBJCCOMPILE',
771                    'compile_flag' => '-c',
772                    'output_flag' => '-o',
773                    'lder' => 'OBJCLD',
774                    'ld' => '$(OBJC)',
775                    'pure' => 1,
776                    'extensions' => ['.m']);
778 # Unified Parallel C.
779 register_language ('name' => 'upc',
780                    'Name' => 'Unified Parallel C',
781                    'config_vars' => ['UPC'],
782                    'linker' => 'UPCLINK',
783                    'link' => '$(UPCLD) $(AM_UPCFLAGS) $(UPCFLAGS) $(AM_LDFLAGS) $(LDFLAGS) -o $@',
784                    'autodep' => 'UPC',
785                    'flags' => ['UPCFLAGS', 'CPPFLAGS'],
786                    'compile' => '$(UPC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_UPCFLAGS) $(UPCFLAGS)',
787                    'compiler' => 'UPCCOMPILE',
788                    'compile_flag' => '-c',
789                    'output_flag' => '-o',
790                    'lder' => 'UPCLD',
791                    'ld' => '$(UPC)',
792                    'pure' => 1,
793                    'extensions' => ['.upc']);
795 # Headers.
796 register_language ('name' => 'header',
797                    'Name' => 'Header',
798                    'extensions' => ['.h', '.H', '.hxx', '.h++', '.hh',
799                                     '.hpp', '.inc'],
800                    # No output.
801                    'output_extensions' => sub { return () },
802                    # Nothing to do.
803                    '_finish' => sub { });
805 # Yacc (C & C++).
806 register_language ('name' => 'yacc',
807                    'Name' => 'Yacc',
808                    'config_vars' => ['YACC'],
809                    'flags' => ['YFLAGS'],
810                    'compile' => '$(YACC) $(YFLAGS) $(AM_YFLAGS)',
811                    'compiler' => 'YACCCOMPILE',
812                    'extensions' => ['.y'],
813                    'output_extensions' => sub { (my $ext = $_[0]) =~ tr/y/c/;
814                                                 return ($ext,) },
815                    'rule_file' => 'yacc',
816                    '_finish' => \&lang_yacc_finish,
817                    '_target_hook' => \&lang_yacc_target_hook,
818                    'nodist_specific' => 1);
819 register_language ('name' => 'yaccxx',
820                    'Name' => 'Yacc (C++)',
821                    'config_vars' => ['YACC'],
822                    'rule_file' => 'yacc',
823                    'flags' => ['YFLAGS'],
824                    'compiler' => 'YACCCOMPILE',
825                    'compile' => '$(YACC) $(YFLAGS) $(AM_YFLAGS)',
826                    'extensions' => ['.y++', '.yy', '.yxx', '.ypp'],
827                    'output_extensions' => sub { (my $ext = $_[0]) =~ tr/y/c/;
828                                                 return ($ext,) },
829                    '_finish' => \&lang_yacc_finish,
830                    '_target_hook' => \&lang_yacc_target_hook,
831                    'nodist_specific' => 1);
833 # Lex (C & C++).
834 register_language ('name' => 'lex',
835                    'Name' => 'Lex',
836                    'config_vars' => ['LEX'],
837                    'rule_file' => 'lex',
838                    'flags' => ['LFLAGS'],
839                    'compile' => '$(LEX) $(LFLAGS) $(AM_LFLAGS)',
840                    'compiler' => 'LEXCOMPILE',
841                    'extensions' => ['.l'],
842                    'output_extensions' => sub { (my $ext = $_[0]) =~ tr/l/c/;
843                                                 return ($ext,) },
844                    '_finish' => \&lang_lex_finish,
845                    '_target_hook' => \&lang_lex_target_hook,
846                    'nodist_specific' => 1);
847 register_language ('name' => 'lexxx',
848                    'Name' => 'Lex (C++)',
849                    'config_vars' => ['LEX'],
850                    'rule_file' => 'lex',
851                    'flags' => ['LFLAGS'],
852                    'compile' => '$(LEX) $(LFLAGS) $(AM_LFLAGS)',
853                    'compiler' => 'LEXCOMPILE',
854                    'extensions' => ['.l++', '.ll', '.lxx', '.lpp'],
855                    'output_extensions' => sub { (my $ext = $_[0]) =~ tr/l/c/;
856                                                 return ($ext,) },
857                    '_finish' => \&lang_lex_finish,
858                    '_target_hook' => \&lang_lex_target_hook,
859                    'nodist_specific' => 1);
861 # Assembler.
862 register_language ('name' => 'asm',
863                    'Name' => 'Assembler',
864                    'config_vars' => ['CCAS', 'CCASFLAGS'],
866                    'flags' => ['CCASFLAGS'],
867                    # Users can set AM_CCASFLAGS to include DEFS, INCLUDES,
868                    # or anything else required.  They can also set CCAS.
869                    # Or simply use Preprocessed Assembler.
870                    'compile' => '$(CCAS) $(AM_CCASFLAGS) $(CCASFLAGS)',
871                    'compiler' => 'CCASCOMPILE',
872                    'compile_flag' => '-c',
873                    'output_flag' => '-o',
874                    'extensions' => ['.s'],
876                    # With assembly we still use the C linker.
877                    '_finish' => \&lang_c_finish);
879 # Preprocessed Assembler.
880 register_language ('name' => 'cppasm',
881                    'Name' => 'Preprocessed Assembler',
882                    'config_vars' => ['CCAS', 'CCASFLAGS'],
884                    'autodep' => 'CCAS',
885                    'flags' => ['CCASFLAGS', 'CPPFLAGS'],
886                    'compile' => '$(CCAS) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CCASFLAGS) $(CCASFLAGS)',
887                    'compiler' => 'CPPASCOMPILE',
888                    'compile_flag' => '-c',
889                    'output_flag' => '-o',
890                    'extensions' => ['.S', '.sx'],
892                    # With assembly we still use the C linker.
893                    '_finish' => \&lang_c_finish);
895 # Fortran 77
896 register_language ('name' => 'f77',
897                    'Name' => 'Fortran 77',
898                    'config_vars' => ['F77'],
899                    'linker' => 'F77LINK',
900                    'link' => '$(F77LD) $(AM_FFLAGS) $(FFLAGS) $(AM_LDFLAGS) $(LDFLAGS) -o $@',
901                    'flags' => ['FFLAGS'],
902                    'compile' => '$(F77) $(AM_FFLAGS) $(FFLAGS)',
903                    'compiler' => 'F77COMPILE',
904                    'compile_flag' => '-c',
905                    'output_flag' => '-o',
906                    'libtool_tag' => 'F77',
907                    'lder' => 'F77LD',
908                    'ld' => '$(F77)',
909                    'pure' => 1,
910                    'extensions' => ['.f', '.for']);
912 # Fortran
913 register_language ('name' => 'fc',
914                    'Name' => 'Fortran',
915                    'config_vars' => ['FC'],
916                    'linker' => 'FCLINK',
917                    'link' => '$(FCLD) $(AM_FCFLAGS) $(FCFLAGS) $(AM_LDFLAGS) $(LDFLAGS) -o $@',
918                    'flags' => ['FCFLAGS'],
919                    'compile' => '$(FC) $(AM_FCFLAGS) $(FCFLAGS)',
920                    'compiler' => 'FCCOMPILE',
921                    'compile_flag' => '-c',
922                    'output_flag' => '-o',
923                    'lder' => 'FCLD',
924                    'ld' => '$(FC)',
925                    'pure' => 1,
926                    'extensions' => ['.f90', '.f95', '.f03', '.f08']);
928 # Preprocessed Fortran
929 register_language ('name' => 'ppfc',
930                    'Name' => 'Preprocessed Fortran',
931                    'config_vars' => ['FC'],
932                    'linker' => 'FCLINK',
933                    'link' => '$(FCLD) $(AM_FCFLAGS) $(FCFLAGS) $(AM_LDFLAGS) $(LDFLAGS) -o $@',
934                    'lder' => 'FCLD',
935                    'ld' => '$(FC)',
936                    'flags' => ['FCFLAGS', 'CPPFLAGS'],
937                    'compiler' => 'PPFCCOMPILE',
938                    'compile' => '$(FC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_FCFLAGS) $(FCFLAGS)',
939                    'compile_flag' => '-c',
940                    'output_flag' => '-o',
941                    'libtool_tag' => 'FC',
942                    'pure' => 1,
943                    'extensions' => ['.F90','.F95', '.F03', '.F08']);
945 # Preprocessed Fortran 77
947 # The current support for preprocessing Fortran 77 just involves
948 # passing `$(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS)
949 # $(CPPFLAGS)' as additional flags to the Fortran 77 compiler, since
950 # this is how GNU Make does it; see the `GNU Make Manual, Edition 0.51
951 # for `make' Version 3.76 Beta' (specifically, from info file
952 # `(make)Catalogue of Rules').
954 # A better approach would be to write an Autoconf test
955 # (i.e. AC_PROG_FPP) for a Fortran 77 preprocessor, because not all
956 # Fortran 77 compilers know how to do preprocessing.  The Autoconf
957 # macro AC_PROG_FPP should test the Fortran 77 compiler first for
958 # preprocessing capabilities, and then fall back on cpp (if cpp were
959 # available).
960 register_language ('name' => 'ppf77',
961                    'Name' => 'Preprocessed Fortran 77',
962                    'config_vars' => ['F77'],
963                    'linker' => 'F77LINK',
964                    'link' => '$(F77LD) $(AM_FFLAGS) $(FFLAGS) $(AM_LDFLAGS) $(LDFLAGS) -o $@',
965                    'lder' => 'F77LD',
966                    'ld' => '$(F77)',
967                    'flags' => ['FFLAGS', 'CPPFLAGS'],
968                    'compiler' => 'PPF77COMPILE',
969                    'compile' => '$(F77) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_FFLAGS) $(FFLAGS)',
970                    'compile_flag' => '-c',
971                    'output_flag' => '-o',
972                    'libtool_tag' => 'F77',
973                    'pure' => 1,
974                    'extensions' => ['.F']);
976 # Ratfor.
977 register_language ('name' => 'ratfor',
978                    'Name' => 'Ratfor',
979                    'config_vars' => ['F77'],
980                    'linker' => 'F77LINK',
981                    'link' => '$(F77LD) $(AM_FFLAGS) $(FFLAGS) $(AM_LDFLAGS) $(LDFLAGS) -o $@',
982                    'lder' => 'F77LD',
983                    'ld' => '$(F77)',
984                    'flags' => ['RFLAGS', 'FFLAGS'],
985                    # FIXME also FFLAGS.
986                    'compile' => '$(F77) $(AM_FFLAGS) $(FFLAGS) $(AM_RFLAGS) $(RFLAGS)',
987                    'compiler' => 'RCOMPILE',
988                    'compile_flag' => '-c',
989                    'output_flag' => '-o',
990                    'libtool_tag' => 'F77',
991                    'pure' => 1,
992                    'extensions' => ['.r']);
994 # Java via gcj.
995 register_language ('name' => 'java',
996                    'Name' => 'Java',
997                    'config_vars' => ['GCJ'],
998                    'linker' => 'GCJLINK',
999                    'link' => '$(GCJLD) $(AM_GCJFLAGS) $(GCJFLAGS) $(AM_LDFLAGS) $(LDFLAGS) -o $@',
1000                    'autodep' => 'GCJ',
1001                    'flags' => ['GCJFLAGS'],
1002                    'compile' => '$(GCJ) $(AM_GCJFLAGS) $(GCJFLAGS)',
1003                    'compiler' => 'GCJCOMPILE',
1004                    'compile_flag' => '-c',
1005                    'output_flag' => '-o',
1006                    'libtool_tag' => 'GCJ',
1007                    'lder' => 'GCJLD',
1008                    'ld' => '$(GCJ)',
1009                    'pure' => 1,
1010                    'extensions' => ['.java', '.class', '.zip', '.jar']);
1012 ################################################################
1014 # Error reporting functions.
1016 # err_am ($MESSAGE, [%OPTIONS])
1017 # -----------------------------
1018 # Uncategorized errors about the current Makefile.am.
1019 sub err_am ($;%)
1021   msg_am ('error', @_);
1024 # err_ac ($MESSAGE, [%OPTIONS])
1025 # -----------------------------
1026 # Uncategorized errors about configure.ac.
1027 sub err_ac ($;%)
1029   msg_ac ('error', @_);
1032 # msg_am ($CHANNEL, $MESSAGE, [%OPTIONS])
1033 # ---------------------------------------
1034 # Messages about about the current Makefile.am.
1035 sub msg_am ($$;%)
1037   my ($channel, $msg, %opts) = @_;
1038   msg $channel, "${am_file}.am", $msg, %opts;
1041 # msg_ac ($CHANNEL, $MESSAGE, [%OPTIONS])
1042 # ---------------------------------------
1043 # Messages about about configure.ac.
1044 sub msg_ac ($$;%)
1046   my ($channel, $msg, %opts) = @_;
1047   msg $channel, $configure_ac, $msg, %opts;
1050 ################################################################
1052 # subst ($TEXT)
1053 # -------------
1054 # Return a configure-style substitution using the indicated text.
1055 # We do this to avoid having the substitutions directly in automake.in;
1056 # when we do that they are sometimes removed and this causes confusion
1057 # and bugs.
1058 sub subst ($)
1060     my ($text) = @_;
1061     return '@' . $text . '@';
1064 ################################################################
1067 # $BACKPATH
1068 # &backname ($REL-DIR)
1069 # --------------------
1070 # If I `cd $REL-DIR', then to come back, I should `cd $BACKPATH'.
1071 # For instance `src/foo' => `../..'.
1072 # Works with non strictly increasing paths, i.e., `src/../lib' => `..'.
1073 sub backname ($)
1075     my ($file) = @_;
1076     my @res;
1077     foreach (split (/\//, $file))
1078     {
1079         next if $_ eq '.' || $_ eq '';
1080         if ($_ eq '..')
1081         {
1082             pop @res
1083               or prog_error ("trying to reverse path `$file' pointing outside tree");
1084         }
1085         else
1086         {
1087             push (@res, '..');
1088         }
1089     }
1090     return join ('/', @res) || '.';
1093 ################################################################
1096 # Handle AUTOMAKE_OPTIONS variable.  Return 1 on error, 0 otherwise.
1097 sub handle_options
1099   my $var = var ('AUTOMAKE_OPTIONS');
1100   if ($var)
1101     {
1102       if ($var->has_conditional_contents)
1103         {
1104           msg_var ('unsupported', $var,
1105                    "`AUTOMAKE_OPTIONS' cannot have conditional contents");
1106         }
1107       foreach my $locvals ($var->value_as_list_recursive (cond_filter => TRUE,
1108                                                           location => 1))
1109         {
1110           my ($loc, $value) = @$locvals;
1111           return 1 if (process_option_list ($loc, $value))
1112         }
1113     }
1115   if ($strictness == GNITS)
1116     {
1117       set_option ('readme-alpha', INTERNAL);
1118       set_option ('std-options', INTERNAL);
1119       set_option ('check-news', INTERNAL);
1120     }
1122   return 0;
1125 # shadow_unconditionally ($varname, $where)
1126 # -----------------------------------------
1127 # Return a $(variable) that contains all possible values
1128 # $varname can take.
1129 # If the VAR wasn't defined conditionally, return $(VAR).
1130 # Otherwise we create a am__VAR_DIST variable which contains
1131 # all possible values, and return $(am__VAR_DIST).
1132 sub shadow_unconditionally ($$)
1134   my ($varname, $where) = @_;
1135   my $var = var $varname;
1136   if ($var->has_conditional_contents)
1137     {
1138       $varname = "am__${varname}_DIST";
1139       my @files = uniq ($var->value_as_list_recursive);
1140       define_pretty_variable ($varname, TRUE, $where, @files);
1141     }
1142   return "\$($varname)"
1145 # get_object_extension ($EXTENSION)
1146 # ---------------------------------
1147 # Prefix $EXTENSION with $U if ansi2knr is in use.
1148 sub get_object_extension ($)
1150     my ($extension) = @_;
1152     # Check for automatic de-ANSI-fication.
1153     $extension = '$U' . $extension
1154       if option 'ansi2knr';
1156     $get_object_extension_was_run = 1;
1158     return $extension;
1161 # check_user_variables (@LIST)
1162 # ----------------------------
1163 # Make sure each variable VAR in @LIST does not exist, suggest using AM_VAR
1164 # otherwise.
1165 sub check_user_variables (@)
1167   my @dont_override = @_;
1168   foreach my $flag (@dont_override)
1169     {
1170       my $var = var $flag;
1171       if ($var)
1172         {
1173           for my $cond ($var->conditions->conds)
1174             {
1175               if ($var->rdef ($cond)->owner == VAR_MAKEFILE)
1176                 {
1177                   msg_cond_var ('gnu', $cond, $flag,
1178                                 "`$flag' is a user variable, "
1179                                 . "you should not override it;\n"
1180                                 . "use `AM_$flag' instead.");
1181                 }
1182             }
1183         }
1184     }
1187 # Call finish function for each language that was used.
1188 sub handle_languages
1190     if (! option 'no-dependencies')
1191     {
1192         # Include auto-dep code.  Don't include it if DEP_FILES would
1193         # be empty.
1194         if (&saw_sources_p (0) && keys %dep_files)
1195         {
1196             # Set location of depcomp.
1197             &define_variable ('depcomp',
1198                               "\$(SHELL) $am_config_aux_dir/depcomp",
1199                               INTERNAL);
1200             &define_variable ('am__depfiles_maybe', 'depfiles', INTERNAL);
1202             require_conf_file ("$am_file.am", FOREIGN, 'depcomp');
1204             my @deplist = sort keys %dep_files;
1205             # Generate each `include' individually.  Irix 6 make will
1206             # not properly include several files resulting from a
1207             # variable expansion; generating many separate includes
1208             # seems safest.
1209             $output_rules .= "\n";
1210             foreach my $iter (@deplist)
1211             {
1212                 $output_rules .= (subst ('AMDEP_TRUE')
1213                                   . subst ('am__include')
1214                                   . ' '
1215                                   . subst ('am__quote')
1216                                   . $iter
1217                                   . subst ('am__quote')
1218                                   . "\n");
1219             }
1221             # Compute the set of directories to remove in distclean-depend.
1222             my @depdirs = uniq (map { dirname ($_) } @deplist);
1223             $output_rules .= &file_contents ('depend',
1224                                              new Automake::Location,
1225                                              DEPDIRS => "@depdirs");
1226         }
1227     }
1228     else
1229     {
1230         &define_variable ('depcomp', '', INTERNAL);
1231         &define_variable ('am__depfiles_maybe', '', INTERNAL);
1232     }
1234     my %done;
1236     # Is the c linker needed?
1237     my $needs_c = 0;
1238     foreach my $ext (sort keys %extension_seen)
1239     {
1240         next unless $extension_map{$ext};
1242         my $lang = $languages{$extension_map{$ext}};
1244         my $rule_file = $lang->rule_file || 'depend2';
1246         # Get information on $LANG.
1247         my $pfx = $lang->autodep;
1248         my $fpfx = ($pfx eq '') ? 'CC' : $pfx;
1250         my ($AMDEP, $FASTDEP) =
1251           (option 'no-dependencies' || $lang->autodep eq 'no')
1252           ? ('FALSE', 'FALSE') : ('AMDEP', "am__fastdep$fpfx");
1254         my %transform = ('EXT'     => $ext,
1255                          'PFX'     => $pfx,
1256                          'FPFX'    => $fpfx,
1257                          'AMDEP'   => $AMDEP,
1258                          'FASTDEP' => $FASTDEP,
1259                          '-c'      => $lang->compile_flag || '',
1260                          # These are not used, but they need to be defined
1261                          # so &transform do not complain.
1262                          SUBDIROBJ     => 0,
1263                          'DERIVED-EXT' => 'BUG',
1264                          DIST_SOURCE   => 1,
1265                         );
1267         # Generate the appropriate rules for this extension.
1268         if (((! option 'no-dependencies') && $lang->autodep ne 'no')
1269             || defined $lang->compile)
1270         {
1271             # Some C compilers don't support -c -o.  Use it only if really
1272             # needed.
1273             my $output_flag = $lang->output_flag || '';
1274             $output_flag = '-o'
1275               if (! $output_flag
1276                   && $lang->name eq 'c'
1277                   && option 'subdir-objects');
1279             # Compute a possible derived extension.
1280             # This is not used by depend2.am.
1281             my $der_ext = (&{$lang->output_extensions} ($ext))[0];
1283             # When we output an inference rule like `.c.o:' we
1284             # have two cases to consider: either subdir-objects
1285             # is used, or it is not.
1286             #
1287             # In the latter case the rule is used to build objects
1288             # in the current directory, and dependencies always
1289             # go into `./$(DEPDIR)/'.  We can hard-code this value.
1290             #
1291             # In the former case the rule can be used to build
1292             # objects in sub-directories too.  Dependencies should
1293             # go into the appropriate sub-directories, e.g.,
1294             # `sub/$(DEPDIR)/'.  The value of this directory
1295             # needs to be computed on-the-fly.
1296             #
1297             # DEPBASE holds the name of this directory, plus the
1298             # basename part of the object file (extensions Po, TPo,
1299             # Plo, TPlo will be added later as appropriate).  It is
1300             # either hardcoded, or a shell variable (`$depbase') that
1301             # will be computed by the rule.
1302             my $depbase =
1303               option ('subdir-objects') ? '$$depbase' : '$(DEPDIR)/$*';
1304             $output_rules .=
1305               file_contents ($rule_file,
1306                              new Automake::Location,
1307                              %transform,
1308                              GENERIC   => 1,
1310                              'DERIVED-EXT' => $der_ext,
1312                              DEPBASE   => $depbase,
1313                              BASE      => '$*',
1314                              SOURCE    => '$<',
1315                              SOURCEFLAG => $sourceflags{$ext} || '',
1316                              OBJ       => '$@',
1317                              OBJOBJ    => '$@',
1318                              LTOBJ     => '$@',
1320                              COMPILE   => '$(' . $lang->compiler . ')',
1321                              LTCOMPILE => '$(LT' . $lang->compiler . ')',
1322                              -o        => $output_flag,
1323                              SUBDIROBJ => !! option 'subdir-objects');
1324         }
1326         # Now include code for each specially handled object with this
1327         # language.
1328         my %seen_files = ();
1329         foreach my $file (@{$lang_specific_files{$lang->name}})
1330         {
1331             my ($derived, $source, $obj, $myext, $srcext, %file_transform) = @$file;
1333             # We might see a given object twice, for instance if it is
1334             # used under different conditions.
1335             next if defined $seen_files{$obj};
1336             $seen_files{$obj} = 1;
1338             prog_error ("found " . $lang->name .
1339                         " in handle_languages, but compiler not defined")
1340               unless defined $lang->compile;
1342             my $obj_compile = $lang->compile;
1344             # Rewrite each occurrence of `AM_$flag' in the compile
1345             # rule into `${derived}_$flag' if it exists.
1346             for my $flag (@{$lang->flags})
1347               {
1348                 my $val = "${derived}_$flag";
1349                 $obj_compile =~ s/\(AM_$flag\)/\($val\)/
1350                   if set_seen ($val);
1351               }
1353             my $libtool_tag = '';
1354             if ($lang->libtool_tag && exists $libtool_tags{$lang->libtool_tag})
1355               {
1356                 $libtool_tag = '--tag=' . $lang->libtool_tag . ' '
1357               }
1359             my $ptltflags = "${derived}_LIBTOOLFLAGS";
1360             $ptltflags = 'AM_LIBTOOLFLAGS' unless set_seen $ptltflags;
1362             my $obj_ltcompile =
1363               "\$(LIBTOOL) $libtool_tag\$($ptltflags) \$(LIBTOOLFLAGS) "
1364               . "--mode=compile $obj_compile";
1366             # We _need_ `-o' for per object rules.
1367             my $output_flag = $lang->output_flag || '-o';
1369             my $depbase = dirname ($obj);
1370             $depbase = ''
1371                 if $depbase eq '.';
1372             $depbase .= '/'
1373                 unless $depbase eq '';
1374             $depbase .= '$(DEPDIR)/' . basename ($obj);
1376             # Support for deansified files in subdirectories is ugly
1377             # enough to deserve an explanation.
1378             #
1379             # A Note about normal ansi2knr processing first.  On
1380             #
1381             #   AUTOMAKE_OPTIONS = ansi2knr
1382             #   bin_PROGRAMS = foo
1383             #   foo_SOURCES = foo.c
1384             #
1385             # we generate rules similar to:
1386             #
1387             #   foo: foo$U.o; link ...
1388             #   foo$U.o: foo$U.c; compile ...
1389             #   foo_.c: foo.c; ansi2knr ...
1390             #
1391             # this is fairly compact, and will call ansi2knr depending
1392             # on the value of $U (`' or `_').
1393             #
1394             # It's harder with subdir sources. On
1395             #
1396             #   AUTOMAKE_OPTIONS = ansi2knr
1397             #   bin_PROGRAMS = foo
1398             #   foo_SOURCES = sub/foo.c
1399             #
1400             # we have to create foo_.c in the current directory.
1401             # (Unless the user asks 'subdir-objects'.)  This is important
1402             # in case the same file (`foo.c') is compiled from other
1403             # directories with different cpp options: foo_.c would
1404             # be preprocessed for only one set of options if it were
1405             # put in the subdirectory.
1406             #
1407             # Because foo$U.o must be built from either foo_.c or
1408             # sub/foo.c we can't be as concise as in the first example.
1409             # Instead we output
1410             #
1411             #   foo: foo$U.o; link ...
1412             #   foo_.o: foo_.c; compile ...
1413             #   foo.o: sub/foo.c; compile ...
1414             #   foo_.c: foo.c; ansi2knr ...
1415             #
1416             # This is why we'll now transform $rule_file twice
1417             # if we detect this case.
1418             # A first time we output the compile rule with `$U'
1419             # replaced by `_' and the source directory removed,
1420             # and another time we simply remove `$U'.
1421             #
1422             # Note that at this point $source (as computed by
1423             # &handle_single_transform) is `sub/foo$U.c'.
1424             # This can be confusing: it can be used as-is when
1425             # subdir-objects is set, otherwise you have to know
1426             # it really means `foo_.c' or `sub/foo.c'.
1427             my $objdir = dirname ($obj);
1428             my $srcdir = dirname ($source);
1429             if ($lang->ansi && $obj =~ /\$U/)
1430               {
1431                 prog_error "`$obj' contains \$U, but `$source' doesn't."
1432                   if $source !~ /\$U/;
1434                 (my $source_ = $source) =~ s/\$U/_/g;
1435                 # Output an additional rule if _.c and .c are not in
1436                 # the same directory.  (_.c is always in $objdir.)
1437                 if ($objdir ne $srcdir)
1438                   {
1439                     (my $obj_ = $obj) =~ s/\$U/_/g;
1440                     (my $depbase_ = $depbase) =~ s/\$U/_/g;
1441                     $source_ = basename ($source_);
1443                     $output_rules .=
1444                       file_contents ($rule_file,
1445                                      new Automake::Location,
1446                                      %transform,
1447                                      GENERIC   => 0,
1449                                      DEPBASE   => $depbase_,
1450                                      BASE      => $obj_,
1451                                      SOURCE    => $source_,
1452                                      SOURCEFLAG => $sourceflags{$srcext} || '',
1453                                      OBJ       => "$obj_$myext",
1454                                      OBJOBJ    => "$obj_.obj",
1455                                      LTOBJ     => "$obj_.lo",
1457                                      COMPILE   => $obj_compile,
1458                                      LTCOMPILE => $obj_ltcompile,
1459                                      -o        => $output_flag,
1460                                      %file_transform);
1461                     $obj =~ s/\$U//g;
1462                     $depbase =~ s/\$U//g;
1463                     $source =~ s/\$U//g;
1464                   }
1465               }
1467             $output_rules .=
1468               file_contents ($rule_file,
1469                              new Automake::Location,
1470                              %transform,
1471                              GENERIC   => 0,
1473                              DEPBASE   => $depbase,
1474                              BASE      => $obj,
1475                              SOURCE    => $source,
1476                              SOURCEFLAG => $sourceflags{$srcext} || '',
1477                              # Use $myext and not `.o' here, in case
1478                              # we are actually building a new source
1479                              # file -- e.g. via yacc.
1480                              OBJ       => "$obj$myext",
1481                              OBJOBJ    => "$obj.obj",
1482                              LTOBJ     => "$obj.lo",
1484                              COMPILE   => $obj_compile,
1485                              LTCOMPILE => $obj_ltcompile,
1486                              -o        => $output_flag,
1487                              %file_transform);
1488         }
1490         # The rest of the loop is done once per language.
1491         next if defined $done{$lang};
1492         $done{$lang} = 1;
1494         # Load the language dependent Makefile chunks.
1495         my %lang = map { uc ($_) => 0 } keys %languages;
1496         $lang{uc ($lang->name)} = 1;
1497         $output_rules .= file_contents ('lang-compile',
1498                                         new Automake::Location,
1499                                         %transform, %lang);
1501         # If the source to a program consists entirely of code from a
1502         # `pure' language, for instance C++ or Fortran 77, then we
1503         # don't need the C compiler code.  However if we run into
1504         # something unusual then we do generate the C code.  There are
1505         # probably corner cases here that do not work properly.
1506         # People linking Java code to Fortran code deserve pain.
1507         $needs_c ||= ! $lang->pure;
1509         define_compiler_variable ($lang)
1510           if ($lang->compile);
1512         define_linker_variable ($lang)
1513           if ($lang->link);
1515         require_variables ("$am_file.am", $lang->Name . " source seen",
1516                            TRUE, @{$lang->config_vars});
1518         # Call the finisher.
1519         $lang->finish;
1521         # Flags listed in `->flags' are user variables (per GNU Standards),
1522         # they should not be overridden in the Makefile...
1523         my @dont_override = @{$lang->flags};
1524         # ... and so is LDFLAGS.
1525         push @dont_override, 'LDFLAGS' if $lang->link;
1527         check_user_variables @dont_override;
1528     }
1530     # If the project is entirely C++ or entirely Fortran 77 (i.e., 1
1531     # suffix rule was learned), don't bother with the C stuff.  But if
1532     # anything else creeps in, then use it.
1533     $needs_c = 1
1534       if $need_link || suffix_rules_count > 1;
1536     if ($needs_c)
1537       {
1538         &define_compiler_variable ($languages{'c'})
1539           unless defined $done{$languages{'c'}};
1540         define_linker_variable ($languages{'c'});
1541       }
1545 # append_exeext { PREDICATE } $MACRO
1546 # ----------------------------------
1547 # Append $(EXEEXT) to each filename in $F appearing in the Makefile
1548 # variable $MACRO if &PREDICATE($F) is true.  @substitutions@ are
1549 # ignored.
1551 # This is typically used on all filenames of *_PROGRAMS, and filenames
1552 # of TESTS that are programs.
1553 sub append_exeext (&$)
1555   my ($pred, $macro) = @_;
1557   transform_variable_recursively
1558     ($macro, $macro, 'am__EXEEXT', 0, INTERNAL,
1559      sub {
1560        my ($subvar, $val, $cond, $full_cond) = @_;
1561        # Append $(EXEEXT) unless the user did it already, or it's a
1562        # @substitution@.
1563        $val .= '$(EXEEXT)'
1564          if $val !~ /(?:\$\(EXEEXT\)$|^[@]\w+[@]$)/ && &$pred ($val);
1565        return $val;
1566      });
1570 # Check to make sure a source defined in LIBOBJS is not explicitly
1571 # mentioned.  This is a separate function (as opposed to being inlined
1572 # in handle_source_transform) because it isn't always appropriate to
1573 # do this check.
1574 sub check_libobjs_sources
1576   my ($one_file, $unxformed) = @_;
1578   foreach my $prefix ('', 'EXTRA_', 'dist_', 'nodist_',
1579                       'dist_EXTRA_', 'nodist_EXTRA_')
1580     {
1581       my @files;
1582       my $varname = $prefix . $one_file . '_SOURCES';
1583       my $var = var ($varname);
1584       if ($var)
1585         {
1586           @files = $var->value_as_list_recursive;
1587         }
1588       elsif ($prefix eq '')
1589         {
1590           @files = ($unxformed . '.c');
1591         }
1592       else
1593         {
1594           next;
1595         }
1597       foreach my $file (@files)
1598         {
1599           err_var ($prefix . $one_file . '_SOURCES',
1600                    "automatically discovered file `$file' should not" .
1601                    " be explicitly mentioned")
1602             if defined $libsources{$file};
1603         }
1604     }
1608 # @OBJECTS
1609 # handle_single_transform ($VAR, $TOPPARENT, $DERIVED, $OBJ, $FILE, %TRANSFORM)
1610 # -----------------------------------------------------------------------------
1611 # Does much of the actual work for handle_source_transform.
1612 # Arguments are:
1613 #   $VAR is the name of the variable that the source filenames come from
1614 #   $TOPPARENT is the name of the _SOURCES variable which is being processed
1615 #   $DERIVED is the name of resulting executable or library
1616 #   $OBJ is the object extension (e.g., `$U.lo')
1617 #   $FILE the source file to transform
1618 #   %TRANSFORM contains extras arguments to pass to file_contents
1619 #     when producing explicit rules
1620 # Result is a list of the names of objects
1621 # %linkers_used will be updated with any linkers needed
1622 sub handle_single_transform ($$$$$%)
1624     my ($var, $topparent, $derived, $obj, $_file, %transform) = @_;
1625     my @files = ($_file);
1626     my @result = ();
1627     my $nonansi_obj = $obj;
1628     $nonansi_obj =~ s/\$U//g;
1630     # Turn sources into objects.  We use a while loop like this
1631     # because we might add to @files in the loop.
1632     while (scalar @files > 0)
1633     {
1634         $_ = shift @files;
1636         # Configure substitutions in _SOURCES variables are errors.
1637         if (/^\@.*\@$/)
1638         {
1639           my $parent_msg = '';
1640           $parent_msg = "\nand is referred to from `$topparent'"
1641             if $topparent ne $var->name;
1642           err_var ($var,
1643                    "`" . $var->name . "' includes configure substitution `$_'"
1644                    . $parent_msg . ";\nconfigure " .
1645                    "substitutions are not allowed in _SOURCES variables");
1646           next;
1647         }
1649         # If the source file is in a subdirectory then the `.o' is put
1650         # into the current directory, unless the subdir-objects option
1651         # is in effect.
1653         # Split file name into base and extension.
1654         next if ! /^(?:(.*)\/)?([^\/]*)($KNOWN_EXTENSIONS_PATTERN)$/;
1655         my $full = $_;
1656         my $directory = $1 || '';
1657         my $base = $2;
1658         my $extension = $3;
1660         # We must generate a rule for the object if it requires its own flags.
1661         my $renamed = 0;
1662         my ($linker, $object);
1664         # This records whether we've seen a derived source file (e.g.
1665         # yacc output).
1666         my $derived_source = 0;
1668         # This holds the `aggregate context' of the file we are
1669         # currently examining.  If the file is compiled with
1670         # per-object flags, then it will be the name of the object.
1671         # Otherwise it will be `AM'.  This is used by the target hook
1672         # language function.
1673         my $aggregate = 'AM';
1675         $extension = &derive_suffix ($extension, $nonansi_obj);
1676         my $lang;
1677         if ($extension_map{$extension} &&
1678             ($lang = $languages{$extension_map{$extension}}))
1679         {
1680             # Found the language, so see what it says.
1681             &saw_extension ($extension);
1683             # Do we have per-executable flags for this executable?
1684             my $have_per_exec_flags = 0;
1685             my @peflags = @{$lang->flags};
1686             push @peflags, 'LIBTOOLFLAGS' if $nonansi_obj eq '.lo';
1687             foreach my $flag (@peflags)
1688               {
1689                 if (set_seen ("${derived}_$flag"))
1690                   {
1691                     $have_per_exec_flags = 1;
1692                     last;
1693                   }
1694               }
1696             # Note: computed subr call.  The language rewrite function
1697             # should return one of the LANG_* constants.  It could
1698             # also return a list whose first value is such a constant
1699             # and whose second value is a new source extension which
1700             # should be applied.  This means this particular language
1701             # generates another source file which we must then process
1702             # further.
1703             my $subr = \&{'lang_' . $lang->name . '_rewrite'};
1704             my ($r, $source_extension)
1705                 = &$subr ($directory, $base, $extension,
1706                           $nonansi_obj, $have_per_exec_flags, $var);
1707             # Skip this entry if we were asked not to process it.
1708             next if $r == LANG_IGNORE;
1710             # Now extract linker and other info.
1711             $linker = $lang->linker;
1713             my $this_obj_ext;
1714             if (defined $source_extension)
1715             {
1716                 $this_obj_ext = $source_extension;
1717                 $derived_source = 1;
1718             }
1719             elsif ($lang->ansi)
1720             {
1721                 $this_obj_ext = $obj;
1722             }
1723             else
1724             {
1725                 $this_obj_ext = $nonansi_obj;
1726             }
1727             $object = $base . $this_obj_ext;
1729             if ($have_per_exec_flags)
1730             {
1731                 # We have a per-executable flag in effect for this
1732                 # object.  In this case we rewrite the object's
1733                 # name to ensure it is unique.
1735                 # We choose the name `DERIVED_OBJECT' to ensure
1736                 # (1) uniqueness, and (2) continuity between
1737                 # invocations.  However, this will result in a
1738                 # name that is too long for losing systems, in
1739                 # some situations.  So we provide _SHORTNAME to
1740                 # override.
1742                 my $dname = $derived;
1743                 my $var = var ($derived . '_SHORTNAME');
1744                 if ($var)
1745                 {
1746                     # FIXME: should use the same Condition as
1747                     # the _SOURCES variable.  But this is really
1748                     # silly overkill -- nobody should have
1749                     # conditional shortnames.
1750                     $dname = $var->variable_value;
1751                 }
1752                 $object = $dname . '-' . $object;
1754                 prog_error ($lang->name . " flags defined without compiler")
1755                   if ! defined $lang->compile;
1757                 $renamed = 1;
1758             }
1760             # If rewrite said it was ok, put the object into a
1761             # subdir.
1762             if ($r == LANG_SUBDIR && $directory ne '')
1763             {
1764                 $object = $directory . '/' . $object;
1765             }
1767             # If the object file has been renamed (because per-target
1768             # flags are used) we cannot compile the file with an
1769             # inference rule: we need an explicit rule.
1770             #
1771             # If the source is in a subdirectory and the object is in
1772             # the current directory, we also need an explicit rule.
1773             #
1774             # If both source and object files are in a subdirectory
1775             # (this happens when the subdir-objects option is used),
1776             # then the inference will work.
1777             #
1778             # The latter case deserves a historical note.  When the
1779             # subdir-objects option was added on 1999-04-11 it was
1780             # thought that inferences rules would work for
1781             # subdirectory objects too.  Later, on 1999-11-22,
1782             # automake was changed to output explicit rules even for
1783             # subdir-objects.  Nobody remembers why, but this occurred
1784             # soon after the merge of the user-dep-gen-branch so it
1785             # might be related.  In late 2003 people complained about
1786             # the size of the generated Makefile.ins (libgcj, with
1787             # 2200+ subdir objects was reported to have a 9MB
1788             # Makefile), so we now rely on inference rules again.
1789             # Maybe we'll run across the same issue as in the past,
1790             # but at least this time we can document it.  However since
1791             # dependency tracking has evolved it is possible that
1792             # our old problem no longer exists.
1793             # Using inference rules for subdir-objects has been tested
1794             # with GNU make, Solaris make, Ultrix make, BSD make,
1795             # HP-UX make, and OSF1 make successfully.
1796             if ($renamed
1797                 || ($directory ne '' && ! option 'subdir-objects')
1798                 # We must also use specific rules for a nodist_ source
1799                 # if its language requests it.
1800                 || ($lang->nodist_specific && ! $transform{'DIST_SOURCE'}))
1801             {
1802                 my $obj_sans_ext = substr ($object, 0,
1803                                            - length ($this_obj_ext));
1804                 my $full_ansi = $full;
1805                 if ($lang->ansi && option 'ansi2knr')
1806                   {
1807                     $full_ansi =~ s/$KNOWN_EXTENSIONS_PATTERN$/\$U$&/;
1808                     $obj_sans_ext .= '$U';
1809                   }
1811                 my @specifics = ($full_ansi, $obj_sans_ext,
1812                                  # Only use $this_obj_ext in the derived
1813                                  # source case because in the other case we
1814                                  # *don't* want $(OBJEXT) to appear here.
1815                                  ($derived_source ? $this_obj_ext : '.o'),
1816                                  $extension);
1818                 # If we renamed the object then we want to use the
1819                 # per-executable flag name.  But if this is simply a
1820                 # subdir build then we still want to use the AM_ flag
1821                 # name.
1822                 if ($renamed)
1823                   {
1824                     unshift @specifics, $derived;
1825                     $aggregate = $derived;
1826                   }
1827                 else
1828                   {
1829                     unshift @specifics, 'AM';
1830                   }
1832                 # Each item on this list is a reference to a list consisting
1833                 # of four values followed by additional transform flags for
1834                 # file_contents.   The four values are the derived flag prefix
1835                 # (e.g. for `foo_CFLAGS', it is `foo'), the name of the
1836                 # source file, the base name of the output file, and
1837                 # the extension for the object file.
1838                 push (@{$lang_specific_files{$lang->name}},
1839                       [@specifics, %transform]);
1840             }
1841         }
1842         elsif ($extension eq $nonansi_obj)
1843         {
1844             # This is probably the result of a direct suffix rule.
1845             # In this case we just accept the rewrite.
1846             $object = "$base$extension";
1847             $object = "$directory/$object" if $directory ne '';
1848             $linker = '';
1849         }
1850         else
1851         {
1852             # No error message here.  Used to have one, but it was
1853             # very unpopular.
1854             # FIXME: we could potentially do more processing here,
1855             # perhaps treating the new extension as though it were a
1856             # new source extension (as above).  This would require
1857             # more restructuring than is appropriate right now.
1858             next;
1859         }
1861         err_am "object `$object' created by `$full' and `$object_map{$object}'"
1862           if (defined $object_map{$object}
1863               && $object_map{$object} ne $full);
1865         my $comp_val = (($object =~ /\.lo$/)
1866                         ? COMPILE_LIBTOOL : COMPILE_ORDINARY);
1867         (my $comp_obj = $object) =~ s/\.lo$/.\$(OBJEXT)/;
1868         if (defined $object_compilation_map{$comp_obj}
1869             && $object_compilation_map{$comp_obj} != 0
1870             # Only see the error once.
1871             && ($object_compilation_map{$comp_obj}
1872                 != (COMPILE_LIBTOOL | COMPILE_ORDINARY))
1873             && $object_compilation_map{$comp_obj} != $comp_val)
1874           {
1875             err_am "object `$comp_obj' created both with libtool and without";
1876           }
1877         $object_compilation_map{$comp_obj} |= $comp_val;
1879         if (defined $lang)
1880         {
1881             # Let the language do some special magic if required.
1882             $lang->target_hook ($aggregate, $object, $full, %transform);
1883         }
1885         if ($derived_source)
1886           {
1887             prog_error ($lang->name . " has automatic dependency tracking")
1888               if $lang->autodep ne 'no';
1889             # Make sure this new source file is handled next.  That will
1890             # make it appear to be at the right place in the list.
1891             unshift (@files, $object);
1892             # Distribute derived sources unless the source they are
1893             # derived from is not.
1894             &push_dist_common ($object)
1895               unless ($topparent =~ /^(?:nobase_)?nodist_/);
1896             next;
1897           }
1899         $linkers_used{$linker} = 1;
1901         push (@result, $object);
1903         if (! defined $object_map{$object})
1904         {
1905             my @dep_list = ();
1906             $object_map{$object} = $full;
1908             # If resulting object is in subdir, we need to make
1909             # sure the subdir exists at build time.
1910             if ($object =~ /\//)
1911             {
1912                 # FIXME: check that $DIRECTORY is somewhere in the
1913                 # project
1915                 # For Java, the way we're handling it right now, a
1916                 # `..' component doesn't make sense.
1917                 if ($lang && $lang->name eq 'java' && $object =~ /(\/|^)\.\.\//)
1918                   {
1919                     err_am "`$full' should not contain a `..' component";
1920                   }
1922                 # Make sure object is removed by `make mostlyclean'.
1923                 $compile_clean_files{$object} = MOSTLY_CLEAN;
1924                 # If we have a libtool object then we also must remove
1925                 # the ordinary .o.
1926                 if ($object =~ /\.lo$/)
1927                 {
1928                     (my $xobj = $object) =~ s,lo$,\$(OBJEXT),;
1929                     $compile_clean_files{$xobj} = MOSTLY_CLEAN;
1931                     # Remove any libtool object in this directory.
1932                     $libtool_clean_directories{$directory} = 1;
1933                 }
1935                 push (@dep_list, require_build_directory ($directory));
1937                 # If we're generating dependencies, we also want
1938                 # to make sure that the appropriate subdir of the
1939                 # .deps directory is created.
1940                 push (@dep_list,
1941                       require_build_directory ($directory . '/$(DEPDIR)'))
1942                   unless option 'no-dependencies';
1943             }
1945             &pretty_print_rule ($object . ':', "\t", @dep_list)
1946                 if scalar @dep_list > 0;
1947         }
1949         # Transform .o or $o file into .P file (for automatic
1950         # dependency code).
1951         if ($lang && $lang->autodep ne 'no')
1952         {
1953             my $depfile = $object;
1954             $depfile =~ s/\.([^.]*)$/.P$1/;
1955             $depfile =~ s/\$\(OBJEXT\)$/o/;
1956             $dep_files{dirname ($depfile) . '/$(DEPDIR)/'
1957                          . basename ($depfile)} = 1;
1958         }
1959     }
1961     return @result;
1965 # $LINKER
1966 # define_objects_from_sources ($VAR, $OBJVAR, $NODEFINE, $ONE_FILE,
1967 #                              $OBJ, $PARENT, $TOPPARENT, $WHERE, %TRANSFORM)
1968 # ---------------------------------------------------------------------------
1969 # Define an _OBJECTS variable for a _SOURCES variable (or subvariable)
1971 # Arguments are:
1972 #   $VAR is the name of the _SOURCES variable
1973 #   $OBJVAR is the name of the _OBJECTS variable if known (otherwise
1974 #     it will be generated and returned).
1975 #   $NODEFINE is a boolean: if true, $OBJVAR will not be defined (but
1976 #     work done to determine the linker will be).
1977 #   $ONE_FILE is the canonical (transformed) name of object to build
1978 #   $OBJ is the object extension (i.e. either `.o' or `.lo').
1979 #   $TOPPARENT is the _SOURCES variable being processed.
1980 #   $WHERE context into which this definition is done
1981 #   %TRANSFORM extra arguments to pass to file_contents when producing
1982 #     rules
1984 # Result is a pair ($LINKER, $OBJVAR):
1985 #    $LINKER is a boolean, true if a linker is needed to deal with the objects
1986 sub define_objects_from_sources ($$$$$$$%)
1988   my ($var, $objvar, $nodefine, $one_file,
1989       $obj, $topparent, $where, %transform) = @_;
1991   my $needlinker = "";
1993   transform_variable_recursively
1994     ($var, $objvar, 'am__objects', $nodefine, $where,
1995      # The transform code to run on each filename.
1996      sub {
1997        my ($subvar, $val, $cond, $full_cond) = @_;
1998        my @trans = handle_single_transform ($subvar, $topparent,
1999                                             $one_file, $obj, $val,
2000                                             %transform);
2001        $needlinker = "true" if @trans;
2002        return @trans;
2003      });
2005   return $needlinker;
2009 # handle_source_transform ($CANON_TARGET, $TARGET, $OBJEXT, $WHERE, %TRANSFORM)
2010 # -----------------------------------------------------------------------------
2011 # Handle SOURCE->OBJECT transform for one program or library.
2012 # Arguments are:
2013 #   canonical (transformed) name of target to build
2014 #   actual target of object to build
2015 #   object extension (i.e., either `.o' or `$o')
2016 #   location of the source variable
2017 #   extra arguments to pass to file_contents when producing rules
2018 # Return the name of the linker variable that must be used.
2019 # Empty return means just use `LINK'.
2020 sub handle_source_transform ($$$$%)
2022     # one_file is canonical name.  unxformed is given name.  obj is
2023     # object extension.
2024     my ($one_file, $unxformed, $obj, $where, %transform) = @_;
2026     my $linker = '';
2028     # No point in continuing if _OBJECTS is defined.
2029     return if reject_var ($one_file . '_OBJECTS',
2030                           $one_file . '_OBJECTS should not be defined');
2032     my %used_pfx = ();
2033     my $needlinker;
2034     %linkers_used = ();
2035     foreach my $prefix ('', 'EXTRA_', 'dist_', 'nodist_',
2036                         'dist_EXTRA_', 'nodist_EXTRA_')
2037     {
2038         my $varname = $prefix . $one_file . "_SOURCES";
2039         my $var = var $varname;
2040         next unless $var;
2042         # We are going to define _OBJECTS variables using the prefix.
2043         # Then we glom them all together.  So we can't use the null
2044         # prefix here as we need it later.
2045         my $xpfx = ($prefix eq '') ? 'am_' : $prefix;
2047         # Keep track of which prefixes we saw.
2048         $used_pfx{$xpfx} = 1
2049           unless $prefix =~ /EXTRA_/;
2051         push @sources, "\$($varname)";
2052         push @dist_sources, shadow_unconditionally ($varname, $where)
2053           unless (option ('no-dist') || $prefix =~ /^nodist_/);
2055         $needlinker |=
2056             define_objects_from_sources ($varname,
2057                                          $xpfx . $one_file . '_OBJECTS',
2058                                          $prefix =~ /EXTRA_/,
2059                                          $one_file, $obj, $varname, $where,
2060                                          DIST_SOURCE => ($prefix !~ /^nodist_/),
2061                                          %transform);
2062     }
2063     if ($needlinker)
2064     {
2065         $linker ||= &resolve_linker (%linkers_used);
2066     }
2068     my @keys = sort keys %used_pfx;
2069     if (scalar @keys == 0)
2070     {
2071         # The default source for libfoo.la is libfoo.c, but for
2072         # backward compatibility we first look at libfoo_la.c,
2073         # if no default source suffix is given.
2074         my $old_default_source = "$one_file.c";
2075         my $ext_var = var ('AM_DEFAULT_SOURCE_EXT');
2076         my $default_source_ext = $ext_var ? variable_value ($ext_var) : '.c';
2077         msg_var ('unsupported', $ext_var, $ext_var->name . " can assume at most one value")
2078           if $default_source_ext =~ /[\t ]/;
2079         (my $default_source = $unxformed) =~ s,(\.[^./\\]*)?$,$default_source_ext,;
2080         if ($old_default_source ne $default_source
2081             && !$ext_var
2082             && (rule $old_default_source
2083                 || rule '$(srcdir)/' . $old_default_source
2084                 || rule '${srcdir}/' . $old_default_source
2085                 || -f $old_default_source))
2086           {
2087             my $loc = $where->clone;
2088             $loc->pop_context;
2089             msg ('obsolete', $loc,
2090                  "the default source for `$unxformed' has been changed "
2091                  . "to `$default_source'.\n(Using `$old_default_source' for "
2092                  . "backward compatibility.)");
2093             $default_source = $old_default_source;
2094           }
2095         # If a rule exists to build this source with a $(srcdir)
2096         # prefix, use that prefix in our variables too.  This is for
2097         # the sake of BSD Make.
2098         if (rule '$(srcdir)/' . $default_source
2099             || rule '${srcdir}/' . $default_source)
2100           {
2101             $default_source = '$(srcdir)/' . $default_source;
2102           }
2104         &define_variable ($one_file . "_SOURCES", $default_source, $where);
2105         push (@sources, $default_source);
2106         push (@dist_sources, $default_source);
2108         %linkers_used = ();
2109         my (@result) =
2110           handle_single_transform ($one_file . '_SOURCES',
2111                                    $one_file . '_SOURCES',
2112                                    $one_file, $obj,
2113                                    $default_source, %transform);
2114         $linker ||= &resolve_linker (%linkers_used);
2115         define_pretty_variable ($one_file . '_OBJECTS', TRUE, $where, @result);
2116     }
2117     else
2118     {
2119         @keys = map { '$(' . $_ . $one_file . '_OBJECTS)' } @keys;
2120         define_pretty_variable ($one_file . '_OBJECTS', TRUE, $where, @keys);
2121     }
2123     # If we want to use `LINK' we must make sure it is defined.
2124     if ($linker eq '')
2125     {
2126         $need_link = 1;
2127     }
2129     return $linker;
2133 # handle_lib_objects ($XNAME, $VAR)
2134 # ---------------------------------
2135 # Special-case ALLOCA and LIBOBJS substitutions in _LDADD or _LIBADD variables.
2136 # Also, generate _DEPENDENCIES variable if appropriate.
2137 # Arguments are:
2138 #   transformed name of object being built, or empty string if no object
2139 #   name of _LDADD/_LIBADD-type variable to examine
2140 # Returns 1 if LIBOBJS seen, 0 otherwise.
2141 sub handle_lib_objects
2143   my ($xname, $varname) = @_;
2145   my $var = var ($varname);
2146   prog_error "handle_lib_objects: `$varname' undefined"
2147     unless $var;
2148   prog_error "handle_lib_objects: unexpected variable name `$varname'"
2149     unless $varname =~ /^(.*)(?:LIB|LD)ADD$/;
2150   my $prefix = $1 || 'AM_';
2152   my $seen_libobjs = 0;
2153   my $flagvar = 0;
2155   transform_variable_recursively
2156     ($varname, $xname . '_DEPENDENCIES', 'am__DEPENDENCIES',
2157      ! $xname, INTERNAL,
2158      # Transformation function, run on each filename.
2159      sub {
2160        my ($subvar, $val, $cond, $full_cond) = @_;
2162        if ($val =~ /^-/)
2163          {
2164            # Skip -lfoo and -Ldir silently; these are explicitly allowed.
2165            if ($val !~ /^-[lL]/ &&
2166                # Skip -dlopen and -dlpreopen; these are explicitly allowed
2167                # for Libtool libraries or programs.  (Actually we are a bit
2168                # laxe here since this code also applies to non-libtool
2169                # libraries or programs, for which -dlopen and -dlopreopen
2170                # are pure nonsense.  Diagnosing this doesn't seem very
2171                # important: the developer will quickly get complaints from
2172                # the linker.)
2173                $val !~ /^-dl(?:pre)?open$/ &&
2174                # Only get this error once.
2175                ! $flagvar)
2176              {
2177                $flagvar = 1;
2178                # FIXME: should display a stack of nested variables
2179                # as context when $var != $subvar.
2180                err_var ($var, "linker flags such as `$val' belong in "
2181                         . "`${prefix}LDFLAGS");
2182              }
2183            return ();
2184          }
2185        elsif ($val !~ /^\@.*\@$/)
2186          {
2187            # Assume we have a file of some sort, and output it into the
2188            # dependency variable.  Autoconf substitutions are not output;
2189            # rarely is a new dependency substituted into e.g. foo_LDADD
2190            # -- but bad things (e.g. -lX11) are routinely substituted.
2191            # Note that LIBOBJS and ALLOCA are exceptions to this rule,
2192            # and handled specially below.
2193            return $val;
2194          }
2195        elsif ($val =~ /^\@(LT)?LIBOBJS\@$/)
2196          {
2197            handle_LIBOBJS ($subvar, $cond, $1);
2198            $seen_libobjs = 1;
2199            return $val;
2200          }
2201        elsif ($val =~ /^\@(LT)?ALLOCA\@$/)
2202          {
2203            handle_ALLOCA ($subvar, $cond, $1);
2204            return $val;
2205          }
2206        else
2207          {
2208            return ();
2209          }
2210      });
2212   return $seen_libobjs;
2215 # handle_LIBOBJS_or_ALLOCA ($VAR)
2216 # -------------------------------
2217 # Definitions common to LIBOBJS and ALLOCA.
2218 # VAR should be one of LIBOBJS, LTLIBOBJS, ALLOCA, or LTALLOCA.
2219 sub handle_LIBOBJS_or_ALLOCA ($)
2221   my ($var) = @_;
2223   my $dir = '';
2225   # If LIBOBJS files must be built in another directory we have
2226   # to define LIBOBJDIR and ensure the files get cleaned.
2227   # Otherwise LIBOBJDIR can be left undefined, and the cleaning
2228   # is achieved by `rm -f *.$(OBJEXT)' in compile.am.
2229   if ($config_libobj_dir
2230       && $relative_dir ne $config_libobj_dir)
2231     {
2232       if (option 'subdir-objects')
2233         {
2234           # In the top-level Makefile we do not use $(top_builddir), because
2235           # we are already there, and since the targets are built without
2236           # a $(top_builddir), it helps BSD Make to match them with
2237           # dependencies.
2238           $dir = "$config_libobj_dir/" if $config_libobj_dir ne '.';
2239           $dir = "$topsrcdir/$dir" if $relative_dir ne '.';
2240           define_variable ('LIBOBJDIR', "$dir", INTERNAL);
2241           $clean_files{"\$($var)"} = MOSTLY_CLEAN;
2242           # If LTLIBOBJS is used, we must also clear LIBOBJS (which might
2243           # be created by libtool as a side-effect of creating LTLIBOBJS).
2244           $clean_files{"\$($var)"} = MOSTLY_CLEAN if $var =~ s/^LT//;
2245         }
2246       else
2247         {
2248           error ("`\$($var)' cannot be used outside `$config_libobj_dir' if"
2249                  . " `subdir-objects' is not set");
2250         }
2251     }
2253   return $dir;
2256 sub handle_LIBOBJS ($$$)
2258   my ($var, $cond, $lt) = @_;
2259   my $myobjext = $lt ? 'lo' : 'o';
2260   $lt ||= '';
2262   $var->requires_variables ("\@${lt}LIBOBJS\@ used", $lt . 'LIBOBJS')
2263     if ! keys %libsources;
2265   my $dir = handle_LIBOBJS_or_ALLOCA "${lt}LIBOBJS";
2267   foreach my $iter (keys %libsources)
2268     {
2269       if ($iter =~ /\.[cly]$/)
2270         {
2271           &saw_extension ($&);
2272           &saw_extension ('.c');
2273         }
2275       if ($iter =~ /\.h$/)
2276         {
2277           require_libsource_with_macro ($cond, $var, FOREIGN, $iter);
2278         }
2279       elsif ($iter ne 'alloca.c')
2280         {
2281           my $rewrite = $iter;
2282           $rewrite =~ s/\.c$/.P$myobjext/;
2283           $dep_files{$dir . '$(DEPDIR)/' . $rewrite} = 1;
2284           $rewrite = "^" . quotemeta ($iter) . "\$";
2285           # Only require the file if it is not a built source.
2286           my $bs = var ('BUILT_SOURCES');
2287           if (! $bs || ! grep (/$rewrite/, $bs->value_as_list_recursive))
2288             {
2289               require_libsource_with_macro ($cond, $var, FOREIGN, $iter);
2290             }
2291         }
2292     }
2295 sub handle_ALLOCA ($$$)
2297   my ($var, $cond, $lt) = @_;
2298   my $myobjext = $lt ? 'lo' : 'o';
2299   $lt ||= '';
2300   my $dir = handle_LIBOBJS_or_ALLOCA "${lt}ALLOCA";
2302   $var->requires_variables ("\@${lt}ALLOCA\@ used", $lt . 'ALLOCA');
2303   $dep_files{$dir . '$(DEPDIR)/alloca.P' . $myobjext} = 1;
2304   require_libsource_with_macro ($cond, $var, FOREIGN, 'alloca.c');
2305   &saw_extension ('.c');
2308 # Canonicalize the input parameter
2309 sub canonicalize
2311     my ($string) = @_;
2312     $string =~ tr/A-Za-z0-9_\@/_/c;
2313     return $string;
2316 # Canonicalize a name, and check to make sure the non-canonical name
2317 # is never used.  Returns canonical name.  Arguments are name and a
2318 # list of suffixes to check for.
2319 sub check_canonical_spelling
2321   my ($name, @suffixes) = @_;
2323   my $xname = &canonicalize ($name);
2324   if ($xname ne $name)
2325     {
2326       foreach my $xt (@suffixes)
2327         {
2328           reject_var ("$name$xt", "use `$xname$xt', not `$name$xt'");
2329         }
2330     }
2332   return $xname;
2336 # handle_compile ()
2337 # -----------------
2338 # Set up the compile suite.
2339 sub handle_compile ()
2341     return
2342       unless $get_object_extension_was_run;
2344     # Boilerplate.
2345     my $default_includes = '';
2346     if (! option 'nostdinc')
2347       {
2348         my @incs = ('-I.', subst ('am__isrc'));
2350         my $var = var 'CONFIG_HEADER';
2351         if ($var)
2352           {
2353             foreach my $hdr (split (' ', $var->variable_value))
2354               {
2355                 push @incs, '-I' . dirname ($hdr);
2356               }
2357           }
2358         # We want `-I. -I$(srcdir)', but the latter -I is redundant
2359         # and unaesthetic in non-VPATH builds.  We use `-I.@am__isrc@`
2360         # instead.  It will be replaced by '-I.' or '-I. -I$(srcdir)'.
2361         # Items in CONFIG_HEADER are never in $(srcdir) so it is safe
2362         # to just put @am__isrc@ right after `-I.', without a space.
2363         ($default_includes = ' ' . uniq (@incs)) =~ s/ @/@/;
2364       }
2366     my (@mostly_rms, @dist_rms);
2367     foreach my $item (sort keys %compile_clean_files)
2368     {
2369         if ($compile_clean_files{$item} == MOSTLY_CLEAN)
2370         {
2371             push (@mostly_rms, "\t-rm -f $item");
2372         }
2373         elsif ($compile_clean_files{$item} == DIST_CLEAN)
2374         {
2375             push (@dist_rms, "\t-rm -f $item");
2376         }
2377         else
2378         {
2379           prog_error 'invalid entry in %compile_clean_files';
2380         }
2381     }
2383     my ($coms, $vars, $rules) =
2384       &file_contents_internal (1, "$libdir/am/compile.am",
2385                                new Automake::Location,
2386                                ('DEFAULT_INCLUDES' => $default_includes,
2387                                 'MOSTLYRMS' => join ("\n", @mostly_rms),
2388                                 'DISTRMS' => join ("\n", @dist_rms)));
2389     $output_vars .= $vars;
2390     $output_rules .= "$coms$rules";
2392     # Check for automatic de-ANSI-fication.
2393     if (option 'ansi2knr')
2394       {
2395         my ($ansi2knr_filename, $ansi2knr_where) = @{option 'ansi2knr'};
2396         my $ansi2knr_dir = '';
2398         require_variables ($ansi2knr_where, "option `ansi2knr' is used",
2399                            TRUE, "ANSI2KNR", "U");
2401         # topdir is where ansi2knr should be.
2402         if ($ansi2knr_filename eq 'ansi2knr')
2403           {
2404             # Only require ansi2knr files if they should appear in
2405             # this directory.
2406             require_file ($ansi2knr_where, FOREIGN,
2407                           'ansi2knr.c', 'ansi2knr.1');
2409             # ansi2knr needs to be built before subdirs, so unshift it.
2410             unshift (@all, '$(ANSI2KNR)');
2411           }
2412         else
2413           {
2414             $ansi2knr_dir = dirname ($ansi2knr_filename);
2415           }
2417         $output_rules .= &file_contents ('ansi2knr',
2418                                          new Automake::Location,
2419                                          'ANSI2KNR-DIR' => $ansi2knr_dir);
2421     }
2424 # handle_libtool ()
2425 # -----------------
2426 # Handle libtool rules.
2427 sub handle_libtool
2429   return unless var ('LIBTOOL');
2431   # Libtool requires some files, but only at top level.
2432   # (Starting with Libtool 2.0 we do not have to bother.  These
2433   # requirements are done with AC_REQUIRE_AUX_FILE.)
2434   require_conf_file_with_macro (TRUE, 'LIBTOOL', FOREIGN, @libtool_files)
2435     if $relative_dir eq '.' && ! $libtool_new_api;
2437   my @libtool_rms;
2438   foreach my $item (sort keys %libtool_clean_directories)
2439     {
2440       my $dir = ($item eq '.') ? '' : "$item/";
2441       # .libs is for Unix, _libs for DOS.
2442       push (@libtool_rms, "\t-rm -rf ${dir}.libs ${dir}_libs");
2443     }
2445   check_user_variables 'LIBTOOLFLAGS';
2447   # Output the libtool compilation rules.
2448   $output_rules .= &file_contents ('libtool',
2449                                    new Automake::Location,
2450                                    LTRMS => join ("\n", @libtool_rms));
2453 # handle_programs ()
2454 # ------------------
2455 # Handle C programs.
2456 sub handle_programs
2458   my @proglist = &am_install_var ('progs', 'PROGRAMS',
2459                                   'bin', 'sbin', 'libexec', 'pkglib',
2460                                   'noinst', 'check');
2461   return if ! @proglist;
2463   my $seen_global_libobjs =
2464     var ('LDADD') && &handle_lib_objects ('', 'LDADD');
2466   foreach my $pair (@proglist)
2467     {
2468       my ($where, $one_file) = @$pair;
2470       my $seen_libobjs = 0;
2471       my $obj = get_object_extension '.$(OBJEXT)';
2473       # Strip any $(EXEEXT) suffix the user might have added, or this
2474       # will confuse &handle_source_transform and &check_canonical_spelling.
2475       # We'll add $(EXEEXT) back later anyway.
2476       $one_file =~ s/\$\(EXEEXT\)$//;
2478       $known_programs{$one_file} = $where;
2480       # Canonicalize names and check for misspellings.
2481       my $xname = &check_canonical_spelling ($one_file, '_LDADD', '_LDFLAGS',
2482                                              '_SOURCES', '_OBJECTS',
2483                                              '_DEPENDENCIES');
2485       $where->push_context ("while processing program `$one_file'");
2486       $where->set (INTERNAL->get);
2488       my $linker = &handle_source_transform ($xname, $one_file, $obj, $where,
2489                                              NONLIBTOOL => 1, LIBTOOL => 0);
2491       if (var ($xname . "_LDADD"))
2492         {
2493           $seen_libobjs = &handle_lib_objects ($xname, $xname . '_LDADD');
2494         }
2495       else
2496         {
2497           # User didn't define prog_LDADD override.  So do it.
2498           &define_variable ($xname . '_LDADD', '$(LDADD)', $where);
2500           # This does a bit too much work.  But we need it to
2501           # generate _DEPENDENCIES when appropriate.
2502           if (var ('LDADD'))
2503             {
2504               $seen_libobjs = &handle_lib_objects ($xname, 'LDADD');
2505             }
2506         }
2508       reject_var ($xname . '_LIBADD',
2509                   "use `${xname}_LDADD', not `${xname}_LIBADD'");
2511       set_seen ($xname . '_DEPENDENCIES');
2512       set_seen ($xname . '_LDFLAGS');
2514       # Determine program to use for link.
2515       my $xlink = &define_per_target_linker_variable ($linker, $xname);
2517       # If the resulting program lies into a subdirectory,
2518       # make sure this directory will exist.
2519       my $dirstamp = require_build_directory_maybe ($one_file);
2521       $libtool_clean_directories{dirname ($one_file)} = 1;
2523       $output_rules .= &file_contents ('program',
2524                                        $where,
2525                                        PROGRAM  => $one_file,
2526                                        XPROGRAM => $xname,
2527                                        XLINK    => $xlink,
2528                                        DIRSTAMP => $dirstamp,
2529                                        EXEEXT   => '$(EXEEXT)');
2531       if ($seen_libobjs || $seen_global_libobjs)
2532         {
2533           if (var ($xname . '_LDADD'))
2534             {
2535               &check_libobjs_sources ($xname, $xname . '_LDADD');
2536             }
2537           elsif (var ('LDADD'))
2538             {
2539               &check_libobjs_sources ($xname, 'LDADD');
2540             }
2541         }
2542     }
2546 # handle_libraries ()
2547 # -------------------
2548 # Handle libraries.
2549 sub handle_libraries
2551   my @liblist = &am_install_var ('libs', 'LIBRARIES',
2552                                  'lib', 'pkglib', 'noinst', 'check');
2553   return if ! @liblist;
2555   my @prefix = am_primary_prefixes ('LIBRARIES', 0, 'lib', 'pkglib',
2556                                     'noinst', 'check');
2558   if (@prefix)
2559     {
2560       my $var = rvar ($prefix[0] . '_LIBRARIES');
2561       $var->requires_variables ('library used', 'RANLIB');
2562     }
2564   &define_variable ('AR', 'ar', INTERNAL);
2565   &define_variable ('ARFLAGS', 'cru', INTERNAL);
2567   foreach my $pair (@liblist)
2568     {
2569       my ($where, $onelib) = @$pair;
2571       my $seen_libobjs = 0;
2572       # Check that the library fits the standard naming convention.
2573       my $bn = basename ($onelib);
2574       if ($bn !~ /^lib.*\.a$/)
2575         {
2576           $bn =~ s/^(?:lib)?(.*?)(?:\.[^.]*)?$/lib$1.a/;
2577           my $suggestion = dirname ($onelib) . "/$bn";
2578           $suggestion =~ s|^\./||g;
2579           msg ('error-gnu/warn', $where,
2580                "`$onelib' is not a standard library name\n"
2581                . "did you mean `$suggestion'?")
2582         }
2584       $where->push_context ("while processing library `$onelib'");
2585       $where->set (INTERNAL->get);
2587       my $obj = get_object_extension '.$(OBJEXT)';
2589       # Canonicalize names and check for misspellings.
2590       my $xlib = &check_canonical_spelling ($onelib, '_LIBADD', '_SOURCES',
2591                                             '_OBJECTS', '_DEPENDENCIES',
2592                                             '_AR');
2594       if (! var ($xlib . '_AR'))
2595         {
2596           &define_variable ($xlib . '_AR', '$(AR) $(ARFLAGS)', $where);
2597         }
2599       # Generate support for conditional object inclusion in
2600       # libraries.
2601       if (var ($xlib . '_LIBADD'))
2602         {
2603           if (&handle_lib_objects ($xlib, $xlib . '_LIBADD'))
2604             {
2605               $seen_libobjs = 1;
2606             }
2607         }
2608       else
2609         {
2610           &define_variable ($xlib . "_LIBADD", '', $where);
2611         }
2613       reject_var ($xlib . '_LDADD',
2614                   "use `${xlib}_LIBADD', not `${xlib}_LDADD'");
2616       # Make sure we at look at this.
2617       set_seen ($xlib . '_DEPENDENCIES');
2619       &handle_source_transform ($xlib, $onelib, $obj, $where,
2620                                 NONLIBTOOL => 1, LIBTOOL => 0);
2622       # If the resulting library lies into a subdirectory,
2623       # make sure this directory will exist.
2624       my $dirstamp = require_build_directory_maybe ($onelib);
2626       $output_rules .= &file_contents ('library',
2627                                        $where,
2628                                        LIBRARY  => $onelib,
2629                                        XLIBRARY => $xlib,
2630                                        DIRSTAMP => $dirstamp);
2632       if ($seen_libobjs)
2633         {
2634           if (var ($xlib . '_LIBADD'))
2635             {
2636               &check_libobjs_sources ($xlib, $xlib . '_LIBADD');
2637             }
2638         }
2639     }
2643 # handle_ltlibraries ()
2644 # ---------------------
2645 # Handle shared libraries.
2646 sub handle_ltlibraries
2648   my @liblist = &am_install_var ('ltlib', 'LTLIBRARIES',
2649                                  'noinst', 'lib', 'pkglib', 'check');
2650   return if ! @liblist;
2652   my @prefix = am_primary_prefixes ('LTLIBRARIES', 0, 'lib', 'pkglib',
2653                                     'noinst', 'check');
2655   if (@prefix)
2656     {
2657       my $var = rvar ($prefix[0] . '_LTLIBRARIES');
2658       $var->requires_variables ('Libtool library used', 'LIBTOOL');
2659     }
2661   my %instdirs = ();
2662   my %instsubdirs = ();
2663   my %instconds = ();
2664   my %liblocations = ();        # Location (in Makefile.am) of each library.
2666   foreach my $key (@prefix)
2667     {
2668       # Get the installation directory of each library.
2669       my $dir = $key;
2670       my $strip_subdir = 1;
2671       if ($dir =~ /^nobase_/)
2672         {
2673           $dir =~ s/^nobase_//;
2674           $strip_subdir = 0;
2675         }
2676       my $var = rvar ($key . '_LTLIBRARIES');
2678       # We reject libraries which are installed in several places
2679       # in the same condition, because we can only specify one
2680       # `-rpath' option.
2681       $var->traverse_recursively
2682         (sub
2683          {
2684            my ($var, $val, $cond, $full_cond) = @_;
2685            my $hcond = $full_cond->human;
2686            my $where = $var->rdef ($cond)->location;
2687            my $ldir = '';
2688            $ldir = '/' . dirname ($val)
2689              if (!$strip_subdir);
2690            # A library cannot be installed in different directory
2691            # in overlapping conditions.
2692            if (exists $instconds{$val})
2693              {
2694                my ($msg, $acond) =
2695                  $instconds{$val}->ambiguous_p ($val, $full_cond);
2697                if ($msg)
2698                  {
2699                    error ($where, $msg, partial => 1);
2700                    my $dirtxt = "installed " . ($strip_subdir ? "in" : "below") . " `$dir'";
2701                    $dirtxt = "built for `$dir'"
2702                      if $dir eq 'EXTRA' || $dir eq 'noinst' || $dir eq 'check';
2703                    my $dircond =
2704                      $full_cond->true ? "" : " in condition $hcond";
2706                    error ($where, "`$val' should be $dirtxt$dircond ...",
2707                           partial => 1);
2709                    my $hacond = $acond->human;
2710                    my $adir = $instdirs{$val}{$acond};
2711                    my $adirtxt = "installed in `$adir'";
2712                    $adirtxt = "built for `$adir'"
2713                      if ($adir eq 'EXTRA' || $adir eq 'noinst'
2714                          || $adir eq 'check');
2715                    my $adircond = $acond->true ? "" : " in condition $hacond";
2717                    my $onlyone = ($dir ne $adir) ?
2718                      ("\nLibtool libraries can be built for only one "
2719                       . "destination.") : "";
2721                    error ($liblocations{$val}{$acond},
2722                           "... and should also be $adirtxt$adircond.$onlyone");
2723                    return;
2724                  }
2725              }
2726            else
2727              {
2728                $instconds{$val} = new Automake::DisjConditions;
2729              }
2730            $instdirs{$val}{$full_cond} = $dir;
2731            $instsubdirs{$val}{$full_cond} = $ldir;
2732            $liblocations{$val}{$full_cond} = $where;
2733            $instconds{$val} = $instconds{$val}->merge ($full_cond);
2734          },
2735          sub
2736          {
2737            return ();
2738          },
2739          skip_ac_subst => 1);
2740     }
2742   foreach my $pair (@liblist)
2743     {
2744       my ($where, $onelib) = @$pair;
2746       my $seen_libobjs = 0;
2747       my $obj = get_object_extension '.lo';
2749       # Canonicalize names and check for misspellings.
2750       my $xlib = &check_canonical_spelling ($onelib, '_LIBADD', '_LDFLAGS',
2751                                             '_SOURCES', '_OBJECTS',
2752                                             '_DEPENDENCIES');
2754       # Check that the library fits the standard naming convention.
2755       my $libname_rx = '^lib.*\.la';
2756       my $ldvar = var ("${xlib}_LDFLAGS") || var ('AM_LDFLAGS');
2757       my $ldvar2 = var ('LDFLAGS');
2758       if (($ldvar && grep (/-module/, $ldvar->value_as_list_recursive))
2759           || ($ldvar2 && grep (/-module/, $ldvar2->value_as_list_recursive)))
2760         {
2761           # Relax name checking for libtool modules.
2762           $libname_rx = '\.la';
2763         }
2765       my $bn = basename ($onelib);
2766       if ($bn !~ /$libname_rx$/)
2767         {
2768           my $type = 'library';
2769           if ($libname_rx eq '\.la')
2770             {
2771               $bn =~ s/^(lib|)(.*?)(?:\.[^.]*)?$/$1$2.la/;
2772               $type = 'module';
2773             }
2774           else
2775             {
2776               $bn =~ s/^(?:lib)?(.*?)(?:\.[^.]*)?$/lib$1.la/;
2777             }
2778           my $suggestion = dirname ($onelib) . "/$bn";
2779           $suggestion =~ s|^\./||g;
2780           msg ('error-gnu/warn', $where,
2781                "`$onelib' is not a standard libtool $type name\n"
2782                . "did you mean `$suggestion'?")
2783         }
2785       $where->push_context ("while processing Libtool library `$onelib'");
2786       $where->set (INTERNAL->get);
2788       # Make sure we look at these.
2789       set_seen ($xlib . '_LDFLAGS');
2790       set_seen ($xlib . '_DEPENDENCIES');
2792       # Generate support for conditional object inclusion in
2793       # libraries.
2794       if (var ($xlib . '_LIBADD'))
2795         {
2796           if (&handle_lib_objects ($xlib, $xlib . '_LIBADD'))
2797             {
2798               $seen_libobjs = 1;
2799             }
2800         }
2801       else
2802         {
2803           &define_variable ($xlib . "_LIBADD", '', $where);
2804         }
2806       reject_var ("${xlib}_LDADD",
2807                   "use `${xlib}_LIBADD', not `${xlib}_LDADD'");
2810       my $linker = &handle_source_transform ($xlib, $onelib, $obj, $where,
2811                                              NONLIBTOOL => 0, LIBTOOL => 1);
2813       # Determine program to use for link.
2814       my $xlink = &define_per_target_linker_variable ($linker, $xlib);
2816       my $rpathvar = "am_${xlib}_rpath";
2817       my $rpath = "\$($rpathvar)";
2818       foreach my $rcond ($instconds{$onelib}->conds)
2819         {
2820           my $val;
2821           if ($instdirs{$onelib}{$rcond} eq 'EXTRA'
2822               || $instdirs{$onelib}{$rcond} eq 'noinst'
2823               || $instdirs{$onelib}{$rcond} eq 'check')
2824             {
2825               # It's an EXTRA_ library, so we can't specify -rpath,
2826               # because we don't know where the library will end up.
2827               # The user probably knows, but generally speaking automake
2828               # doesn't -- and in fact configure could decide
2829               # dynamically between two different locations.
2830               $val = '';
2831             }
2832           else
2833             {
2834               $val = ('-rpath $(' . $instdirs{$onelib}{$rcond} . 'dir)');
2835               $val .= $instsubdirs{$onelib}{$rcond}
2836                 if defined $instsubdirs{$onelib}{$rcond};
2837             }
2838           if ($rcond->true)
2839             {
2840               # If $rcond is true there is only one condition and
2841               # there is no point defining an helper variable.
2842               $rpath = $val;
2843             }
2844           else
2845             {
2846               define_pretty_variable ($rpathvar, $rcond, INTERNAL, $val);
2847             }
2848         }
2850       # If the resulting library lies into a subdirectory,
2851       # make sure this directory will exist.
2852       my $dirstamp = require_build_directory_maybe ($onelib);
2854       # Remember to cleanup .libs/ in this directory.
2855       my $dirname = dirname $onelib;
2856       $libtool_clean_directories{$dirname} = 1;
2858       $output_rules .= &file_contents ('ltlibrary',
2859                                        $where,
2860                                        LTLIBRARY  => $onelib,
2861                                        XLTLIBRARY => $xlib,
2862                                        RPATH      => $rpath,
2863                                        XLINK      => $xlink,
2864                                        DIRSTAMP   => $dirstamp);
2865       if ($seen_libobjs)
2866         {
2867           if (var ($xlib . '_LIBADD'))
2868             {
2869               &check_libobjs_sources ($xlib, $xlib . '_LIBADD');
2870             }
2871         }
2872     }
2875 # See if any _SOURCES variable were misspelled.
2876 sub check_typos ()
2878   # It is ok if the user sets this particular variable.
2879   set_seen 'AM_LDFLAGS';
2881   foreach my $primary ('SOURCES', 'LIBADD', 'LDADD', 'LDFLAGS', 'DEPENDENCIES')
2882     {
2883       foreach my $var (variables $primary)
2884         {
2885           my $varname = $var->name;
2886           # A configure variable is always legitimate.
2887           next if exists $configure_vars{$varname};
2889           for my $cond ($var->conditions->conds)
2890             {
2891               $varname =~ /^(?:nobase_)?(?:dist_|nodist_)?(.*)_[[:alnum:]]+$/;
2892               msg_var ('syntax', $var, "variable `$varname' is defined but no"
2893                        . " program or\nlibrary has `$1' as canonic name"
2894                        . " (possible typo)")
2895                 unless $var->rdef ($cond)->seen;
2896             }
2897         }
2898     }
2902 # Handle scripts.
2903 sub handle_scripts
2905     # NOTE we no longer automatically clean SCRIPTS, because it is
2906     # useful to sometimes distribute scripts verbatim.  This happens
2907     # e.g. in Automake itself.
2908     &am_install_var ('-candist', 'scripts', 'SCRIPTS',
2909                      'bin', 'sbin', 'libexec', 'pkgdata',
2910                      'noinst', 'check');
2916 ## ------------------------ ##
2917 ## Handling Texinfo files.  ##
2918 ## ------------------------ ##
2920 # ($OUTFILE, $VFILE, @CLEAN_FILES)
2921 # &scan_texinfo_file ($FILENAME)
2922 # ------------------------------
2923 # $OUTFILE     - name of the info file produced by $FILENAME.
2924 # $VFILE       - name of the version.texi file used (undef if none).
2925 # @CLEAN_FILES - list of byproducts (indexes etc.)
2926 sub scan_texinfo_file ($)
2928   my ($filename) = @_;
2930   # Some of the following extensions are always created, no matter
2931   # whether indexes are used or not.  Other (like cps, fns, ... pgs)
2932   # are only created when they are used.  We used to scan $FILENAME
2933   # for their use, but that is not enough: they could be used in
2934   # included files.  We can't scan included files because we don't
2935   # know the include path.  Therefore we always erase these files, no
2936   # matter whether they are used or not.
2937   #
2938   # (tmp is only created if an @macro is used and a certain e-TeX
2939   # feature is not available.)
2940   my %clean_suffixes =
2941     map { $_ => 1 } (qw(aux log toc tmp
2942                         cp cps
2943                         fn fns
2944                         ky kys
2945                         vr vrs
2946                         tp tps
2947                         pg pgs)); # grep 'new.*index' texinfo.tex
2949   my $texi = new Automake::XFile "< $filename";
2950   verb "reading $filename";
2952   my ($outfile, $vfile);
2953   while ($_ = $texi->getline)
2954     {
2955       if (/^\@setfilename +(\S+)/)
2956         {
2957           # Honor only the first @setfilename.  (It's possible to have
2958           # more occurrences later if the manual shows examples of how
2959           # to use @setfilename...)
2960           next if $outfile;
2962           $outfile = $1;
2963           if ($outfile =~ /\.([^.]+)$/ && $1 ne 'info')
2964             {
2965               error ("$filename:$.",
2966                      "output `$outfile' has unrecognized extension");
2967               return;
2968             }
2969         }
2970       # A "version.texi" file is actually any file whose name matches
2971       # "vers*.texi".
2972       elsif (/^\@include\s+(vers[^.]*\.texi)\s*$/)
2973         {
2974           $vfile = $1;
2975         }
2977       # Try to find new or unused indexes.
2979       # Creating a new category of index.
2980       elsif (/^\@def(code)?index (\w+)/)
2981         {
2982           $clean_suffixes{$2} = 1;
2983           $clean_suffixes{"$2s"} = 1;
2984         }
2986       # Merging an index into an another.
2987       elsif (/^\@syn(code)?index (\w+) (\w+)/)
2988         {
2989           delete $clean_suffixes{"$2s"};
2990           $clean_suffixes{"$3s"} = 1;
2991         }
2993     }
2995   if (! $outfile)
2996     {
2997       err_am "`$filename' missing \@setfilename";
2998       return;
2999     }
3001   my $infobase = basename ($filename);
3002   $infobase =~ s/\.te?xi(nfo)?$//;
3003   return ($outfile, $vfile,
3004           map { "$infobase.$_" } (sort keys %clean_suffixes));
3008 # ($DIRSTAMP, @CLEAN_FILES)
3009 # output_texinfo_build_rules ($SOURCE, $DEST, $INSRC, @DEPENDENCIES)
3010 # ------------------------------------------------------------------
3011 # SOURCE - the source Texinfo file
3012 # DEST - the destination Info file
3013 # INSRC - wether DEST should be built in the source tree
3014 # DEPENDENCIES - known dependencies
3015 sub output_texinfo_build_rules ($$$@)
3017   my ($source, $dest, $insrc, @deps) = @_;
3019   # Split `a.texi' into `a' and `.texi'.
3020   my ($spfx, $ssfx) = ($source =~ /^(.*?)(\.[^.]*)?$/);
3021   my ($dpfx, $dsfx) = ($dest =~ /^(.*?)(\.[^.]*)?$/);
3023   $ssfx ||= "";
3024   $dsfx ||= "";
3026   # We can output two kinds of rules: the "generic" rules use Make
3027   # suffix rules and are appropriate when $source and $dest do not lie
3028   # in a sub-directory; the "specific" rules are needed in the other
3029   # case.
3030   #
3031   # The former are output only once (this is not really apparent here,
3032   # but just remember that some logic deeper in Automake will not
3033   # output the same rule twice); while the later need to be output for
3034   # each Texinfo source.
3035   my $generic;
3036   my $makeinfoflags;
3037   my $sdir = dirname $source;
3038   if ($sdir eq '.' && dirname ($dest) eq '.')
3039     {
3040       $generic = 1;
3041       $makeinfoflags = '-I $(srcdir)';
3042     }
3043   else
3044     {
3045       $generic = 0;
3046       $makeinfoflags = "-I $sdir -I \$(srcdir)/$sdir";
3047     }
3049   # A directory can contain two kinds of info files: some built in the
3050   # source tree, and some built in the build tree.  The rules are
3051   # different in each case.  However we cannot output two different
3052   # set of generic rules.  Because in-source builds are more usual, we
3053   # use generic rules in this case and fall back to "specific" rules
3054   # for build-dir builds.  (It should not be a problem to invert this
3055   # if needed.)
3056   $generic = 0 unless $insrc;
3058   # We cannot use a suffix rule to build info files with an empty
3059   # extension.  Otherwise we would output a single suffix inference
3060   # rule, with separate dependencies, as in
3061   #
3062   #    .texi:
3063   #             $(MAKEINFO) ...
3064   #    foo.info: foo.texi
3065   #
3066   # which confuse Solaris make.  (See the Autoconf manual for
3067   # details.)  Therefore we use a specific rule in this case.  This
3068   # applies to info files only (dvi and pdf files always have an
3069   # extension).
3070   my $generic_info = ($generic && $dsfx) ? 1 : 0;
3072   # If the resulting file lie into a subdirectory,
3073   # make sure this directory will exist.
3074   my $dirstamp = require_build_directory_maybe ($dest);
3076   my $dipfx = ($insrc ? '$(srcdir)/' : '') . $dpfx;
3078   $output_rules .= file_contents ('texibuild',
3079                                   new Automake::Location,
3080                                   DEPS             => "@deps",
3081                                   DEST_PREFIX      => $dpfx,
3082                                   DEST_INFO_PREFIX => $dipfx,
3083                                   DEST_SUFFIX      => $dsfx,
3084                                   DIRSTAMP         => $dirstamp,
3085                                   GENERIC          => $generic,
3086                                   GENERIC_INFO     => $generic_info,
3087                                   INSRC            => $insrc,
3088                                   MAKEINFOFLAGS    => $makeinfoflags,
3089                                   SOURCE           => ($generic
3090                                                        ? '$<' : $source),
3091                                   SOURCE_INFO      => ($generic_info
3092                                                        ? '$<' : $source),
3093                                   SOURCE_REAL      => $source,
3094                                   SOURCE_SUFFIX    => $ssfx,
3095                                   );
3096   return ($dirstamp, "$dpfx.dvi", "$dpfx.pdf", "$dpfx.ps", "$dpfx.html");
3100 # $TEXICLEANS
3101 # handle_texinfo_helper ($info_texinfos)
3102 # --------------------------------------
3103 # Handle all Texinfo source; helper for handle_texinfo.
3104 sub handle_texinfo_helper ($)
3106   my ($info_texinfos) = @_;
3107   my (@infobase, @info_deps_list, @texi_deps);
3108   my %versions;
3109   my $done = 0;
3110   my @texi_cleans;
3112   # Build a regex matching user-cleaned files.
3113   my $d = var 'DISTCLEANFILES';
3114   my $c = var 'CLEANFILES';
3115   my @f = ();
3116   push @f, $d->value_as_list_recursive (inner_expand => 1) if $d;
3117   push @f, $c->value_as_list_recursive (inner_expand => 1) if $c;
3118   @f = map { s|[^A-Za-z_0-9*\[\]\-]|\\$&|g; s|\*|[^/]*|g; $_; } @f;
3119   my $user_cleaned_files = '^(?:' . join ('|', @f) . ')$';
3121   foreach my $texi
3122       ($info_texinfos->value_as_list_recursive (inner_expand => 1))
3123     {
3124       my $infobase = $texi;
3125       $infobase =~ s/\.(txi|texinfo|texi)$//;
3127       if ($infobase eq $texi)
3128         {
3129           # FIXME: report line number.
3130           err_am "texinfo file `$texi' has unrecognized extension";
3131           next;
3132         }
3134       push @infobase, $infobase;
3136       # If 'version.texi' is referenced by input file, then include
3137       # automatic versioning capability.
3138       my ($out_file, $vtexi, @clean_files) =
3139         scan_texinfo_file ("$relative_dir/$texi")
3140         or next;
3141       push (@texi_cleans, @clean_files);
3143       # If the Texinfo source is in a subdirectory, create the
3144       # resulting info in this subdirectory.  If it is in the current
3145       # directory, try hard to not prefix "./" because it breaks the
3146       # generic rules.
3147       my $outdir = dirname ($texi) . '/';
3148       $outdir = "" if $outdir eq './';
3149       $out_file =  $outdir . $out_file;
3151       # Until Automake 1.6.3, .info files were built in the
3152       # source tree.  This was an obstacle to the support of
3153       # non-distributed .info files, and non-distributed .texi
3154       # files.
3155       #
3156       # * Non-distributed .texi files is important in some packages
3157       #   where .texi files are built at make time, probably using
3158       #   other binaries built in the package itself, maybe using
3159       #   tools or information found on the build host.  Because
3160       #   these files are not distributed they are always rebuilt
3161       #   at make time; they should therefore not lie in the source
3162       #   directory.  One plan was to support this using
3163       #   nodist_info_TEXINFOS or something similar.  (Doing this
3164       #   requires some sanity checks.  For instance Automake should
3165       #   not allow:
3166       #      dist_info_TEXINFOS = foo.texi
3167       #      nodist_foo_TEXINFOS = included.texi
3168       #   because a distributed file should never depend on a
3169       #   non-distributed file.)
3170       #
3171       # * If .texi files are not distributed, then .info files should
3172       #   not be distributed either.  There are also cases where one
3173       #   wants to distribute .texi files, but does not want to
3174       #   distribute the .info files.  For instance the Texinfo package
3175       #   distributes the tool used to build these files; it would
3176       #   be a waste of space to distribute them.  It's not clear
3177       #   which syntax we should use to indicate that .info files should
3178       #   not be distributed.  Akim Demaille suggested that eventually
3179       #   we switch to a new syntax:
3180       #   |  Maybe we should take some inspiration from what's already
3181       #   |  done in the rest of Automake.  Maybe there is too much
3182       #   |  syntactic sugar here, and you want
3183       #   |     nodist_INFO = bar.info
3184       #   |     dist_bar_info_SOURCES = bar.texi
3185       #   |     bar_texi_DEPENDENCIES = foo.texi
3186       #   |  with a bit of magic to have bar.info represent the whole
3187       #   |  bar*info set.  That's a lot more verbose that the current
3188       #   |  situation, but it is # not new, hence the user has less
3189       #   |  to learn.
3190       #   |
3191       #   |  But there is still too much room for meaningless specs:
3192       #   |     nodist_INFO = bar.info
3193       #   |     dist_bar_info_SOURCES = bar.texi
3194       #   |     dist_PS = bar.ps something-written-by-hand.ps
3195       #   |     nodist_bar_ps_SOURCES = bar.texi
3196       #   |     bar_texi_DEPENDENCIES = foo.texi
3197       #   |  here bar.texi is dist_ in line 2, and nodist_ in 4.
3198       #
3199       # Back to the point, it should be clear that in order to support
3200       # non-distributed .info files, we need to build them in the
3201       # build tree, not in the source tree (non-distributed .texi
3202       # files are less of a problem, because we do not output build
3203       # rules for them).  In Automake 1.7 .info build rules have been
3204       # largely cleaned up so that .info files get always build in the
3205       # build tree, even when distributed.  The idea was that
3206       #   (1) if during a VPATH build the .info file was found to be
3207       #       absent or out-of-date (in the source tree or in the
3208       #       build tree), Make would rebuild it in the build tree.
3209       #       If an up-to-date source-tree of the .info file existed,
3210       #       make would not rebuild it in the build tree.
3211       #   (2) having two copies of .info files, one in the source tree
3212       #       and one (newer) in the build tree is not a problem
3213       #       because `make dist' always pick files in the build tree
3214       #       first.
3215       # However it turned out the be a bad idea for several reasons:
3216       #   * Tru64, OpenBSD, and FreeBSD (not NetBSD) Make do not behave
3217       #     like GNU Make on point (1) above.  These implementations
3218       #     of Make would always rebuild .info files in the build
3219       #     tree, even if such files were up to date in the source
3220       #     tree.  Consequently, it was impossible to perform a VPATH
3221       #     build of a package containing Texinfo files using these
3222       #     Make implementations.
3223       #     (Refer to the Autoconf Manual, section "Limitation of
3224       #     Make", paragraph "VPATH", item "target lookup", for
3225       #     an account of the differences between these
3226       #     implementations.)
3227       #   * The GNU Coding Standards require these files to be built
3228       #     in the source-tree (when they are distributed, that is).
3229       #   * Keeping a fresher copy of distributed files in the
3230       #     build tree can be annoying during development because
3231       #     - if the files is kept under CVS, you really want it
3232       #       to be updated in the source tree
3233       #     - it is confusing that `make distclean' does not erase
3234       #       all files in the build tree.
3235       #
3236       # Consequently, starting with Automake 1.8, .info files are
3237       # built in the source tree again.  Because we still plan to
3238       # support non-distributed .info files at some point, we
3239       # have a single variable ($INSRC) that controls whether
3240       # the current .info file must be built in the source tree
3241       # or in the build tree.  Actually this variable is switched
3242       # off for .info files that appear to be cleaned; this is
3243       # for backward compatibility with package such as Texinfo,
3244       # which do things like
3245       #   info_TEXINFOS = texinfo.txi info-stnd.texi info.texi
3246       #   DISTCLEANFILES = texinfo texinfo-* info*.info*
3247       #   # Do not create info files for distribution.
3248       #   dist-info:
3249       # in order not to distribute .info files.
3250       my $insrc = ($out_file =~ $user_cleaned_files) ? 0 : 1;
3252       my $soutdir = '$(srcdir)/' . $outdir;
3253       $outdir = $soutdir if $insrc;
3255       # If user specified file_TEXINFOS, then use that as explicit
3256       # dependency list.
3257       @texi_deps = ();
3258       push (@texi_deps, "$soutdir$vtexi") if $vtexi;
3260       my $canonical = canonicalize ($infobase);
3261       if (var ($canonical . "_TEXINFOS"))
3262         {
3263           push (@texi_deps, '$(' . $canonical . '_TEXINFOS)');
3264           push_dist_common ('$(' . $canonical . '_TEXINFOS)');
3265         }
3267       my ($dirstamp, @cfiles) =
3268         output_texinfo_build_rules ($texi, $out_file, $insrc, @texi_deps);
3269       push (@texi_cleans, @cfiles);
3271       push (@info_deps_list, $out_file);
3273       # If a vers*.texi file is needed, emit the rule.
3274       if ($vtexi)
3275         {
3276           err_am ("`$vtexi', included in `$texi', "
3277                   . "also included in `$versions{$vtexi}'")
3278             if defined $versions{$vtexi};
3279           $versions{$vtexi} = $texi;
3281           # We number the stamp-vti files.  This is doable since the
3282           # actual names don't matter much.  We only number starting
3283           # with the second one, so that the common case looks nice.
3284           my $vti = ($done ? $done : 'vti');
3285           ++$done;
3287           # This is ugly, but it is our historical practice.
3288           if ($config_aux_dir_set_in_configure_ac)
3289             {
3290               require_conf_file_with_macro (TRUE, 'info_TEXINFOS', FOREIGN,
3291                                             'mdate-sh');
3292             }
3293           else
3294             {
3295               require_file_with_macro (TRUE, 'info_TEXINFOS',
3296                                        FOREIGN, 'mdate-sh');
3297             }
3299           my $conf_dir;
3300           if ($config_aux_dir_set_in_configure_ac)
3301             {
3302               $conf_dir = "$am_config_aux_dir/";
3303             }
3304           else
3305             {
3306               $conf_dir = '$(srcdir)/';
3307             }
3308           $output_rules .= file_contents ('texi-vers',
3309                                           new Automake::Location,
3310                                           TEXI     => $texi,
3311                                           VTI      => $vti,
3312                                           STAMPVTI => "${soutdir}stamp-$vti",
3313                                           VTEXI    => "$soutdir$vtexi",
3314                                           MDDIR    => $conf_dir,
3315                                           DIRSTAMP => $dirstamp);
3316         }
3317     }
3319   # Handle location of texinfo.tex.
3320   my $need_texi_file = 0;
3321   my $texinfodir;
3322   if (var ('TEXINFO_TEX'))
3323     {
3324       # The user defined TEXINFO_TEX so assume he knows what he is
3325       # doing.
3326       $texinfodir = ('$(srcdir)/'
3327                      . dirname (variable_value ('TEXINFO_TEX')));
3328     }
3329   elsif (option 'cygnus')
3330     {
3331       $texinfodir = '$(top_srcdir)/../texinfo';
3332       define_variable ('TEXINFO_TEX', "$texinfodir/texinfo.tex", INTERNAL);
3333     }
3334   elsif ($config_aux_dir_set_in_configure_ac)
3335     {
3336       $texinfodir = $am_config_aux_dir;
3337       define_variable ('TEXINFO_TEX', "$texinfodir/texinfo.tex", INTERNAL);
3338       $need_texi_file = 2; # so that we require_conf_file later
3339     }
3340   else
3341     {
3342       $texinfodir = '$(srcdir)';
3343       $need_texi_file = 1;
3344     }
3345   define_variable ('am__TEXINFO_TEX_DIR', $texinfodir, INTERNAL);
3347   push (@dist_targets, 'dist-info');
3349   if (! option 'no-installinfo')
3350     {
3351       # Make sure documentation is made and installed first.  Use
3352       # $(INFO_DEPS), not 'info', because otherwise recursive makes
3353       # get run twice during "make all".
3354       unshift (@all, '$(INFO_DEPS)');
3355     }
3357   define_files_variable ("DVIS", @infobase, 'dvi', INTERNAL);
3358   define_files_variable ("PDFS", @infobase, 'pdf', INTERNAL);
3359   define_files_variable ("PSS", @infobase, 'ps', INTERNAL);
3360   define_files_variable ("HTMLS", @infobase, 'html', INTERNAL);
3362   # This next isn't strictly needed now -- the places that look here
3363   # could easily be changed to look in info_TEXINFOS.  But this is
3364   # probably better, in case noinst_TEXINFOS is ever supported.
3365   define_variable ("TEXINFOS", variable_value ('info_TEXINFOS'), INTERNAL);
3367   # Do some error checking.  Note that this file is not required
3368   # when in Cygnus mode; instead we defined TEXINFO_TEX explicitly
3369   # up above.
3370   if ($need_texi_file && ! option 'no-texinfo.tex')
3371     {
3372       if ($need_texi_file > 1)
3373         {
3374           require_conf_file_with_macro (TRUE, 'info_TEXINFOS', FOREIGN,
3375                                         'texinfo.tex');
3376         }
3377       else
3378         {
3379           require_file_with_macro (TRUE, 'info_TEXINFOS', FOREIGN,
3380                                    'texinfo.tex');
3381         }
3382     }
3384   return makefile_wrap ("", "\t  ", @texi_cleans);
3388 # handle_texinfo ()
3389 # -----------------
3390 # Handle all Texinfo source.
3391 sub handle_texinfo ()
3393   reject_var 'TEXINFOS', "`TEXINFOS' is an anachronism; use `info_TEXINFOS'";
3394   # FIXME: I think this is an obsolete future feature name.
3395   reject_var 'html_TEXINFOS', "HTML generation not yet supported";
3397   my $info_texinfos = var ('info_TEXINFOS');
3398   my $texiclean = "";
3399   if ($info_texinfos)
3400     {
3401       $texiclean = handle_texinfo_helper ($info_texinfos);
3402     }
3403   $output_rules .=  file_contents ('texinfos',
3404                                    new Automake::Location,
3405                                    TEXICLEAN     => $texiclean,
3406                                    'LOCAL-TEXIS' => !!$info_texinfos);
3410 # Handle any man pages.
3411 sub handle_man_pages
3413   reject_var 'MANS', "`MANS' is an anachronism; use `man_MANS'";
3415   # Find all the sections in use.  We do this by first looking for
3416   # "standard" sections, and then looking for any additional
3417   # sections used in man_MANS.
3418   my (%sections, %notrans_sections, %trans_sections,
3419       %notrans_vars, %trans_vars, %notrans_sect_vars, %trans_sect_vars);
3420   # We handle nodist_ for uniformity.  man pages aren't distributed
3421   # by default so it isn't actually very important.
3422   foreach my $npfx ('', 'notrans_')
3423     {
3424       foreach my $pfx ('', 'dist_', 'nodist_')
3425         {
3426           # Add more sections as needed.
3427           foreach my $section ('0'..'9', 'n', 'l')
3428             {
3429               my $varname = $npfx . $pfx . 'man' . $section . '_MANS';
3430               if (var ($varname))
3431                 {
3432                   $sections{$section} = 1;
3433                   $varname = '$(' . $varname . ')';
3434                   if ($npfx eq 'notrans_')
3435                     {
3436                       $notrans_sections{$section} = 1;
3437                       $notrans_sect_vars{$varname} = 1;
3438                     }
3439                   else
3440                     {
3441                       $trans_sections{$section} = 1;
3442                       $trans_sect_vars{$varname} = 1;
3443                     }
3445                   &push_dist_common ($varname)
3446                     if $pfx eq 'dist_';
3447                 }
3448             }
3450           my $varname = $npfx . $pfx . 'man_MANS';
3451           my $var = var ($varname);
3452           if ($var)
3453             {
3454               foreach ($var->value_as_list_recursive)
3455                 {
3456                   # A page like `foo.1c' goes into man1dir.
3457                   if (/\.([0-9a-z])([a-z]*)$/)
3458                     {
3459                       $sections{$1} = 1;
3460                       if ($npfx eq 'notrans_')
3461                         {
3462                           $notrans_sections{$1} = 1;
3463                         }
3464                       else
3465                         {
3466                           $trans_sections{$1} = 1;
3467                         }
3468                     }
3469                 }
3471               $varname = '$(' . $varname . ')';
3472               if ($npfx eq 'notrans_')
3473                 {
3474                   $notrans_vars{$varname} = 1;
3475                 }
3476               else
3477                 {
3478                   $trans_vars{$varname} = 1;
3479                 }
3480               &push_dist_common ($varname)
3481                 if $pfx eq 'dist_';
3482             }
3483         }
3484     }
3486   return unless %sections;
3488   my @unsorted_deps;
3490   # Build section independent variables.
3491   my $have_notrans = %notrans_vars;
3492   my @notrans_list = sort keys %notrans_vars;
3493   my $have_trans = %trans_vars;
3494   my @trans_list = sort keys %trans_vars;
3496   # Now for each section, generate an install and uninstall rule.
3497   # Sort sections so output is deterministic.
3498   foreach my $section (sort keys %sections)
3499     {
3500       # Build section dependent variables.
3501       my $notrans_mans = $have_notrans || exists $notrans_sections{$section};
3502       my $trans_mans = $have_trans || exists $trans_sections{$section};
3503       my (%notrans_this_sect, %trans_this_sect);
3504       my $expr = 'man' . $section . '_MANS';
3505       foreach my $varname (keys %notrans_sect_vars)
3506         {
3507           if ($varname =~ /$expr/)
3508             {
3509               $notrans_this_sect{$varname} = 1;
3510             }
3511         }
3512       foreach my $varname (keys %trans_sect_vars)
3513         {
3514           if ($varname =~ /$expr/)
3515             {
3516               $trans_this_sect{$varname} = 1;
3517             }
3518         }
3519       my @notrans_sect_list = sort keys %notrans_this_sect;
3520       my @trans_sect_list = sort keys %trans_this_sect;
3521       @unsorted_deps = (keys %notrans_vars, keys %trans_vars,
3522                         keys %notrans_this_sect, keys %trans_this_sect);
3523       my @deps = sort @unsorted_deps;
3524       $output_rules .= &file_contents ('mans',
3525                                        new Automake::Location,
3526                                        SECTION           => $section,
3527                                        DEPS              => "@deps",
3528                                        NOTRANS_MANS      => $notrans_mans,
3529                                        NOTRANS_SECT_LIST => "@notrans_sect_list",
3530                                        HAVE_NOTRANS      => $have_notrans,
3531                                        NOTRANS_LIST      => "@notrans_list",
3532                                        TRANS_MANS        => $trans_mans,
3533                                        TRANS_SECT_LIST   => "@trans_sect_list",
3534                                        HAVE_TRANS        => $have_trans,
3535                                        TRANS_LIST        => "@trans_list");
3536     }
3538   @unsorted_deps  = (keys %notrans_vars, keys %trans_vars,
3539                      keys %notrans_sect_vars, keys %trans_sect_vars);
3540   my @mans = sort @unsorted_deps;
3541   $output_vars .= file_contents ('mans-vars',
3542                                  new Automake::Location,
3543                                  MANS => "@mans");
3545   push (@all, '$(MANS)')
3546     unless option 'no-installman';
3549 # Handle DATA variables.
3550 sub handle_data
3552     &am_install_var ('-noextra', '-candist', 'data', 'DATA',
3553                      'data', 'dataroot', 'dvi', 'html', 'pdf', 'ps',
3554                      'sysconf', 'sharedstate', 'localstate',
3555                      'pkgdata', 'lisp', 'noinst', 'check');
3558 # Handle TAGS.
3559 sub handle_tags
3561     my @tag_deps = ();
3562     my @ctag_deps = ();
3563     if (var ('SUBDIRS'))
3564     {
3565         $output_rules .= ("tags-recursive:\n"
3566                           . "\tlist=\'\$(SUBDIRS)\'; for subdir in \$\$list; do \\\n"
3567                           # Never fail here if a subdir fails; it
3568                           # isn't important.
3569                           . "\t  test \"\$\$subdir\" = . || (\$(am__cd) \$\$subdir"
3570                           . " && \$(MAKE) \$(AM_MAKEFLAGS) tags); \\\n"
3571                           . "\tdone\n");
3572         push (@tag_deps, 'tags-recursive');
3573         &depend ('.PHONY', 'tags-recursive');
3574         &depend ('.MAKE', 'tags-recursive');
3576         $output_rules .= ("ctags-recursive:\n"
3577                           . "\tlist=\'\$(SUBDIRS)\'; for subdir in \$\$list; do \\\n"
3578                           # Never fail here if a subdir fails; it
3579                           # isn't important.
3580                           . "\t  test \"\$\$subdir\" = . || (\$(am__cd) \$\$subdir"
3581                           . " && \$(MAKE) \$(AM_MAKEFLAGS) ctags); \\\n"
3582                           . "\tdone\n");
3583         push (@ctag_deps, 'ctags-recursive');
3584         &depend ('.PHONY', 'ctags-recursive');
3585         &depend ('.MAKE', 'ctags-recursive');
3586     }
3588     if (&saw_sources_p (1)
3589         || var ('ETAGS_ARGS')
3590         || @tag_deps)
3591     {
3592         my @config;
3593         foreach my $spec (@config_headers)
3594         {
3595             my ($out, @ins) = split_config_file_spec ($spec);
3596             foreach my $in (@ins)
3597               {
3598                 # If the config header source is in this directory,
3599                 # require it.
3600                 push @config, basename ($in)
3601                   if $relative_dir eq dirname ($in);
3602               }
3603         }
3604         $output_rules .= &file_contents ('tags',
3605                                          new Automake::Location,
3606                                          CONFIG    => "@config",
3607                                          TAGSDIRS  => "@tag_deps",
3608                                          CTAGSDIRS => "@ctag_deps");
3610         set_seen 'TAGS_DEPENDENCIES';
3611     }
3612     elsif (reject_var ('TAGS_DEPENDENCIES',
3613                        "doesn't make sense to define `TAGS_DEPENDENCIES'"
3614                        . "without\nsources or `ETAGS_ARGS'"))
3615     {
3616     }
3617     else
3618     {
3619         # Every Makefile must define some sort of TAGS rule.
3620         # Otherwise, it would be possible for a top-level "make TAGS"
3621         # to fail because some subdirectory failed.
3622         $output_rules .= "tags: TAGS\nTAGS:\n\n";
3623         # Ditto ctags.
3624         $output_rules .= "ctags: CTAGS\nCTAGS:\n\n";
3625     }
3628 # Handle multilib support.
3629 sub handle_multilib
3631   if ($seen_multilib && $relative_dir eq '.')
3632     {
3633       $output_rules .= &file_contents ('multilib', new Automake::Location);
3634       push (@all, 'all-multi');
3635     }
3639 # user_phony_rule ($NAME)
3640 # -----------------------
3641 # Return false if rule $NAME does not exist.  Otherwise,
3642 # declare it as phony, complete its definition (in case it is
3643 # conditional), and return its Automake::Rule instance.
3644 sub user_phony_rule ($)
3646   my ($name) = @_;
3647   my $rule = rule $name;
3648   if ($rule)
3649     {
3650       depend ('.PHONY', $name);
3651       # Define $NAME in all condition where it is not already defined,
3652       # so that it is always OK to depend on $NAME.
3653       for my $c ($rule->not_always_defined_in_cond (TRUE)->conds)
3654         {
3655           Automake::Rule::define ($name, 'internal', RULE_AUTOMAKE,
3656                                   $c, INTERNAL);
3657           $output_rules .= $c->subst_string . "$name:\n";
3658         }
3659     }
3660   return $rule;
3664 # $BOOLEAN
3665 # &for_dist_common ($A, $B)
3666 # -------------------------
3667 # Subroutine for &handle_dist: sort files to dist.
3669 # We put README first because it then becomes easier to make a
3670 # Usenet-compliant shar file (in these, README must be first).
3672 # FIXME: do more ordering of files here.
3673 sub for_dist_common
3675     return 0
3676         if $a eq $b;
3677     return -1
3678         if $a eq 'README';
3679     return 1
3680         if $b eq 'README';
3681     return $a cmp $b;
3684 # handle_dist
3685 # -----------
3686 # Handle 'dist' target.
3687 sub handle_dist ()
3689   # Substitutions for distdir.am
3690   my %transform;
3692   # Define DIST_SUBDIRS.  This must always be done, regardless of the
3693   # no-dist setting: target like `distclean' or `maintainer-clean' use it.
3694   my $subdirs = var ('SUBDIRS');
3695   if ($subdirs)
3696     {
3697       # If SUBDIRS is conditionally defined, then set DIST_SUBDIRS
3698       # to all possible directories, and use it.  If DIST_SUBDIRS is
3699       # defined, just use it.
3701       # Note that we check DIST_SUBDIRS first on purpose, so that
3702       # we don't call has_conditional_contents for now reason.
3703       # (In the past one project used so many conditional subdirectories
3704       # that calling has_conditional_contents on SUBDIRS caused
3705       # automake to grow to 150Mb -- this should not happen with
3706       # the current implementation of has_conditional_contents,
3707       # but it's more efficient to avoid the call anyway.)
3708       if (var ('DIST_SUBDIRS'))
3709         {
3710         }
3711       elsif ($subdirs->has_conditional_contents)
3712         {
3713           define_pretty_variable
3714             ('DIST_SUBDIRS', TRUE, INTERNAL,
3715              uniq ($subdirs->value_as_list_recursive));
3716         }
3717       else
3718         {
3719           # We always define this because that is what `distclean'
3720           # wants.
3721           define_pretty_variable ('DIST_SUBDIRS', TRUE, INTERNAL,
3722                                   '$(SUBDIRS)');
3723         }
3724     }
3726   # The remaining definitions are only required when a dist target is used.
3727   return if option 'no-dist';
3729   # At least one of the archive formats must be enabled.
3730   if ($relative_dir eq '.')
3731     {
3732       my $archive_defined = option 'no-dist-gzip' ? 0 : 1;
3733       $archive_defined ||=
3734         grep { option "dist-$_" } qw(shar zip tarZ bzip2 lzma xz);
3735       error (option 'no-dist-gzip',
3736              "no-dist-gzip specified but no dist-* specified, "
3737              . "at least one archive format must be enabled")
3738         unless $archive_defined;
3739     }
3741   # Look for common files that should be included in distribution.
3742   # If the aux dir is set, and it does not have a Makefile.am, then
3743   # we check for these files there as well.
3744   my $check_aux = 0;
3745   if ($relative_dir eq '.'
3746       && $config_aux_dir_set_in_configure_ac)
3747     {
3748       if (! &is_make_dir ($config_aux_dir))
3749         {
3750           $check_aux = 1;
3751         }
3752     }
3753   foreach my $cfile (@common_files)
3754     {
3755       if (dir_has_case_matching_file ($relative_dir, $cfile)
3756           # The file might be absent, but if it can be built it's ok.
3757           || rule $cfile)
3758         {
3759           &push_dist_common ($cfile);
3760         }
3762       # Don't use `elsif' here because a file might meaningfully
3763       # appear in both directories.
3764       if ($check_aux && dir_has_case_matching_file ($config_aux_dir, $cfile))
3765         {
3766           &push_dist_common ("$config_aux_dir/$cfile")
3767         }
3768     }
3770   # We might copy elements from $configure_dist_common to
3771   # %dist_common if we think we need to.  If the file appears in our
3772   # directory, we would have discovered it already, so we don't
3773   # check that.  But if the file is in a subdir without a Makefile,
3774   # we want to distribute it here if we are doing `.'.  Ugly!
3775   if ($relative_dir eq '.')
3776     {
3777       foreach my $file (split (' ' , $configure_dist_common))
3778         {
3779           push_dist_common ($file)
3780             unless is_make_dir (dirname ($file));
3781         }
3782     }
3784   # Files to distributed.  Don't use ->value_as_list_recursive
3785   # as it recursively expands `$(dist_pkgdata_DATA)' etc.
3786   my @dist_common = split (' ', rvar ('DIST_COMMON')->variable_value);
3787   @dist_common = uniq (sort for_dist_common (@dist_common));
3788   variable_delete 'DIST_COMMON';
3789   define_pretty_variable ('DIST_COMMON', TRUE, INTERNAL, @dist_common);
3791   # Now that we've processed DIST_COMMON, disallow further attempts
3792   # to set it.
3793   $handle_dist_run = 1;
3795   # Scan EXTRA_DIST to see if we need to distribute anything from a
3796   # subdir.  If so, add it to the list.  I didn't want to do this
3797   # originally, but there were so many requests that I finally
3798   # relented.
3799   my $extra_dist = var ('EXTRA_DIST');
3801   $transform{'DISTCHECK-HOOK'} = !! rule 'distcheck-hook';
3802   $transform{'GETTEXT'} = $seen_gettext && !$seen_gettext_external;
3804   # If the target `dist-hook' exists, make sure it is run.  This
3805   # allows users to do random weird things to the distribution
3806   # before it is packaged up.
3807   push (@dist_targets, 'dist-hook')
3808     if user_phony_rule 'dist-hook';
3809   $transform{'DIST-TARGETS'} = join (' ', @dist_targets);
3811   my $flm = option ('filename-length-max');
3812   my $filename_filter = $flm ? '.' x $flm->[1] : '';
3814   $output_rules .= &file_contents ('distdir',
3815                                    new Automake::Location,
3816                                    %transform,
3817                                    FILENAME_FILTER => $filename_filter);
3821 # check_directory ($NAME, $WHERE)
3822 # -------------------------------
3823 # Ensure $NAME is a directory, and that it uses a sane name.
3824 # Use $WHERE as a location in the diagnostic, if any.
3825 sub check_directory ($$)
3827   my ($dir, $where) = @_;
3829   error $where, "required directory $relative_dir/$dir does not exist"
3830     unless -d "$relative_dir/$dir";
3832   # If an `obj/' directory exists, BSD make will enter it before
3833   # reading `Makefile'.  Hence the `Makefile' in the current directory
3834   # will not be read.
3835   #
3836   #  % cat Makefile
3837   #  all:
3838   #          echo Hello
3839   #  % cat obj/Makefile
3840   #  all:
3841   #          echo World
3842   #  % make      # GNU make
3843   #  echo Hello
3844   #  Hello
3845   #  % pmake     # BSD make
3846   #  echo World
3847   #  World
3848   msg ('portability', $where,
3849        "naming a subdirectory `obj' causes troubles with BSD make")
3850     if $dir eq 'obj';
3852   # `aux' is probably the most important of the following forbidden name,
3853   # since it's tempting to use it as an AC_CONFIG_AUX_DIR.
3854   msg ('portability', $where,
3855        "name `$dir' is reserved on W32 and DOS platforms")
3856     if grep (/^\Q$dir\E$/i, qw/aux lpt1 lpt2 lpt3 com1 com2 com3 com4 con prn/);
3859 # check_directories_in_var ($VARIABLE)
3860 # ------------------------------------
3861 # Recursively check all items in variables $VARIABLE as directories
3862 sub check_directories_in_var ($)
3864   my ($var) = @_;
3865   $var->traverse_recursively
3866     (sub
3867      {
3868        my ($var, $val, $cond, $full_cond) = @_;
3869        check_directory ($val, $var->rdef ($cond)->location);
3870        return ();
3871      },
3872      undef,
3873      skip_ac_subst => 1);
3876 # &handle_subdirs ()
3877 # ------------------
3878 # Handle subdirectories.
3879 sub handle_subdirs ()
3881   my $subdirs = var ('SUBDIRS');
3882   return
3883     unless $subdirs;
3885   check_directories_in_var $subdirs;
3887   my $dsubdirs = var ('DIST_SUBDIRS');
3888   check_directories_in_var $dsubdirs
3889     if $dsubdirs;
3891   $output_rules .= &file_contents ('subdirs', new Automake::Location);
3892   rvar ('RECURSIVE_TARGETS')->rdef (TRUE)->{'pretty'} = VAR_SORTED; # Gross!
3896 # ($REGEN, @DEPENDENCIES)
3897 # &scan_aclocal_m4
3898 # ----------------
3899 # If aclocal.m4 creation is automated, return the list of its dependencies.
3900 sub scan_aclocal_m4 ()
3902   my $regen_aclocal = 0;
3904   set_seen 'CONFIG_STATUS_DEPENDENCIES';
3905   set_seen 'CONFIGURE_DEPENDENCIES';
3907   if (-f 'aclocal.m4')
3908     {
3909       &define_variable ("ACLOCAL_M4", '$(top_srcdir)/aclocal.m4', INTERNAL);
3911       my $aclocal = new Automake::XFile "< aclocal.m4";
3912       my $line = $aclocal->getline;
3913       $regen_aclocal = $line =~ 'generated automatically by aclocal';
3914     }
3916   my @ac_deps = ();
3918   if (set_seen ('ACLOCAL_M4_SOURCES'))
3919     {
3920       push (@ac_deps, '$(ACLOCAL_M4_SOURCES)');
3921       msg_var ('obsolete', 'ACLOCAL_M4_SOURCES',
3922                "`ACLOCAL_M4_SOURCES' is obsolete.\n"
3923                . "It should be safe to simply remove it.");
3924     }
3926   # Note that it might be possible that aclocal.m4 doesn't exist but
3927   # should be auto-generated.  This case probably isn't very
3928   # important.
3930   return ($regen_aclocal, @ac_deps);
3934 # Helper function for substitute_ac_subst_variables.
3935 sub substitute_ac_subst_variables_worker($)
3937   my ($token) = @_;
3938   return "\@$token\@" if var $token;
3939   return "\${$token\}";
3942 # substitute_ac_subst_variables ($TEXT)
3943 # -------------------------------------
3944 # Replace any occurrence of ${FOO} in $TEXT by @FOO@ if FOO is an AC_SUBST
3945 # variable.
3946 sub substitute_ac_subst_variables ($)
3948   my ($text) = @_;
3949   $text =~ s/\${([^ \t=:+{}]+)}/&substitute_ac_subst_variables_worker ($1)/ge;
3950   return $text;
3953 # @DEPENDENCIES
3954 # &prepend_srcdir (@INPUTS)
3955 # -------------------------
3956 # Prepend $(srcdir) or $(top_srcdir) to all @INPUTS.  The idea is that
3957 # if an input file has a directory part the same as the current
3958 # directory, then the directory part is simply replaced by $(srcdir).
3959 # But if the directory part is different, then $(top_srcdir) is
3960 # prepended.
3961 sub prepend_srcdir (@)
3963   my (@inputs) = @_;
3964   my @newinputs;
3966   foreach my $single (@inputs)
3967     {
3968       if (dirname ($single) eq $relative_dir)
3969         {
3970           push (@newinputs, '$(srcdir)/' . basename ($single));
3971         }
3972       else
3973         {
3974           push (@newinputs, '$(top_srcdir)/' . $single);
3975         }
3976     }
3977   return @newinputs;
3980 # @DEPENDENCIES
3981 # rewrite_inputs_into_dependencies ($OUTPUT, @INPUTS)
3982 # ---------------------------------------------------
3983 # Compute a list of dependencies appropriate for the rebuild
3984 # rule of
3985 #   AC_CONFIG_FILES($OUTPUT:$INPUT[0]:$INPUTS[1]:...)
3986 # Also distribute $INPUTs which are not built by another AC_CONFIG_FOOS.
3987 sub rewrite_inputs_into_dependencies ($@)
3989   my ($file, @inputs) = @_;
3990   my @res = ();
3992   for my $i (@inputs)
3993     {
3994       # We cannot create dependencies on shell variables.
3995       next if (substitute_ac_subst_variables $i) =~ /\$/;
3997       if (exists $ac_config_files_location{$i} && $i ne $file)
3998         {
3999           my $di = dirname $i;
4000           if ($di eq $relative_dir)
4001             {
4002               $i = basename $i;
4003             }
4004           # In the top-level Makefile we do not use $(top_builddir), because
4005           # we are already there, and since the targets are built without
4006           # a $(top_builddir), it helps BSD Make to match them with
4007           # dependencies.
4008           elsif ($relative_dir ne '.')
4009             {
4010               $i = '$(top_builddir)/' . $i;
4011             }
4012         }
4013       else
4014         {
4015           msg ('error', $ac_config_files_location{$file},
4016                "required file `$i' not found")
4017             unless $i =~ /\$/ || exists $output_files{$i} || -f $i;
4018           ($i) = prepend_srcdir ($i);
4019           push_dist_common ($i);
4020         }
4021       push @res, $i;
4022     }
4023   return @res;
4028 # &handle_configure ($MAKEFILE_AM, $MAKEFILE_IN, $MAKEFILE, @INPUTS)
4029 # ------------------------------------------------------------------
4030 # Handle remaking and configure stuff.
4031 # We need the name of the input file, to do proper remaking rules.
4032 sub handle_configure ($$$@)
4034   my ($makefile_am, $makefile_in, $makefile, @inputs) = @_;
4036   prog_error 'empty @inputs'
4037     unless @inputs;
4039   my ($rel_makefile_am, $rel_makefile_in) = prepend_srcdir ($makefile_am,
4040                                                             $makefile_in);
4041   my $rel_makefile = basename $makefile;
4043   my $colon_infile = ':' . join (':', @inputs);
4044   $colon_infile = '' if $colon_infile eq ":$makefile.in";
4045   my @rewritten = rewrite_inputs_into_dependencies ($makefile, @inputs);
4046   my ($regen_aclocal_m4, @aclocal_m4_deps) = scan_aclocal_m4;
4047   define_pretty_variable ('am__aclocal_m4_deps', TRUE, INTERNAL,
4048                           @configure_deps, @aclocal_m4_deps,
4049                           '$(top_srcdir)/' . $configure_ac);
4050   my @configuredeps = ('$(am__aclocal_m4_deps)', '$(CONFIGURE_DEPENDENCIES)');
4051   push @configuredeps, '$(ACLOCAL_M4)' if -f 'aclocal.m4';
4052   define_pretty_variable ('am__configure_deps', TRUE, INTERNAL,
4053                           @configuredeps);
4055   $output_rules .= file_contents
4056     ('configure',
4057      new Automake::Location,
4058      MAKEFILE              => $rel_makefile,
4059      'MAKEFILE-DEPS'       => "@rewritten",
4060      'CONFIG-MAKEFILE'     => ($relative_dir eq '.') ? '$@' : '$(subdir)/$@',
4061      'MAKEFILE-IN'         => $rel_makefile_in,
4062      'MAKEFILE-IN-DEPS'    => "@include_stack",
4063      'MAKEFILE-AM'         => $rel_makefile_am,
4064      STRICTNESS            => global_option 'cygnus'
4065                                 ? 'cygnus' : $strictness_name,
4066      'USE-DEPS'            => global_option 'no-dependencies'
4067                                 ? ' --ignore-deps' : '',
4068      'MAKEFILE-AM-SOURCES' => "$makefile$colon_infile",
4069      'REGEN-ACLOCAL-M4'    => $regen_aclocal_m4);
4071   if ($relative_dir eq '.')
4072     {
4073       &push_dist_common ('acconfig.h')
4074         if -f 'acconfig.h';
4075     }
4077   # If we have a configure header, require it.
4078   my $hdr_index = 0;
4079   my @distclean_config;
4080   foreach my $spec (@config_headers)
4081     {
4082       $hdr_index += 1;
4083       # $CONFIG_H_PATH: config.h from top level.
4084       my ($config_h_path, @ins) = split_config_file_spec ($spec);
4085       my $config_h_dir = dirname ($config_h_path);
4087       # If the header is in the current directory we want to build
4088       # the header here.  Otherwise, if we're at the topmost
4089       # directory and the header's directory doesn't have a
4090       # Makefile, then we also want to build the header.
4091       if ($relative_dir eq $config_h_dir
4092           || ($relative_dir eq '.' && ! &is_make_dir ($config_h_dir)))
4093         {
4094           my ($cn_sans_dir, $stamp_dir);
4095           if ($relative_dir eq $config_h_dir)
4096             {
4097               $cn_sans_dir = basename ($config_h_path);
4098               $stamp_dir = '';
4099             }
4100           else
4101             {
4102               $cn_sans_dir = $config_h_path;
4103               if ($config_h_dir eq '.')
4104                 {
4105                   $stamp_dir = '';
4106                 }
4107               else
4108                 {
4109                   $stamp_dir = $config_h_dir . '/';
4110                 }
4111             }
4113           # This will also distribute all inputs.
4114           @ins = rewrite_inputs_into_dependencies ($config_h_path, @ins);
4116           # Cannot define rebuild rules for filenames with shell variables.
4117           next if (substitute_ac_subst_variables $config_h_path) =~ /\$/;
4119           # Header defined in this directory.
4120           my @files;
4121           if (-f $config_h_path . '.top')
4122             {
4123               push (@files, "$cn_sans_dir.top");
4124             }
4125           if (-f $config_h_path . '.bot')
4126             {
4127               push (@files, "$cn_sans_dir.bot");
4128             }
4130           push_dist_common (@files);
4132           # For now, acconfig.h can only appear in the top srcdir.
4133           if (-f 'acconfig.h')
4134             {
4135               push (@files, '$(top_srcdir)/acconfig.h');
4136             }
4138           my $stamp = "${stamp_dir}stamp-h${hdr_index}";
4139           $output_rules .=
4140             file_contents ('remake-hdr',
4141                            new Automake::Location,
4142                            FILES            => "@files",
4143                            CONFIG_H         => $cn_sans_dir,
4144                            CONFIG_HIN       => $ins[0],
4145                            CONFIG_H_DEPS    => "@ins",
4146                            CONFIG_H_PATH    => $config_h_path,
4147                            STAMP            => "$stamp");
4149           push @distclean_config, $cn_sans_dir, $stamp;
4150         }
4151     }
4153   $output_rules .= file_contents ('clean-hdr',
4154                                   new Automake::Location,
4155                                   FILES => "@distclean_config")
4156     if @distclean_config;
4158   # Distribute and define mkinstalldirs only if it is already present
4159   # in the package, for backward compatibility (some people may still
4160   # use $(mkinstalldirs)).
4161   my $mkidpath = "$config_aux_dir/mkinstalldirs";
4162   if (-f $mkidpath)
4163     {
4164       # Use require_file so that any existing script gets updated
4165       # by --force-missing.
4166       require_conf_file ($mkidpath, FOREIGN, 'mkinstalldirs');
4167       define_variable ('mkinstalldirs',
4168                        "\$(SHELL) $am_config_aux_dir/mkinstalldirs", INTERNAL);
4169     }
4170   else
4171     {
4172       # Use $(install_sh), not $(MKDIR_P) because the latter requires
4173       # at least one argument, and $(mkinstalldirs) used to work
4174       # even without arguments (e.g. $(mkinstalldirs) $(conditional_dir)).
4175       define_variable ('mkinstalldirs', '$(install_sh) -d', INTERNAL);
4176     }
4178   reject_var ('CONFIG_HEADER',
4179               "`CONFIG_HEADER' is an anachronism; now determined "
4180               . "automatically\nfrom `$configure_ac'");
4182   my @config_h;
4183   foreach my $spec (@config_headers)
4184     {
4185       my ($out, @ins) = split_config_file_spec ($spec);
4186       # Generate CONFIG_HEADER define.
4187       if ($relative_dir eq dirname ($out))
4188         {
4189           push @config_h, basename ($out);
4190         }
4191       else
4192         {
4193           push @config_h, "\$(top_builddir)/$out";
4194         }
4195     }
4196   define_variable ("CONFIG_HEADER", "@config_h", INTERNAL)
4197     if @config_h;
4199   # Now look for other files in this directory which must be remade
4200   # by config.status, and generate rules for them.
4201   my @actual_other_files = ();
4202   # These get cleaned only in a VPATH build.
4203   my @actual_other_vpath_files = ();
4204   foreach my $lfile (@other_input_files)
4205     {
4206       my $file;
4207       my @inputs;
4208       if ($lfile =~ /^([^:]*):(.*)$/)
4209         {
4210           # This is the ":" syntax of AC_OUTPUT.
4211           $file = $1;
4212           @inputs = split (':', $2);
4213         }
4214       else
4215         {
4216           # Normal usage.
4217           $file = $lfile;
4218           @inputs = $file . '.in';
4219         }
4221       # Automake files should not be stored in here, but in %MAKE_LIST.
4222       prog_error ("$lfile in \@other_input_files\n"
4223                   . "\@other_input_files = (@other_input_files)")
4224         if -f $file . '.am';
4226       my $local = basename ($file);
4228       # We skip files that aren't in this directory.  However, if
4229       # the file's directory does not have a Makefile, and we are
4230       # currently doing `.', then we create a rule to rebuild the
4231       # file in the subdir.
4232       my $fd = dirname ($file);
4233       if ($fd ne $relative_dir)
4234         {
4235           if ($relative_dir eq '.' && ! &is_make_dir ($fd))
4236             {
4237               $local = $file;
4238             }
4239           else
4240             {
4241               next;
4242             }
4243         }
4245       my @rewritten_inputs = rewrite_inputs_into_dependencies ($file, @inputs);
4247       # Cannot output rules for shell variables.
4248       next if (substitute_ac_subst_variables $local) =~ /\$/;
4250       my $condstr = '';
4251       my $cond = $ac_config_files_condition{$lfile};
4252       if (defined $cond)
4253         {
4254           $condstr = $cond->subst_string;
4255           Automake::Rule::define ($local, $configure_ac, RULE_AUTOMAKE, $cond,
4256                                   $ac_config_files_location{$file});
4257         }
4258       $output_rules .= ($condstr . $local . ': '
4259                         . '$(top_builddir)/config.status '
4260                         . "@rewritten_inputs\n"
4261                         . $condstr . "\t"
4262                         . 'cd $(top_builddir) && '
4263                         . '$(SHELL) ./config.status '
4264                         . ($relative_dir eq '.' ? '' : '$(subdir)/')
4265                         . '$@'
4266                         . "\n");
4267       push (@actual_other_files, $local);
4268     }
4270   # For links we should clean destinations and distribute sources.
4271   foreach my $spec (@config_links)
4272     {
4273       my ($link, $file) = split /:/, $spec;
4274       # Some people do AC_CONFIG_LINKS($computed).  We only handle
4275       # the DEST:SRC form.
4276       next unless $file;
4277       my $where = $ac_config_files_location{$link};
4279       # Skip destinations that contain shell variables.
4280       if ((substitute_ac_subst_variables $link) !~ /\$/)
4281         {
4282           # We skip links that aren't in this directory.  However, if
4283           # the link's directory does not have a Makefile, and we are
4284           # currently doing `.', then we add the link to CONFIG_CLEAN_FILES
4285           # in `.'s Makefile.in.
4286           my $local = basename ($link);
4287           my $fd = dirname ($link);
4288           if ($fd ne $relative_dir)
4289             {
4290               if ($relative_dir eq '.' && ! &is_make_dir ($fd))
4291                 {
4292                   $local = $link;
4293                 }
4294               else
4295                 {
4296                   $local = undef;
4297                 }
4298             }
4299           if ($file ne $link)
4300             {
4301               push @actual_other_files, $local if $local;
4302             }
4303           else
4304             {
4305               push @actual_other_vpath_files, $local if $local;
4306             }
4307         }
4309       # Do not process sources that contain shell variables.
4310       if ((substitute_ac_subst_variables $file) !~ /\$/)
4311         {
4312           my $fd = dirname ($file);
4314           # We distribute files that are in this directory.
4315           # At the top-level (`.') we also distribute files whose
4316           # directory does not have a Makefile.
4317           if (($fd eq $relative_dir)
4318               || ($relative_dir eq '.' && ! &is_make_dir ($fd)))
4319             {
4320               # The following will distribute $file as a side-effect when
4321               # it is appropriate (i.e., when $file is not already an output).
4322               # We do not need the result, just the side-effect.
4323               rewrite_inputs_into_dependencies ($link, $file);
4324             }
4325         }
4326     }
4328   # These files get removed by "make distclean".
4329   define_pretty_variable ('CONFIG_CLEAN_FILES', TRUE, INTERNAL,
4330                           @actual_other_files);
4331   define_pretty_variable ('CONFIG_CLEAN_VPATH_FILES', TRUE, INTERNAL,
4332                           @actual_other_vpath_files);
4335 # Handle C headers.
4336 sub handle_headers
4338     my @r = &am_install_var ('-defaultdist', 'header', 'HEADERS', 'include',
4339                              'oldinclude', 'pkginclude',
4340                              'noinst', 'check');
4341     foreach (@r)
4342     {
4343       next unless $_->[1] =~ /\..*$/;
4344       &saw_extension ($&);
4345     }
4348 sub handle_gettext
4350   return if ! $seen_gettext || $relative_dir ne '.';
4352   my $subdirs = var 'SUBDIRS';
4354   if (! $subdirs)
4355     {
4356       err_ac "AM_GNU_GETTEXT used but SUBDIRS not defined";
4357       return;
4358     }
4360   # Perform some sanity checks to help users get the right setup.
4361   # We disable these tests when po/ doesn't exist in order not to disallow
4362   # unusual gettext setups.
4363   #
4364   # Bruno Haible:
4365   # | The idea is:
4366   # |
4367   # |  1) If a package doesn't have a directory po/ at top level, it
4368   # |     will likely have multiple po/ directories in subpackages.
4369   # |
4370   # |  2) It is useful to warn for the absence of intl/ if AM_GNU_GETTEXT
4371   # |     is used without 'external'. It is also useful to warn for the
4372   # |     presence of intl/ if AM_GNU_GETTEXT([external]) is used. Both
4373   # |     warnings apply only to the usual layout of packages, therefore
4374   # |     they should both be disabled if no po/ directory is found at
4375   # |     top level.
4377   if (-d 'po')
4378     {
4379       my @subdirs = $subdirs->value_as_list_recursive;
4381       msg_var ('syntax', $subdirs,
4382                "AM_GNU_GETTEXT used but `po' not in SUBDIRS")
4383         if ! grep ($_ eq 'po', @subdirs);
4385       # intl/ is not required when AM_GNU_GETTEXT is called with the
4386       # `external' option and AM_GNU_GETTEXT_INTL_SUBDIR is not called.
4387       msg_var ('syntax', $subdirs,
4388                "AM_GNU_GETTEXT used but `intl' not in SUBDIRS")
4389         if (! ($seen_gettext_external && ! $seen_gettext_intl)
4390             && ! grep ($_ eq 'intl', @subdirs));
4392       # intl/ should not be used with AM_GNU_GETTEXT([external]), except
4393       # if AM_GNU_GETTEXT_INTL_SUBDIR is called.
4394       msg_var ('syntax', $subdirs,
4395                "`intl' should not be in SUBDIRS when "
4396                . "AM_GNU_GETTEXT([external]) is used")
4397         if ($seen_gettext_external && ! $seen_gettext_intl
4398             && grep ($_ eq 'intl', @subdirs));
4399     }
4401   require_file ($ac_gettext_location, GNU, 'ABOUT-NLS');
4404 # Handle footer elements.
4405 sub handle_footer
4407     reject_rule ('.SUFFIXES',
4408                  "use variable `SUFFIXES', not target `.SUFFIXES'");
4410     # Note: AIX 4.1 /bin/make will fail if any suffix rule appears
4411     # before .SUFFIXES.  So we make sure that .SUFFIXES appears before
4412     # anything else, by sticking it right after the default: target.
4413     $output_header .= ".SUFFIXES:\n";
4414     my $suffixes = var 'SUFFIXES';
4415     my @suffixes = Automake::Rule::suffixes;
4416     if (@suffixes || $suffixes)
4417     {
4418         # Make sure SUFFIXES has unique elements.  Sort them to ensure
4419         # the output remains consistent.  However, $(SUFFIXES) is
4420         # always at the start of the list, unsorted.  This is done
4421         # because make will choose rules depending on the ordering of
4422         # suffixes, and this lets the user have some control.  Push
4423         # actual suffixes, and not $(SUFFIXES).  Some versions of make
4424         # do not like variable substitutions on the .SUFFIXES line.
4425         my @user_suffixes = ($suffixes
4426                              ? $suffixes->value_as_list_recursive : ());
4428         my %suffixes = map { $_ => 1 } @suffixes;
4429         delete @suffixes{@user_suffixes};
4431         $output_header .= (".SUFFIXES: "
4432                            . join (' ', @user_suffixes, sort keys %suffixes)
4433                            . "\n");
4434     }
4436     $output_trailer .= file_contents ('footer', new Automake::Location);
4440 # Generate `make install' rules.
4441 sub handle_install ()
4443   $output_rules .= &file_contents
4444     ('install',
4445      new Automake::Location,
4446      maybe_BUILT_SOURCES => (set_seen ('BUILT_SOURCES')
4447                              ? (" \$(BUILT_SOURCES)\n"
4448                                 . "\t\$(MAKE) \$(AM_MAKEFLAGS)")
4449                              : ''),
4450      'installdirs-local' => (user_phony_rule 'installdirs-local'
4451                              ? ' installdirs-local' : ''),
4452      am__installdirs => variable_value ('am__installdirs') || '');
4456 # Deal with all and all-am.
4457 sub handle_all ($)
4459     my ($makefile) = @_;
4461     # Output `all-am'.
4463     # Put this at the beginning for the sake of non-GNU makes.  This
4464     # is still wrong if these makes can run parallel jobs.  But it is
4465     # right enough.
4466     unshift (@all, basename ($makefile));
4468     foreach my $spec (@config_headers)
4469       {
4470         my ($out, @ins) = split_config_file_spec ($spec);
4471         push (@all, basename ($out))
4472           if dirname ($out) eq $relative_dir;
4473       }
4475     # Install `all' hooks.
4476     push (@all, "all-local")
4477       if user_phony_rule "all-local";
4479     &pretty_print_rule ("all-am:", "\t\t", @all);
4480     &depend ('.PHONY', 'all-am', 'all');
4483     # Output `all'.
4485     my @local_headers = ();
4486     push @local_headers, '$(BUILT_SOURCES)'
4487       if var ('BUILT_SOURCES');
4488     foreach my $spec (@config_headers)
4489       {
4490         my ($out, @ins) = split_config_file_spec ($spec);
4491         push @local_headers, basename ($out)
4492           if dirname ($out) eq $relative_dir;
4493       }
4495     if (@local_headers)
4496       {
4497         # We need to make sure config.h is built before we recurse.
4498         # We also want to make sure that built sources are built
4499         # before any ordinary `all' targets are run.  We can't do this
4500         # by changing the order of dependencies to the "all" because
4501         # that breaks when using parallel makes.  Instead we handle
4502         # things explicitly.
4503         $output_all .= ("all: @local_headers"
4504                         . "\n\t"
4505                         . '$(MAKE) $(AM_MAKEFLAGS) '
4506                         . (var ('SUBDIRS') ? 'all-recursive' : 'all-am')
4507                         . "\n\n");
4508         depend ('.MAKE', 'all');
4509       }
4510     else
4511       {
4512         $output_all .= "all: " . (var ('SUBDIRS')
4513                                   ? 'all-recursive' : 'all-am') . "\n\n";
4514       }
4518 # &do_check_merge_target ()
4519 # -------------------------
4520 # Handle check merge target specially.
4521 sub do_check_merge_target ()
4523   # Include user-defined local form of target.
4524   push @check_tests, 'check-local'
4525     if user_phony_rule 'check-local';
4527   # In --cygnus mode, check doesn't depend on all.
4528   if (option 'cygnus')
4529     {
4530       # Just run the local check rules.
4531       pretty_print_rule ('check-am:', "\t\t", @check);
4532     }
4533   else
4534     {
4535       # The check target must depend on the local equivalent of
4536       # `all', to ensure all the primary targets are built.  Then it
4537       # must build the local check rules.
4538       $output_rules .= "check-am: all-am\n";
4539       if (@check)
4540         {
4541           pretty_print_rule ("\t\$(MAKE) \$(AM_MAKEFLAGS)", "\t  ",
4542                              @check);
4543           depend ('.MAKE', 'check-am');
4544         }
4545     }
4546   if (@check_tests)
4547     {
4548       pretty_print_rule ("\t\$(MAKE) \$(AM_MAKEFLAGS)", "\t  ",
4549                          @check_tests);
4550       depend ('.MAKE', 'check-am');
4551     }
4553   depend '.PHONY', 'check', 'check-am';
4554   # Handle recursion.  We have to honor BUILT_SOURCES like for `all:'.
4555   $output_rules .= ("check: "
4556                     . (var ('BUILT_SOURCES')
4557                        ? "\$(BUILT_SOURCES)\n\t\$(MAKE) \$(AM_MAKEFLAGS) "
4558                        : '')
4559                     . (var ('SUBDIRS') ? 'check-recursive' : 'check-am')
4560                     . "\n");
4561   depend ('.MAKE', 'check')
4562     if var ('BUILT_SOURCES');
4565 # handle_clean ($MAKEFILE)
4566 # ------------------------
4567 # Handle all 'clean' targets.
4568 sub handle_clean ($)
4570   my ($makefile) = @_;
4572   # Clean the files listed in user variables if they exist.
4573   $clean_files{'$(MOSTLYCLEANFILES)'} = MOSTLY_CLEAN
4574     if var ('MOSTLYCLEANFILES');
4575   $clean_files{'$(CLEANFILES)'} = CLEAN
4576     if var ('CLEANFILES');
4577   $clean_files{'$(DISTCLEANFILES)'} = DIST_CLEAN
4578     if var ('DISTCLEANFILES');
4579   $clean_files{'$(MAINTAINERCLEANFILES)'} = MAINTAINER_CLEAN
4580     if var ('MAINTAINERCLEANFILES');
4582   # Built sources are automatically removed by maintainer-clean.
4583   $clean_files{'$(BUILT_SOURCES)'} = MAINTAINER_CLEAN
4584     if var ('BUILT_SOURCES');
4586   # Compute a list of "rm"s to run for each target.
4587   my %rms = (MOSTLY_CLEAN, [],
4588              CLEAN, [],
4589              DIST_CLEAN, [],
4590              MAINTAINER_CLEAN, []);
4592   foreach my $file (keys %clean_files)
4593     {
4594       my $when = $clean_files{$file};
4595       prog_error 'invalid entry in %clean_files'
4596         unless exists $rms{$when};
4598       my $rm = "rm -f $file";
4599       # If file is a variable, make sure when don't call `rm -f' without args.
4600       $rm ="test -z \"$file\" || $rm"
4601         if ($file =~ /^\s*\$(\(.*\)|\{.*\})\s*$/);
4603       push @{$rms{$when}}, "\t-$rm\n";
4604     }
4606   $output_rules .= &file_contents
4607     ('clean',
4608      new Automake::Location,
4609      MOSTLYCLEAN_RMS      => join ('', sort @{$rms{&MOSTLY_CLEAN}}),
4610      CLEAN_RMS            => join ('', sort @{$rms{&CLEAN}}),
4611      DISTCLEAN_RMS        => join ('', sort @{$rms{&DIST_CLEAN}}),
4612      MAINTAINER_CLEAN_RMS => join ('', sort @{$rms{&MAINTAINER_CLEAN}}),
4613      MAKEFILE             => basename $makefile,
4614      );
4618 # &target_cmp ($A, $B)
4619 # --------------------
4620 # Subroutine for &handle_factored_dependencies to let `.PHONY' and
4621 # other `.TARGETS' be last.
4622 sub target_cmp
4624   return 0 if $a eq $b;
4626   my $a1 = substr ($a, 0, 1);
4627   my $b1 = substr ($b, 0, 1);
4628   if ($a1 ne $b1)
4629     {
4630       return -1 if $b1 eq '.';
4631       return 1 if $a1 eq '.';
4632     }
4633   return $a cmp $b;
4637 # &handle_factored_dependencies ()
4638 # --------------------------------
4639 # Handle everything related to gathered targets.
4640 sub handle_factored_dependencies
4642   # Reject bad hooks.
4643   foreach my $utarg ('uninstall-data-local', 'uninstall-data-hook',
4644                      'uninstall-exec-local', 'uninstall-exec-hook',
4645                      'uninstall-dvi-local',
4646                      'uninstall-html-local',
4647                      'uninstall-info-local',
4648                      'uninstall-pdf-local',
4649                      'uninstall-ps-local')
4650     {
4651       my $x = $utarg;
4652       $x =~ s/-.*-/-/;
4653       reject_rule ($utarg, "use `$x', not `$utarg'");
4654     }
4656   reject_rule ('install-local',
4657                "use `install-data-local' or `install-exec-local', "
4658                . "not `install-local'");
4660   reject_rule ('install-hook',
4661                "use `install-data-hook' or `install-exec-hook', "
4662                . "not `install-hook'");
4664   # Install the -local hooks.
4665   foreach (keys %dependencies)
4666     {
4667       # Hooks are installed on the -am targets.
4668       s/-am$// or next;
4669       depend ("$_-am", "$_-local")
4670         if user_phony_rule "$_-local";
4671     }
4673   # Install the -hook hooks.
4674   # FIXME: Why not be as liberal as we are with -local hooks?
4675   foreach ('install-exec', 'install-data', 'uninstall')
4676     {
4677       if (user_phony_rule "$_-hook")
4678         {
4679           depend ('.MAKE', "$_-am");
4680           register_action("$_-am",
4681                           ("\t\@\$(NORMAL_INSTALL)\n"
4682                            . "\t\$(MAKE) \$(AM_MAKEFLAGS) $_-hook"));
4683         }
4684     }
4686   # All the required targets are phony.
4687   depend ('.PHONY', keys %required_targets);
4689   # Actually output gathered targets.
4690   foreach (sort target_cmp keys %dependencies)
4691     {
4692       # If there is nothing about this guy, skip it.
4693       next
4694         unless (@{$dependencies{$_}}
4695                 || $actions{$_}
4696                 || $required_targets{$_});
4698       # Define gathered targets in undefined conditions.
4699       # FIXME: Right now we must handle .PHONY as an exception,
4700       # because people write things like
4701       #    .PHONY: myphonytarget
4702       # to append dependencies.  This would not work if Automake
4703       # refrained from defining its own .PHONY target as it does
4704       # with other overridden targets.
4705       # Likewise for `.MAKE'.
4706       my @undefined_conds = (TRUE,);
4707       if ($_ ne '.PHONY' && $_ ne '.MAKE')
4708         {
4709           @undefined_conds =
4710             Automake::Rule::define ($_, 'internal',
4711                                     RULE_AUTOMAKE, TRUE, INTERNAL);
4712         }
4713       my @uniq_deps = uniq (sort @{$dependencies{$_}});
4714       foreach my $cond (@undefined_conds)
4715         {
4716           my $condstr = $cond->subst_string;
4717           &pretty_print_rule ("$condstr$_:", "$condstr\t", @uniq_deps);
4718           $output_rules .= $actions{$_} if defined $actions{$_};
4719           $output_rules .= "\n";
4720         }
4721     }
4725 # &handle_tests_dejagnu ()
4726 # ------------------------
4727 sub handle_tests_dejagnu
4729     push (@check_tests, 'check-DEJAGNU');
4730     $output_rules .= file_contents ('dejagnu', new Automake::Location);
4734 # Handle TESTS variable and other checks.
4735 sub handle_tests
4737   if (option 'dejagnu')
4738     {
4739       &handle_tests_dejagnu;
4740     }
4741   else
4742     {
4743       foreach my $c ('DEJATOOL', 'RUNTEST', 'RUNTESTFLAGS')
4744         {
4745           reject_var ($c, "`$c' defined but `dejagnu' not in "
4746                       . "`AUTOMAKE_OPTIONS'");
4747         }
4748     }
4750   if (var ('TESTS'))
4751     {
4752       push (@check_tests, 'check-TESTS');
4753       $output_rules .= &file_contents ('check', new Automake::Location,
4754                                        COLOR => !! option 'color-tests',
4755                                        PARALLEL_TESTS => !! option 'parallel-tests');
4757       # Tests that are known programs should have $(EXEEXT) appended.
4758       # For matching purposes, we need to adjust XFAIL_TESTS as well.
4759       append_exeext { exists $known_programs{$_[0]} } 'TESTS';
4760       append_exeext { exists $known_programs{$_[0]} } 'XFAIL_TESTS'
4761         if (var ('XFAIL_TESTS'));
4763       if (option 'parallel-tests')
4764         {
4765           define_variable ('TEST_SUITE_LOG', 'test-suite.log', INTERNAL);
4766           define_variable ('TEST_SUITE_HTML', '$(TEST_SUITE_LOG:.log=.html)', INTERNAL);
4767           my $suff = '.test';
4768           my $at_exeext = '';
4769           if (exists $configure_vars{'EXEEXT'})
4770             {
4771               $at_exeext = subst ('EXEEXT');
4772               $suff = $at_exeext  . ' ' . $suff;
4773             }
4774           define_variable ('TEST_EXTENSIONS', $suff, INTERNAL);
4775           # FIXME: this mishandles conditions.
4776           my @test_suffixes = (var 'TEST_EXTENSIONS')->value_as_list_recursive;
4777           if (exists $configure_vars{'EXEEXT'})
4778             {
4779               unshift (@test_suffixes, $at_exeext)
4780                 unless $test_suffixes[0] eq $at_exeext;
4781             }
4782           unshift (@test_suffixes, '');
4784           transform_variable_recursively
4785             ('TESTS', 'TEST_LOGS', 'am__testlogs', 1, INTERNAL,
4786               sub {
4787                 my ($subvar, $val, $cond, $full_cond) = @_;
4788                 my $obj = $val;
4789                 return $obj
4790                   if $val =~ /^\@.*\@$/;
4791                 $obj =~ s/\$\(EXEEXT\)$//o;
4793                 if ($val =~ /(\$\((top_)?srcdir\))\//o)
4794                   {
4795                     msg ('error', $subvar->rdef ($cond)->location,
4796                          "parallel-tests: using `$1' in TESTS is currently broken: `$val'");
4797                   }
4799                 foreach my $test_suffix (@test_suffixes)
4800                   {
4801                     next
4802                       if $test_suffix eq $at_exeext || $test_suffix eq '';
4803                     return substr ($obj, 0, length ($obj) - length ($test_suffix)) . '.log'
4804                       if substr ($obj, - length ($test_suffix)) eq $test_suffix;
4805                   }
4806                 $obj .= '.log';
4807                 $output_rules .= file_contents ('check2', new Automake::Location,
4808                                                 GENERIC => 0,
4809                                                 OBJ => $obj,
4810                                                 SOURCE => $val,
4811                                                 COMPILE => '',
4812                                                 EXT => '');
4813                 return $obj;
4814               });
4816           my $nhelper=1;
4817           my $prev = 'TESTS';
4818           my $post = '';
4819           my $last_suffix = $test_suffixes[$#test_suffixes];
4820           my $cur = '';
4821           foreach my $test_suffix (@test_suffixes)
4822             {
4823               if ($test_suffix eq $last_suffix)
4824                 {
4825                   $cur = 'TEST_LOGS';
4826                 }
4827               else
4828                 {
4829                   $cur = 'am__test_logs' . $nhelper;
4830                 }
4831               define_variable ($cur,
4832                 '$(' . $prev . ':' . $test_suffix . $post . '=.log)', INTERNAL);
4833               $post = '.log';
4834               $prev = $cur;
4835               $nhelper++;
4836               if ($test_suffix ne $at_exeext && $test_suffix ne '')
4837                 {
4838                   (my $ext = $test_suffix) =~ s/^\.//;
4839                   $ext = uc $ext;
4840                   my $compile = $ext . '_LOG_COMPILE';
4841                   define_variable ($compile,
4842                                    '$(' . $ext . '_LOG_COMPILER) $(AM_' .  $ext . '_LOG_FLAGS)'
4843                                    . ' $(' . $ext . '_LOG_FLAGS)', INTERNAL);
4844                   $output_rules .= file_contents ('check2', new Automake::Location,
4845                                                   GENERIC => 1,
4846                                                   OBJ => '',
4847                                                   SOURCE => '$<',
4848                                                   COMPILE => '$(' . $compile . ')' ,
4849                                                   EXT => $test_suffix);
4850                 }
4851             }
4853           define_variable ('TEST_LOGS_TMP', '$(TEST_LOGS:.log=.log-t)', INTERNAL);
4855           $clean_files{'$(TEST_LOGS_TMP)'} = MOSTLY_CLEAN;
4856           $clean_files{'$(TEST_LOGS)'} = MOSTLY_CLEAN;
4857           $clean_files{'$(TEST_SUITE_LOG)'} = MOSTLY_CLEAN;
4858           $clean_files{'$(TEST_SUITE_HTML)'} = MOSTLY_CLEAN;
4859         }
4860     }
4863 # Handle Emacs Lisp.
4864 sub handle_emacs_lisp
4866   my @elfiles = &am_install_var ('-candist', 'lisp', 'LISP',
4867                                  'lisp', 'noinst');
4869   return if ! @elfiles;
4871   define_pretty_variable ('am__ELFILES', TRUE, INTERNAL,
4872                           map { $_->[1] } @elfiles);
4873   define_pretty_variable ('am__ELCFILES', TRUE, INTERNAL,
4874                           '$(am__ELFILES:.el=.elc)');
4875   # This one can be overridden by users.
4876   define_pretty_variable ('ELCFILES', TRUE, INTERNAL, '$(LISP:.el=.elc)');
4878   push @all, '$(ELCFILES)';
4880   require_variables ($elfiles[0][0], "Emacs Lisp sources seen", TRUE,
4881                      'EMACS', 'lispdir');
4882   require_conf_file ($elfiles[0][0], FOREIGN, 'elisp-comp');
4883   &define_variable ('elisp_comp', "$am_config_aux_dir/elisp-comp", INTERNAL);
4886 # Handle Python
4887 sub handle_python
4889   my @pyfiles = &am_install_var ('-defaultdist', 'python', 'PYTHON',
4890                                  'noinst');
4891   return if ! @pyfiles;
4893   require_variables ($pyfiles[0][0], "Python sources seen", TRUE, 'PYTHON');
4894   require_conf_file ($pyfiles[0][0], FOREIGN, 'py-compile');
4895   &define_variable ('py_compile', "$am_config_aux_dir/py-compile", INTERNAL);
4898 # Handle Java.
4899 sub handle_java
4901     my @sourcelist = &am_install_var ('-candist',
4902                                       'java', 'JAVA',
4903                                       'java', 'noinst', 'check');
4904     return if ! @sourcelist;
4906     my @prefix = am_primary_prefixes ('JAVA', 1,
4907                                       'java', 'noinst', 'check');
4909     my $dir;
4910     foreach my $curs (@prefix)
4911       {
4912         next
4913           if $curs eq 'EXTRA';
4915         err_var "${curs}_JAVA", "multiple _JAVA primaries in use"
4916           if defined $dir;
4917         $dir = $curs;
4918       }
4921     push (@all, 'class' . $dir . '.stamp');
4925 # Handle some of the minor options.
4926 sub handle_minor_options
4928   if (option 'readme-alpha')
4929     {
4930       if ($relative_dir eq '.')
4931         {
4932           if ($package_version !~ /^$GNITS_VERSION_PATTERN$/)
4933             {
4934               msg ('error-gnits', $package_version_location,
4935                    "version `$package_version' doesn't follow " .
4936                    "Gnits standards");
4937             }
4938           if (defined $1 && -f 'README-alpha')
4939             {
4940               # This means we have an alpha release.  See
4941               # GNITS_VERSION_PATTERN for details.
4942               push_dist_common ('README-alpha');
4943             }
4944         }
4945     }
4948 ################################################################
4950 # ($OUTPUT, @INPUTS)
4951 # &split_config_file_spec ($SPEC)
4952 # -------------------------------
4953 # Decode the Autoconf syntax for config files (files, headers, links
4954 # etc.).
4955 sub split_config_file_spec ($)
4957   my ($spec) = @_;
4958   my ($output, @inputs) = split (/:/, $spec);
4960   push @inputs, "$output.in"
4961     unless @inputs;
4963   return ($output, @inputs);
4966 # $input
4967 # locate_am (@POSSIBLE_SOURCES)
4968 # -----------------------------
4969 # AC_CONFIG_FILES allow specifications such as Makefile:top.in:mid.in:bot.in
4970 # This functions returns the first *.in file for which a *.am exists.
4971 # It returns undef otherwise.
4972 sub locate_am (@)
4974   my (@rest) = @_;
4975   my $input;
4976   foreach my $file (@rest)
4977     {
4978       if (($file =~ /^(.*)\.in$/) && -f "$1.am")
4979         {
4980           $input = $file;
4981           last;
4982         }
4983     }
4984   return $input;
4987 my %make_list;
4989 # &scan_autoconf_config_files ($WHERE, $CONFIG-FILES)
4990 # ---------------------------------------------------
4991 # Study $CONFIG-FILES which is the first argument to AC_CONFIG_FILES
4992 # (or AC_OUTPUT).
4993 sub scan_autoconf_config_files ($$)
4995   my ($where, $config_files) = @_;
4997   # Look at potential Makefile.am's.
4998   foreach (split ' ', $config_files)
4999     {
5000       # Must skip empty string for Perl 4.
5001       next if $_ eq "\\" || $_ eq '';
5003       # Handle $local:$input syntax.
5004       my ($local, @rest) = split (/:/);
5005       @rest = ("$local.in",) unless @rest;
5006       msg ('portability', $where,
5007           "Omit leading `./' from config file names such as `$local',"
5008           . "\nas not all make implementations treat `file' and `./file' equally.")
5009         if ($local =~ /^\.\//);
5010       my $input = locate_am @rest;
5011       if ($input)
5012         {
5013           # We have a file that automake should generate.
5014           $make_list{$input} = join (':', ($local, @rest));
5015         }
5016       else
5017         {
5018           # We have a file that automake should cause to be
5019           # rebuilt, but shouldn't generate itself.
5020           push (@other_input_files, $_);
5021         }
5022       $ac_config_files_location{$local} = $where;
5023       $ac_config_files_condition{$local} =
5024         new Automake::Condition (@cond_stack)
5025           if (@cond_stack);
5026     }
5030 # &scan_autoconf_traces ($FILENAME)
5031 # ---------------------------------
5032 sub scan_autoconf_traces ($)
5034   my ($filename) = @_;
5036   # Macros to trace, with their minimal number of arguments.
5037   #
5038   # IMPORTANT: If you add a macro here, you should also add this macro
5039   # =========  to Automake-preselection in autoconf/lib/autom4te.in.
5040   my %traced = (
5041                 AC_CANONICAL_BUILD => 0,
5042                 AC_CANONICAL_HOST => 0,
5043                 AC_CANONICAL_TARGET => 0,
5044                 AC_CONFIG_AUX_DIR => 1,
5045                 AC_CONFIG_FILES => 1,
5046                 AC_CONFIG_HEADERS => 1,
5047                 AC_CONFIG_LIBOBJ_DIR => 1,
5048                 AC_CONFIG_LINKS => 1,
5049                 AC_FC_SRCEXT => 1,
5050                 AC_INIT => 0,
5051                 AC_LIBSOURCE => 1,
5052                 AC_REQUIRE_AUX_FILE => 1,
5053                 AC_SUBST_TRACE => 1,
5054                 AM_AUTOMAKE_VERSION => 1,
5055                 AM_CONDITIONAL => 2,
5056                 AM_ENABLE_MULTILIB => 0,
5057                 AM_GNU_GETTEXT => 0,
5058                 AM_GNU_GETTEXT_INTL_SUBDIR => 0,
5059                 AM_INIT_AUTOMAKE => 0,
5060                 AM_MAINTAINER_MODE => 0,
5061                 AM_PROG_CC_C_O => 0,
5062                 _AM_SUBST_NOTMAKE => 1,
5063                 _AM_COND_IF => 1,
5064                 _AM_COND_ELSE => 1,
5065                 _AM_COND_ENDIF => 1,
5066                 LT_SUPPORTED_TAG => 1,
5067                 _LT_AC_TAGCONFIG => 0,
5068                 m4_include => 1,
5069                 m4_sinclude => 1,
5070                 sinclude => 1,
5071               );
5073   my $traces = ($ENV{AUTOCONF} || 'autoconf') . " ";
5075   # Use a separator unlikely to be used, not `:', the default, which
5076   # has a precise meaning for AC_CONFIG_FILES and so on.
5077   $traces .= join (' ',
5078                    map { "--trace=$_" . ':\$f:\$l::\$d::\$n::\${::}%' }
5079                    (keys %traced));
5081   my $tracefh = new Automake::XFile ("$traces $filename |");
5082   verb "reading $traces";
5084   @cond_stack = ();
5085   my $where;
5087   while ($_ = $tracefh->getline)
5088     {
5089       chomp;
5090       my ($here, $depth, @args) = split (/::/);
5091       $where = new Automake::Location $here;
5092       my $macro = $args[0];
5094       prog_error ("unrequested trace `$macro'")
5095         unless exists $traced{$macro};
5097       # Skip and diagnose malformed calls.
5098       if ($#args < $traced{$macro})
5099         {
5100           msg ('syntax', $where, "not enough arguments for $macro");
5101           next;
5102         }
5104       # Alphabetical ordering please.
5105       if ($macro eq 'AC_CANONICAL_BUILD')
5106         {
5107           if ($seen_canonical <= AC_CANONICAL_BUILD)
5108             {
5109               $seen_canonical = AC_CANONICAL_BUILD;
5110               $canonical_location = $where;
5111             }
5112         }
5113       elsif ($macro eq 'AC_CANONICAL_HOST')
5114         {
5115           if ($seen_canonical <= AC_CANONICAL_HOST)
5116             {
5117               $seen_canonical = AC_CANONICAL_HOST;
5118               $canonical_location = $where;
5119             }
5120         }
5121       elsif ($macro eq 'AC_CANONICAL_TARGET')
5122         {
5123           $seen_canonical = AC_CANONICAL_TARGET;
5124           $canonical_location = $where;
5125         }
5126       elsif ($macro eq 'AC_CONFIG_AUX_DIR')
5127         {
5128           if ($seen_init_automake)
5129             {
5130               error ($where, "AC_CONFIG_AUX_DIR must be called before "
5131                      . "AM_INIT_AUTOMAKE...", partial => 1);
5132               error ($seen_init_automake, "... AM_INIT_AUTOMAKE called here");
5133             }
5134           $config_aux_dir = $args[1];
5135           $config_aux_dir_set_in_configure_ac = 1;
5136           $relative_dir = '.';
5137           check_directory ($config_aux_dir, $where);
5138         }
5139       elsif ($macro eq 'AC_CONFIG_FILES')
5140         {
5141           # Look at potential Makefile.am's.
5142           scan_autoconf_config_files ($where, $args[1]);
5143         }
5144       elsif ($macro eq 'AC_CONFIG_HEADERS')
5145         {
5146           foreach my $spec (split (' ', $args[1]))
5147             {
5148               my ($dest, @src) = split (':', $spec);
5149               $ac_config_files_location{$dest} = $where;
5150               push @config_headers, $spec;
5151             }
5152         }
5153       elsif ($macro eq 'AC_CONFIG_LIBOBJ_DIR')
5154         {
5155           $config_libobj_dir = $args[1];
5156           $relative_dir = '.';
5157           check_directory ($config_libobj_dir, $where);
5158         }
5159       elsif ($macro eq 'AC_CONFIG_LINKS')
5160         {
5161           foreach my $spec (split (' ', $args[1]))
5162             {
5163               my ($dest, $src) = split (':', $spec);
5164               $ac_config_files_location{$dest} = $where;
5165               push @config_links, $spec;
5166             }
5167         }
5168       elsif ($macro eq 'AC_FC_SRCEXT')
5169         {
5170           my $suffix = $args[1];
5171           # These flags are used as %SOURCEFLAG% in depend2.am,
5172           # where the trailing space is important.
5173           $sourceflags{'.' . $suffix} = '$(FCFLAGS_' . $suffix . ') '
5174             if ($suffix eq 'f90' || $suffix eq 'f95' || $suffix eq 'f03' || $suffix eq 'f08');
5175         }
5176       elsif ($macro eq 'AC_INIT')
5177         {
5178           if (defined $args[2])
5179             {
5180               $package_version = $args[2];
5181               $package_version_location = $where;
5182             }
5183         }
5184       elsif ($macro eq 'AC_LIBSOURCE')
5185         {
5186           $libsources{$args[1]} = $here;
5187         }
5188       elsif ($macro eq 'AC_REQUIRE_AUX_FILE')
5189         {
5190           # Only remember the first time a file is required.
5191           $required_aux_file{$args[1]} = $where
5192             unless exists $required_aux_file{$args[1]};
5193         }
5194       elsif ($macro eq 'AC_SUBST_TRACE')
5195         {
5196           # Just check for alphanumeric in AC_SUBST_TRACE.  If you do
5197           # AC_SUBST(5), then too bad.
5198           $configure_vars{$args[1]} = $where
5199             if $args[1] =~ /^\w+$/;
5200         }
5201       elsif ($macro eq 'AM_AUTOMAKE_VERSION')
5202         {
5203           error ($where,
5204                  "version mismatch.  This is Automake $VERSION,\n" .
5205                  "but the definition used by this AM_INIT_AUTOMAKE\n" .
5206                  "comes from Automake $args[1].  You should recreate\n" .
5207                  "aclocal.m4 with aclocal and run automake again.\n",
5208                  # $? = 63 is used to indicate version mismatch to missing.
5209                  exit_code => 63)
5210             if $VERSION ne $args[1];
5212           $seen_automake_version = 1;
5213         }
5214       elsif ($macro eq 'AM_CONDITIONAL')
5215         {
5216           $configure_cond{$args[1]} = $where;
5217         }
5218       elsif ($macro eq 'AM_ENABLE_MULTILIB')
5219         {
5220           $seen_multilib = $where;
5221         }
5222       elsif ($macro eq 'AM_GNU_GETTEXT')
5223         {
5224           $seen_gettext = $where;
5225           $ac_gettext_location = $where;
5226           $seen_gettext_external = grep ($_ eq 'external', @args);
5227         }
5228       elsif ($macro eq 'AM_GNU_GETTEXT_INTL_SUBDIR')
5229         {
5230           $seen_gettext_intl = $where;
5231         }
5232       elsif ($macro eq 'AM_INIT_AUTOMAKE')
5233         {
5234           $seen_init_automake = $where;
5235           if (defined $args[2])
5236             {
5237               $package_version = $args[2];
5238               $package_version_location = $where;
5239             }
5240           elsif (defined $args[1])
5241             {
5242               exit $exit_code
5243                 if (process_global_option_list ($where,
5244                                                 split (' ', $args[1])));
5245             }
5246         }
5247       elsif ($macro eq 'AM_MAINTAINER_MODE')
5248         {
5249           $seen_maint_mode = $where;
5250         }
5251       elsif ($macro eq 'AM_PROG_CC_C_O')
5252         {
5253           $seen_cc_c_o = $where;
5254         }
5255       elsif ($macro eq '_AM_COND_IF')
5256         {
5257           cond_stack_if ('', $args[1], $where);
5258           error ($where, "missing m4 quoting, macro depth $depth")
5259             if ($depth != 1);
5260         }
5261       elsif ($macro eq '_AM_COND_ELSE')
5262         {
5263           cond_stack_else ('!', $args[1], $where);
5264           error ($where, "missing m4 quoting, macro depth $depth")
5265             if ($depth != 1);
5266         }
5267       elsif ($macro eq '_AM_COND_ENDIF')
5268         {
5269           cond_stack_endif (undef, undef, $where);
5270           error ($where, "missing m4 quoting, macro depth $depth")
5271             if ($depth != 1);
5272         }
5273       elsif ($macro eq '_AM_SUBST_NOTMAKE')
5274         {
5275           $ignored_configure_vars{$args[1]} = $where;
5276         }
5277       elsif ($macro eq 'm4_include'
5278              || $macro eq 'm4_sinclude'
5279              || $macro eq 'sinclude')
5280         {
5281           # Skip missing `sinclude'd files.
5282           next if $macro ne 'm4_include' && ! -f $args[1];
5284           # Some modified versions of Autoconf don't use
5285           # frozen files.  Consequently it's possible that we see all
5286           # m4_include's performed during Autoconf's startup.
5287           # Obviously we don't want to distribute Autoconf's files
5288           # so we skip absolute filenames here.
5289           push @configure_deps, '$(top_srcdir)/' . $args[1]
5290             unless $here =~ m,^(?:\w:)?[\\/],;
5291           # Keep track of the greatest timestamp.
5292           if (-e $args[1])
5293             {
5294               my $mtime = mtime $args[1];
5295               $configure_deps_greatest_timestamp = $mtime
5296                 if $mtime > $configure_deps_greatest_timestamp;
5297             }
5298         }
5299       elsif ($macro eq 'LT_SUPPORTED_TAG')
5300         {
5301           $libtool_tags{$args[1]} = 1;
5302           $libtool_new_api = 1;
5303         }
5304       elsif ($macro eq '_LT_AC_TAGCONFIG')
5305         {
5306           # _LT_AC_TAGCONFIG is an old macro present in Libtool 1.5.
5307           # We use it to detect whether tags are supported.  Our
5308           # preferred interface is LT_SUPPORTED_TAG, but it was
5309           # introduced in Libtool 1.6.
5310           if (0 == keys %libtool_tags)
5311             {
5312               # Hardcode the tags supported by Libtool 1.5.
5313               %libtool_tags = (CC => 1, CXX => 1, GCJ => 1, F77 => 1);
5314             }
5315         }
5316     }
5318   error ($where, "condition stack not properly closed")
5319     if (@cond_stack);
5321   $tracefh->close;
5325 # &scan_autoconf_files ()
5326 # -----------------------
5327 # Check whether we use `configure.ac' or `configure.in'.
5328 # Scan it (and possibly `aclocal.m4') for interesting things.
5329 # We must scan aclocal.m4 because there might be AC_SUBSTs and such there.
5330 sub scan_autoconf_files ()
5332   # Reinitialize libsources here.  This isn't really necessary,
5333   # since we currently assume there is only one configure.ac.  But
5334   # that won't always be the case.
5335   %libsources = ();
5337   # Keep track of the youngest configure dependency.
5338   $configure_deps_greatest_timestamp = mtime $configure_ac;
5339   if (-e 'aclocal.m4')
5340     {
5341       my $mtime = mtime 'aclocal.m4';
5342       $configure_deps_greatest_timestamp = $mtime
5343         if $mtime > $configure_deps_greatest_timestamp;
5344     }
5346   scan_autoconf_traces ($configure_ac);
5348   @configure_input_files = sort keys %make_list;
5349   # Set input and output files if not specified by user.
5350   if (! @input_files)
5351     {
5352       @input_files = @configure_input_files;
5353       %output_files = %make_list;
5354     }
5357   if (! $seen_init_automake)
5358     {
5359       err_ac ("no proper invocation of AM_INIT_AUTOMAKE was found.\nYou "
5360               . "should verify that $configure_ac invokes AM_INIT_AUTOMAKE,"
5361               . "\nthat aclocal.m4 is present in the top-level directory,\n"
5362               . "and that aclocal.m4 was recently regenerated "
5363               . "(using aclocal).");
5364     }
5365   else
5366     {
5367       if (! $seen_automake_version)
5368         {
5369           if (-f 'aclocal.m4')
5370             {
5371               error ($seen_init_automake,
5372                      "your implementation of AM_INIT_AUTOMAKE comes from " .
5373                      "an\nold Automake version.  You should recreate " .
5374                      "aclocal.m4\nwith aclocal and run automake again.\n",
5375                      # $? = 63 is used to indicate version mismatch to missing.
5376                      exit_code => 63);
5377             }
5378           else
5379             {
5380               error ($seen_init_automake,
5381                      "no proper implementation of AM_INIT_AUTOMAKE was " .
5382                      "found,\nprobably because aclocal.m4 is missing...\n" .
5383                      "You should run aclocal to create this file, then\n" .
5384                      "run automake again.\n");
5385             }
5386         }
5387     }
5389   locate_aux_dir ();
5391   # Reorder @input_files so that the Makefile that distributes aux
5392   # files is processed last.  This is important because each directory
5393   # can require auxiliary scripts and we should wait until they have
5394   # been installed before distributing them.
5396   # The Makefile.in that distribute the aux files is the one in
5397   # $config_aux_dir or the top-level Makefile.
5398   my $auxdirdist = is_make_dir ($config_aux_dir) ? $config_aux_dir : '.';
5399   my @new_input_files = ();
5400   while (@input_files)
5401     {
5402       my $in = pop @input_files;
5403       my @ins = split (/:/, $output_files{$in});
5404       if (dirname ($ins[0]) eq $auxdirdist)
5405         {
5406           push @new_input_files, $in;
5407           $automake_will_process_aux_dir = 1;
5408         }
5409       else
5410         {
5411           unshift @new_input_files, $in;
5412         }
5413     }
5414   @input_files = @new_input_files;
5416   # If neither the auxdir/Makefile nor the ./Makefile are generated
5417   # by Automake, we won't distribute the aux files anyway.  Assume
5418   # the user know what (s)he does, and pretend we will distribute
5419   # them to disable the error in require_file_internal.
5420   $automake_will_process_aux_dir = 1 if ! is_make_dir ($auxdirdist);
5422   # Look for some files we need.  Always check for these.  This
5423   # check must be done for every run, even those where we are only
5424   # looking at a subdir Makefile.  We must set relative_dir for
5425   # maybe_push_required_file to work.
5426   # Sort the files for stable verbose output.
5427   $relative_dir = '.';
5428   foreach my $file (sort keys %required_aux_file)
5429     {
5430       require_conf_file ($required_aux_file{$file}->get, FOREIGN, $file)
5431     }
5432   err_am "`install.sh' is an anachronism; use `install-sh' instead"
5433     if -f $config_aux_dir . '/install.sh';
5435   # Preserve dist_common for later.
5436   $configure_dist_common = variable_value ('DIST_COMMON') || '';
5440 ################################################################
5442 # Set up for Cygnus mode.
5443 sub check_cygnus
5445   my $cygnus = option 'cygnus';
5446   return unless $cygnus;
5448   set_strictness ('foreign');
5449   set_option ('no-installinfo', $cygnus);
5450   set_option ('no-dependencies', $cygnus);
5451   set_option ('no-dist', $cygnus);
5453   err_ac "`AM_MAINTAINER_MODE' required when --cygnus specified"
5454     if !$seen_maint_mode;
5457 # Do any extra checking for GNU standards.
5458 sub check_gnu_standards
5460   if ($relative_dir eq '.')
5461     {
5462       # In top level (or only) directory.
5463       require_file ("$am_file.am", GNU,
5464                     qw/INSTALL NEWS README AUTHORS ChangeLog/);
5466       # Accept one of these three licenses; default to COPYING.
5467       # Make sure we do not overwrite an existing license.
5468       my $license;
5469       foreach (qw /COPYING COPYING.LIB COPYING.LESSER/)
5470         {
5471           if (-f $_)
5472             {
5473               $license = $_;
5474               last;
5475             }
5476         }
5477       require_file ("$am_file.am", GNU, 'COPYING')
5478         unless $license;
5479     }
5481   for my $opt ('no-installman', 'no-installinfo')
5482     {
5483       msg ('error-gnu', option $opt,
5484            "option `$opt' disallowed by GNU standards")
5485         if option $opt;
5486     }
5489 # Do any extra checking for GNITS standards.
5490 sub check_gnits_standards
5492   if ($relative_dir eq '.')
5493     {
5494       # In top level (or only) directory.
5495       require_file ("$am_file.am", GNITS, 'THANKS');
5496     }
5499 ################################################################
5501 # Functions to handle files of each language.
5503 # Each `lang_X_rewrite($DIRECTORY, $BASE, $EXT)' function follows a
5504 # simple formula: Return value is LANG_SUBDIR if the resulting object
5505 # file should be in a subdir if the source file is, LANG_PROCESS if
5506 # file is to be dealt with, LANG_IGNORE otherwise.
5508 # Much of the actual processing is handled in
5509 # handle_single_transform.  These functions exist so that
5510 # auxiliary information can be recorded for a later cleanup pass.
5511 # Note that the calls to these functions are computed, so don't bother
5512 # searching for their precise names in the source.
5514 # This is just a convenience function that can be used to determine
5515 # when a subdir object should be used.
5516 sub lang_sub_obj
5518     return option 'subdir-objects' ? LANG_SUBDIR : LANG_PROCESS;
5521 # Rewrite a single C source file.
5522 sub lang_c_rewrite
5524   my ($directory, $base, $ext, $nonansi_obj, $have_per_exec_flags, $var) = @_;
5526   if (option 'ansi2knr' && $base =~ /_$/)
5527     {
5528       # FIXME: include line number in error.
5529       err_am "C source file `$base.c' would be deleted by ansi2knr rules";
5530     }
5532   my $r = LANG_PROCESS;
5533   if (option 'subdir-objects')
5534     {
5535       $r = LANG_SUBDIR;
5536       if ($directory && $directory ne '.')
5537         {
5538           $base = $directory . '/' . $base;
5540           # libtool is always able to put the object at the proper place,
5541           # so we do not have to require AM_PROG_CC_C_O when building .lo files.
5542           msg_var ('portability', $var,
5543                    "compiling `$base.c' in subdir requires "
5544                    . "`AM_PROG_CC_C_O' in `$configure_ac'",
5545                    uniq_scope => US_GLOBAL,
5546                    uniq_part => 'AM_PROG_CC_C_O subdir')
5547             unless $seen_cc_c_o || $nonansi_obj eq '.lo';
5548         }
5550       # In this case we already have the directory information, so
5551       # don't add it again.
5552       $de_ansi_files{$base} = '';
5553     }
5554   else
5555     {
5556       $de_ansi_files{$base} = (($directory eq '.' || $directory eq '')
5557                                ? ''
5558                                : "$directory/");
5559     }
5561   if (! $seen_cc_c_o
5562       && $have_per_exec_flags
5563       && ! option 'subdir-objects'
5564       && $nonansi_obj ne '.lo')
5565     {
5566       msg_var ('portability',
5567                $var, "compiling `$base.c' with per-target flags requires "
5568                . "`AM_PROG_CC_C_O' in `$configure_ac'",
5569                uniq_scope => US_GLOBAL,
5570                uniq_part => 'AM_PROG_CC_C_O per-target')
5571     }
5573     return $r;
5576 # Rewrite a single C++ source file.
5577 sub lang_cxx_rewrite
5579     return &lang_sub_obj;
5582 # Rewrite a single header file.
5583 sub lang_header_rewrite
5585     # Header files are simply ignored.
5586     return LANG_IGNORE;
5589 # Rewrite a single yacc file.
5590 sub lang_yacc_rewrite
5592     my ($directory, $base, $ext) = @_;
5594     my $r = &lang_sub_obj;
5595     (my $newext = $ext) =~ tr/y/c/;
5596     return ($r, $newext);
5599 # Rewrite a single yacc++ file.
5600 sub lang_yaccxx_rewrite
5602     my ($directory, $base, $ext) = @_;
5604     my $r = &lang_sub_obj;
5605     (my $newext = $ext) =~ tr/y/c/;
5606     return ($r, $newext);
5609 # Rewrite a single lex file.
5610 sub lang_lex_rewrite
5612     my ($directory, $base, $ext) = @_;
5614     my $r = &lang_sub_obj;
5615     (my $newext = $ext) =~ tr/l/c/;
5616     return ($r, $newext);
5619 # Rewrite a single lex++ file.
5620 sub lang_lexxx_rewrite
5622     my ($directory, $base, $ext) = @_;
5624     my $r = &lang_sub_obj;
5625     (my $newext = $ext) =~ tr/l/c/;
5626     return ($r, $newext);
5629 # Rewrite a single assembly file.
5630 sub lang_asm_rewrite
5632     return &lang_sub_obj;
5635 # Rewrite a single preprocessed assembly file.
5636 sub lang_cppasm_rewrite
5638     return &lang_sub_obj;
5641 # Rewrite a single Fortran 77 file.
5642 sub lang_f77_rewrite
5644     return &lang_sub_obj;
5647 # Rewrite a single Fortran file.
5648 sub lang_fc_rewrite
5650     return &lang_sub_obj;
5653 # Rewrite a single preprocessed Fortran file.
5654 sub lang_ppfc_rewrite
5656     return &lang_sub_obj;
5659 # Rewrite a single preprocessed Fortran 77 file.
5660 sub lang_ppf77_rewrite
5662     return &lang_sub_obj;
5665 # Rewrite a single ratfor file.
5666 sub lang_ratfor_rewrite
5668     return &lang_sub_obj;
5671 # Rewrite a single Objective C file.
5672 sub lang_objc_rewrite
5674     return &lang_sub_obj;
5677 # Rewrite a single Unified Parallel C file.
5678 sub lang_upc_rewrite
5680     return &lang_sub_obj;
5683 # Rewrite a single Java file.
5684 sub lang_java_rewrite
5686     return LANG_SUBDIR;
5689 # The lang_X_finish functions are called after all source file
5690 # processing is done.  Each should handle defining rules for the
5691 # language, etc.  A finish function is only called if a source file of
5692 # the appropriate type has been seen.
5694 sub lang_c_finish
5696     # Push all libobjs files onto de_ansi_files.  We actually only
5697     # push files which exist in the current directory, and which are
5698     # genuine source files.
5699     foreach my $file (keys %libsources)
5700     {
5701         if ($file =~ /^(.*)\.[cly]$/ && -f "$relative_dir/$file")
5702         {
5703             $de_ansi_files{$1} = ''
5704         }
5705     }
5707     if (option 'ansi2knr' && keys %de_ansi_files)
5708     {
5709         # Make all _.c files depend on their corresponding .c files.
5710         my @objects;
5711         foreach my $base (sort keys %de_ansi_files)
5712         {
5713             # Each _.c file must depend on ansi2knr; otherwise it
5714             # might be used in a parallel build before it is built.
5715             # We need to support files in the srcdir and in the build
5716             # dir (because these files might be auto-generated.  But
5717             # we can't use $< -- some makes only define $< during a
5718             # suffix rule.
5719             my $ansfile = $de_ansi_files{$base} . $base . '.c';
5720             $output_rules .= ($base . "_.c: $ansfile \$(ANSI2KNR)\n\t"
5721                               . '$(CPP) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) '
5722                               . '`if test -f $(srcdir)/' . $ansfile
5723                               . '; then echo $(srcdir)/' . $ansfile
5724                               . '; else echo ' . $ansfile . '; fi` '
5725                               . "| sed 's/^# \\([0-9]\\)/#line \\1/' "
5726                               . '| $(ANSI2KNR) > $@'
5727                               # If ansi2knr fails then we shouldn't
5728                               # create the _.c file
5729                               . " || rm -f \$\@\n");
5730             push (@objects, $base . '_.$(OBJEXT)');
5731             push (@objects, $base . '_.lo')
5732               if var ('LIBTOOL');
5734             # Explicitly clean the _.c files if they are in a
5735             # subdirectory. (In the current directory they get erased
5736             # by a `rm -f *_.c' rule.)
5737             $clean_files{$base . '_.c'} = MOSTLY_CLEAN
5738               if dirname ($base) ne '.';
5739         }
5741         # Make all _.o (and _.lo) files depend on ansi2knr.
5742         # Use a sneaky little hack to make it print nicely.
5743         &pretty_print_rule ('', '', @objects, ':', '$(ANSI2KNR)');
5744     }
5747 # This is a yacc helper which is called whenever we have decided to
5748 # compile a yacc file.
5749 sub lang_yacc_target_hook
5751     my ($self, $aggregate, $output, $input, %transform) = @_;
5753     my $flag = $aggregate . "_YFLAGS";
5754     my $flagvar = var $flag;
5755     my $YFLAGSvar = var 'YFLAGS';
5756     if (($flagvar && $flagvar->variable_value =~ /$DASH_D_PATTERN/o)
5757         || ($YFLAGSvar && $YFLAGSvar->variable_value =~ /$DASH_D_PATTERN/o))
5758     {
5759         (my $output_base = $output) =~ s/$KNOWN_EXTENSIONS_PATTERN$//;
5760         my $header = $output_base . '.h';
5762         # Found a `-d' that applies to the compilation of this file.
5763         # Add a dependency for the generated header file, and arrange
5764         # for that file to be included in the distribution.
5765         foreach my $cond (Automake::Rule::define (${header}, 'internal',
5766                                                   RULE_AUTOMAKE, TRUE,
5767                                                   INTERNAL))
5768           {
5769             my $condstr = $cond->subst_string;
5770             $output_rules .=
5771               "$condstr${header}: $output\n"
5772               # Recover from removal of $header
5773               . "$condstr\t\@if test ! -f \$@; then \\\n"
5774               . "$condstr\t  rm -f $output; \\\n"
5775               . "$condstr\t  \$(MAKE) \$(AM_MAKEFLAGS) $output; \\\n"
5776               . "$condstr\telse :; fi\n";
5777           }
5778         # Distribute the generated file, unless its .y source was
5779         # listed in a nodist_ variable.  (&handle_source_transform
5780         # will set DIST_SOURCE.)
5781         &push_dist_common ($header)
5782           if $transform{'DIST_SOURCE'};
5784         # If the files are built in the build directory, then we want
5785         # to remove them with `make clean'.  If they are in srcdir
5786         # they shouldn't be touched.  However, we can't determine this
5787         # statically, and the GNU rules say that yacc/lex output files
5788         # should be removed by maintainer-clean.  So that's what we
5789         # do.
5790         $clean_files{$header} = MAINTAINER_CLEAN;
5791     }
5792     # Erase $OUTPUT on `make maintainer-clean' (by GNU standards).
5793     # See the comment above for $HEADER.
5794     $clean_files{$output} = MAINTAINER_CLEAN;
5797 # This is a lex helper which is called whenever we have decided to
5798 # compile a lex file.
5799 sub lang_lex_target_hook
5801     my ($self, $aggregate, $output, $input) = @_;
5802     # If the files are built in the build directory, then we want to
5803     # remove them with `make clean'.  If they are in srcdir they
5804     # shouldn't be touched.  However, we can't determine this
5805     # statically, and the GNU rules say that yacc/lex output files
5806     # should be removed by maintainer-clean.  So that's what we do.
5807     $clean_files{$output} = MAINTAINER_CLEAN;
5810 # This is a helper for both lex and yacc.
5811 sub yacc_lex_finish_helper
5813   return if defined $language_scratch{'lex-yacc-done'};
5814   $language_scratch{'lex-yacc-done'} = 1;
5816   # FIXME: for now, no line number.
5817   require_conf_file ($configure_ac, FOREIGN, 'ylwrap');
5818   &define_variable ('YLWRAP', "$am_config_aux_dir/ylwrap", INTERNAL);
5821 sub lang_yacc_finish
5823   return if defined $language_scratch{'yacc-done'};
5824   $language_scratch{'yacc-done'} = 1;
5826   reject_var 'YACCFLAGS', "`YACCFLAGS' obsolete; use `YFLAGS' instead";
5828   yacc_lex_finish_helper;
5832 sub lang_lex_finish
5834   return if defined $language_scratch{'lex-done'};
5835   $language_scratch{'lex-done'} = 1;
5837   yacc_lex_finish_helper;
5841 # Given a hash table of linker names, pick the name that has the most
5842 # precedence.  This is lame, but something has to have global
5843 # knowledge in order to eliminate the conflict.  Add more linkers as
5844 # required.
5845 sub resolve_linker
5847     my (%linkers) = @_;
5849     foreach my $l (qw(GCJLINK CXXLINK F77LINK FCLINK OBJCLINK UPCLINK))
5850     {
5851         return $l if defined $linkers{$l};
5852     }
5853     return 'LINK';
5856 # Called to indicate that an extension was used.
5857 sub saw_extension
5859     my ($ext) = @_;
5860     if (! defined $extension_seen{$ext})
5861     {
5862         $extension_seen{$ext} = 1;
5863     }
5864     else
5865     {
5866         ++$extension_seen{$ext};
5867     }
5870 # Return the number of files seen for a given language.  Knows about
5871 # special cases we care about.  FIXME: this is hideous.  We need
5872 # something that involves real language objects.  For instance yacc
5873 # and yaccxx could both derive from a common yacc class which would
5874 # know about the strange ylwrap requirement.  (Or better yet we could
5875 # just not support legacy yacc!)
5876 sub count_files_for_language
5878     my ($name) = @_;
5880     my @names;
5881     if ($name eq 'yacc' || $name eq 'yaccxx')
5882     {
5883         @names = ('yacc', 'yaccxx');
5884     }
5885     elsif ($name eq 'lex' || $name eq 'lexxx')
5886     {
5887         @names = ('lex', 'lexxx');
5888     }
5889     else
5890     {
5891         @names = ($name);
5892     }
5894     my $r = 0;
5895     foreach $name (@names)
5896     {
5897         my $lang = $languages{$name};
5898         foreach my $ext (@{$lang->extensions})
5899         {
5900             $r += $extension_seen{$ext}
5901                 if defined $extension_seen{$ext};
5902         }
5903     }
5905     return $r
5908 # Called to ask whether source files have been seen . If HEADERS is 1,
5909 # headers can be included.
5910 sub saw_sources_p
5912     my ($headers) = @_;
5914     # count all the sources
5915     my $count = 0;
5916     foreach my $val (values %extension_seen)
5917     {
5918         $count += $val;
5919     }
5921     if (!$headers)
5922     {
5923         $count -= count_files_for_language ('header');
5924     }
5926     return $count > 0;
5930 # register_language (%ATTRIBUTE)
5931 # ------------------------------
5932 # Register a single language.
5933 # Each %ATTRIBUTE is of the form ATTRIBUTE => VALUE.
5934 sub register_language (%)
5936   my (%option) = @_;
5938   # Set the defaults.
5939   $option{'ansi'} = 0
5940     unless defined $option{'ansi'};
5941   $option{'autodep'} = 'no'
5942     unless defined $option{'autodep'};
5943   $option{'linker'} = ''
5944     unless defined $option{'linker'};
5945   $option{'flags'} = []
5946     unless defined $option{'flags'};
5947   $option{'output_extensions'} = sub { return ( '.$(OBJEXT)', '.lo' ) }
5948     unless defined $option{'output_extensions'};
5949   $option{'nodist_specific'} = 0
5950     unless defined $option{'nodist_specific'};
5952   my $lang = new Language (%option);
5954   # Fill indexes.
5955   $extension_map{$_} = $lang->name foreach @{$lang->extensions};
5956   $languages{$lang->name} = $lang;
5957   my $link = $lang->linker;
5958   if ($link)
5959     {
5960       if (exists $link_languages{$link})
5961         {
5962           prog_error ("`$link' has different definitions in "
5963                       . $lang->name . " and " . $link_languages{$link}->name)
5964             if $lang->link ne $link_languages{$link}->link;
5965         }
5966       else
5967         {
5968           $link_languages{$link} = $lang;
5969         }
5970     }
5972   # Update the pattern of known extensions.
5973   accept_extensions (@{$lang->extensions});
5975   # Upate the $suffix_rule map.
5976   foreach my $suffix (@{$lang->extensions})
5977     {
5978       foreach my $dest (&{$lang->output_extensions} ($suffix))
5979         {
5980           register_suffix_rule (INTERNAL, $suffix, $dest);
5981         }
5982     }
5985 # derive_suffix ($EXT, $OBJ)
5986 # --------------------------
5987 # This function is used to find a path from a user-specified suffix $EXT
5988 # to $OBJ or to some other suffix we recognize internally, e.g. `cc'.
5989 sub derive_suffix ($$)
5991   my ($source_ext, $obj) = @_;
5993   while (! $extension_map{$source_ext}
5994          && $source_ext ne $obj
5995          && exists $suffix_rules->{$source_ext}
5996          && exists $suffix_rules->{$source_ext}{$obj})
5997     {
5998       $source_ext = $suffix_rules->{$source_ext}{$obj}[0];
5999     }
6001   return $source_ext;
6005 ################################################################
6007 # Pretty-print something and append to output_rules.
6008 sub pretty_print_rule
6010     $output_rules .= &makefile_wrap (@_);
6014 ################################################################
6017 ## -------------------------------- ##
6018 ## Handling the conditional stack.  ##
6019 ## -------------------------------- ##
6022 # $STRING
6023 # make_conditional_string ($NEGATE, $COND)
6024 # ----------------------------------------
6025 sub make_conditional_string ($$)
6027   my ($negate, $cond) = @_;
6028   $cond = "${cond}_TRUE"
6029     unless $cond =~ /^TRUE|FALSE$/;
6030   $cond = Automake::Condition::conditional_negate ($cond)
6031     if $negate;
6032   return $cond;
6036 my %_am_macro_for_cond =
6037   (
6038   AMDEP => "one of the compiler tests\n"
6039            . "    AC_PROG_CC, AC_PROG_CXX, AC_PROG_CXX, AC_PROG_OBJC,\n"
6040            . "    AM_PROG_AS, AM_PROG_GCJ, AM_PROG_UPC",
6041   am__fastdepCC => 'AC_PROG_CC',
6042   am__fastdepCCAS => 'AM_PROG_AS',
6043   am__fastdepCXX => 'AC_PROG_CXX',
6044   am__fastdepGCJ => 'AM_PROG_GCJ',
6045   am__fastdepOBJC => 'AC_PROG_OBJC',
6046   am__fastdepUPC => 'AM_PROG_UPC'
6047   );
6049 # $COND
6050 # cond_stack_if ($NEGATE, $COND, $WHERE)
6051 # --------------------------------------
6052 sub cond_stack_if ($$$)
6054   my ($negate, $cond, $where) = @_;
6056   if (! $configure_cond{$cond} && $cond !~ /^TRUE|FALSE$/)
6057     {
6058       my $text = "$cond does not appear in AM_CONDITIONAL";
6059       my $scope = US_LOCAL;
6060       if (exists $_am_macro_for_cond{$cond})
6061         {
6062           my $mac = $_am_macro_for_cond{$cond};
6063           $text .= "\n  The usual way to define `$cond' is to add ";
6064           $text .= ($mac =~ / /) ? $mac : "`$mac'";
6065           $text .= "\n  to `$configure_ac' and run `aclocal' and `autoconf' again.";
6066           # These warnings appear in Automake files (depend2.am),
6067           # so there is no need to display them more than once:
6068           $scope = US_GLOBAL;
6069         }
6070       error $where, $text, uniq_scope => $scope;
6071     }
6073   push (@cond_stack, make_conditional_string ($negate, $cond));
6075   return new Automake::Condition (@cond_stack);
6079 # $COND
6080 # cond_stack_else ($NEGATE, $COND, $WHERE)
6081 # ----------------------------------------
6082 sub cond_stack_else ($$$)
6084   my ($negate, $cond, $where) = @_;
6086   if (! @cond_stack)
6087     {
6088       error $where, "else without if";
6089       return FALSE;
6090     }
6092   $cond_stack[$#cond_stack] =
6093     Automake::Condition::conditional_negate ($cond_stack[$#cond_stack]);
6095   # If $COND is given, check against it.
6096   if (defined $cond)
6097     {
6098       $cond = make_conditional_string ($negate, $cond);
6100       error ($where, "else reminder ($negate$cond) incompatible with "
6101              . "current conditional: $cond_stack[$#cond_stack]")
6102         if $cond_stack[$#cond_stack] ne $cond;
6103     }
6105   return new Automake::Condition (@cond_stack);
6109 # $COND
6110 # cond_stack_endif ($NEGATE, $COND, $WHERE)
6111 # -----------------------------------------
6112 sub cond_stack_endif ($$$)
6114   my ($negate, $cond, $where) = @_;
6115   my $old_cond;
6117   if (! @cond_stack)
6118     {
6119       error $where, "endif without if";
6120       return TRUE;
6121     }
6123   # If $COND is given, check against it.
6124   if (defined $cond)
6125     {
6126       $cond = make_conditional_string ($negate, $cond);
6128       error ($where, "endif reminder ($negate$cond) incompatible with "
6129              . "current conditional: $cond_stack[$#cond_stack]")
6130         if $cond_stack[$#cond_stack] ne $cond;
6131     }
6133   pop @cond_stack;
6135   return new Automake::Condition (@cond_stack);
6142 ## ------------------------ ##
6143 ## Handling the variables.  ##
6144 ## ------------------------ ##
6147 # &define_pretty_variable ($VAR, $COND, $WHERE, @VALUE)
6148 # -----------------------------------------------------
6149 # Like define_variable, but the value is a list, and the variable may
6150 # be defined conditionally.  The second argument is the condition
6151 # under which the value should be defined; this should be the empty
6152 # string to define the variable unconditionally.  The third argument
6153 # is a list holding the values to use for the variable.  The value is
6154 # pretty printed in the output file.
6155 sub define_pretty_variable ($$$@)
6157     my ($var, $cond, $where, @value) = @_;
6159     if (! vardef ($var, $cond))
6160     {
6161         Automake::Variable::define ($var, VAR_AUTOMAKE, '', $cond, "@value",
6162                                     '', $where, VAR_PRETTY);
6163         rvar ($var)->rdef ($cond)->set_seen;
6164     }
6168 # define_variable ($VAR, $VALUE, $WHERE)
6169 # --------------------------------------
6170 # Define a new Automake Makefile variable VAR to VALUE, but only if
6171 # not already defined.
6172 sub define_variable ($$$)
6174     my ($var, $value, $where) = @_;
6175     define_pretty_variable ($var, TRUE, $where, $value);
6179 # define_files_variable ($VAR, \@BASENAME, $EXTENSION, $WHERE)
6180 # -----------------------------------------------------------
6181 # Define the $VAR which content is the list of file names composed of
6182 # a @BASENAME and the $EXTENSION.
6183 sub define_files_variable ($\@$$)
6185   my ($var, $basename, $extension, $where) = @_;
6186   define_variable ($var,
6187                    join (' ', map { "$_.$extension" } @$basename),
6188                    $where);
6192 # Like define_variable, but define a variable to be the configure
6193 # substitution by the same name.
6194 sub define_configure_variable ($)
6196   my ($var) = @_;
6198   my $pretty = VAR_ASIS;
6199   my $owner = VAR_CONFIGURE;
6201   # Some variables we do not want to output.  For instance it
6202   # would be a bad idea to output `U = @U@` when `@U@` can be
6203   # substituted as `\`.
6204   $pretty = VAR_SILENT if exists $ignored_configure_vars{$var};
6206   # ANSI2KNR is a variable that Automake wants to redefine, so
6207   # it must be owned by Automake.  (It is also used as a proof
6208   # that AM_C_PROTOTYPES has been run, that's why we do not simply
6209   # omit the AC_SUBST.)
6210   $owner = VAR_AUTOMAKE if $var eq 'ANSI2KNR';
6212   Automake::Variable::define ($var, $owner, '', TRUE, subst $var,
6213                               '', $configure_vars{$var}, $pretty);
6217 # define_compiler_variable ($LANG)
6218 # --------------------------------
6219 # Define a compiler variable.  We also handle defining the `LT'
6220 # version of the command when using libtool.
6221 sub define_compiler_variable ($)
6223     my ($lang) = @_;
6225     my ($var, $value) = ($lang->compiler, $lang->compile);
6226     my $libtool_tag = '';
6227     $libtool_tag = '--tag=' . $lang->libtool_tag . ' '
6228       if $lang->libtool_tag && exists $libtool_tags{$lang->libtool_tag};
6229     &define_variable ($var, $value, INTERNAL);
6230     &define_variable ("LT$var",
6231                       "\$(LIBTOOL) $libtool_tag\$(AM_LIBTOOLFLAGS) "
6232                       . "\$(LIBTOOLFLAGS) --mode=compile $value",
6233                       INTERNAL)
6234       if var ('LIBTOOL');
6238 # define_linker_variable ($LANG)
6239 # ------------------------------
6240 # Define linker variables.
6241 sub define_linker_variable ($)
6243     my ($lang) = @_;
6245     my $libtool_tag = '';
6246     $libtool_tag = '--tag=' . $lang->libtool_tag . ' '
6247       if $lang->libtool_tag && exists $libtool_tags{$lang->libtool_tag};
6248     # CCLD = $(CC).
6249     &define_variable ($lang->lder, $lang->ld, INTERNAL);
6250     # CCLINK = $(CCLD) blah blah...
6251     &define_variable ($lang->linker,
6252                       ((var ('LIBTOOL') ?
6253                         "\$(LIBTOOL) $libtool_tag\$(AM_LIBTOOLFLAGS) "
6254                         . "\$(LIBTOOLFLAGS) --mode=link " : '')
6255                        . $lang->link),
6256                       INTERNAL);
6259 sub define_per_target_linker_variable ($$)
6261   my ($linker, $target) = @_;
6263   # If the user wrote a custom link command, we don't define ours.
6264   return "${target}_LINK"
6265     if set_seen "${target}_LINK";
6267   my $xlink = $linker ? $linker : 'LINK';
6269   my $lang = $link_languages{$xlink};
6270   prog_error "Unknown language for linker variable `$xlink'"
6271     unless $lang;
6273   my $link_command = $lang->link;
6274   if (var 'LIBTOOL')
6275     {
6276       my $libtool_tag = '';
6277       $libtool_tag = '--tag=' . $lang->libtool_tag . ' '
6278         if $lang->libtool_tag && exists $libtool_tags{$lang->libtool_tag};
6280       $link_command =
6281         "\$(LIBTOOL) $libtool_tag\$(AM_LIBTOOLFLAGS) \$(LIBTOOLFLAGS) "
6282         . "--mode=link " . $link_command;
6283     }
6285   # Rewrite each occurrence of `AM_$flag' in the link
6286   # command into `${derived}_$flag' if it exists.
6287   my $orig_command = $link_command;
6288   my @flags = (@{$lang->flags}, 'LDFLAGS');
6289   push @flags, 'LIBTOOLFLAGS' if var 'LIBTOOL';
6290   for my $flag (@flags)
6291     {
6292       my $val = "${target}_$flag";
6293       $link_command =~ s/\(AM_$flag\)/\($val\)/
6294         if set_seen ($val);
6295     }
6297   # If the computed command is the same as the generic command, use
6298   # the command linker variable.
6299   return $lang->linker
6300     if $link_command eq $orig_command;
6302   &define_variable ("${target}_LINK", $link_command, INTERNAL);
6303   return "${target}_LINK";
6306 ################################################################
6308 # &check_trailing_slash ($WHERE, $LINE)
6309 # --------------------------------------
6310 # Return 1 iff $LINE ends with a slash.
6311 # Might modify $LINE.
6312 sub check_trailing_slash ($\$)
6314   my ($where, $line) = @_;
6316   # Ignore `##' lines.
6317   return 0 if $$line =~ /$IGNORE_PATTERN/o;
6319   # Catch and fix a common error.
6320   msg "syntax", $where, "whitespace following trailing backslash"
6321     if $$line =~ s/\\\s+\n$/\\\n/;
6323   return $$line =~ /\\$/;
6327 # &read_am_file ($AMFILE, $WHERE)
6328 # -------------------------------
6329 # Read Makefile.am and set up %contents.  Simultaneously copy lines
6330 # from Makefile.am into $output_trailer, or define variables as
6331 # appropriate.  NOTE we put rules in the trailer section.  We want
6332 # user rules to come after our generated stuff.
6333 sub read_am_file ($$)
6335     my ($amfile, $where) = @_;
6337     my $am_file = new Automake::XFile ("< $amfile");
6338     verb "reading $amfile";
6340     # Keep track of the youngest output dependency.
6341     my $mtime = mtime $amfile;
6342     $output_deps_greatest_timestamp = $mtime
6343       if $mtime > $output_deps_greatest_timestamp;
6345     my $spacing = '';
6346     my $comment = '';
6347     my $blank = 0;
6348     my $saw_bk = 0;
6349     my $var_look = VAR_ASIS;
6351     use constant IN_VAR_DEF => 0;
6352     use constant IN_RULE_DEF => 1;
6353     use constant IN_COMMENT => 2;
6354     my $prev_state = IN_RULE_DEF;
6356     while ($_ = $am_file->getline)
6357     {
6358         $where->set ("$amfile:$.");
6359         if (/$IGNORE_PATTERN/o)
6360         {
6361             # Merely delete comments beginning with two hashes.
6362         }
6363         elsif (/$WHITE_PATTERN/o)
6364         {
6365             error $where, "blank line following trailing backslash"
6366               if $saw_bk;
6367             # Stick a single white line before the incoming macro or rule.
6368             $spacing = "\n";
6369             $blank = 1;
6370             # Flush all comments seen so far.
6371             if ($comment ne '')
6372             {
6373                 $output_vars .= $comment;
6374                 $comment = '';
6375             }
6376         }
6377         elsif (/$COMMENT_PATTERN/o)
6378         {
6379             # Stick comments before the incoming macro or rule.  Make
6380             # sure a blank line precedes the first block of comments.
6381             $spacing = "\n" unless $blank;
6382             $blank = 1;
6383             $comment .= $spacing . $_;
6384             $spacing = '';
6385             $prev_state = IN_COMMENT;
6386         }
6387         else
6388         {
6389             last;
6390         }
6391         $saw_bk = check_trailing_slash ($where, $_);
6392     }
6394     # We save the conditional stack on entry, and then check to make
6395     # sure it is the same on exit.  This lets us conditionally include
6396     # other files.
6397     my @saved_cond_stack = @cond_stack;
6398     my $cond = new Automake::Condition (@cond_stack);
6400     my $last_var_name = '';
6401     my $last_var_type = '';
6402     my $last_var_value = '';
6403     my $last_where;
6404     # FIXME: shouldn't use $_ in this loop; it is too big.
6405     while ($_)
6406     {
6407         $where->set ("$amfile:$.");
6409         # Make sure the line is \n-terminated.
6410         chomp;
6411         $_ .= "\n";
6413         # Don't look at MAINTAINER_MODE_TRUE here.  That shouldn't be
6414         # used by users.  @MAINT@ is an anachronism now.
6415         $_ =~ s/\@MAINT\@//g
6416             unless $seen_maint_mode;
6418         my $new_saw_bk = check_trailing_slash ($where, $_);
6420         if (/$IGNORE_PATTERN/o)
6421         {
6422             # Merely delete comments beginning with two hashes.
6424             # Keep any backslash from the previous line.
6425             $new_saw_bk = $saw_bk;
6426         }
6427         elsif (/$WHITE_PATTERN/o)
6428         {
6429             # Stick a single white line before the incoming macro or rule.
6430             $spacing = "\n";
6431             error $where, "blank line following trailing backslash"
6432               if $saw_bk;
6433         }
6434         elsif (/$COMMENT_PATTERN/o)
6435         {
6436             error $where, "comment following trailing backslash"
6437               if $saw_bk && $comment eq '';
6439             # Stick comments before the incoming macro or rule.
6440             $comment .= $spacing . $_;
6441             $spacing = '';
6442             $prev_state = IN_COMMENT;
6443         }
6444         elsif ($saw_bk)
6445         {
6446             if ($prev_state == IN_RULE_DEF)
6447             {
6448               my $cond = new Automake::Condition @cond_stack;
6449               $output_trailer .= $cond->subst_string;
6450               $output_trailer .= $_;
6451             }
6452             elsif ($prev_state == IN_COMMENT)
6453             {
6454                 # If the line doesn't start with a `#', add it.
6455                 # We do this because a continued comment like
6456                 #   # A = foo \
6457                 #         bar \
6458                 #         baz
6459                 # is not portable.  BSD make doesn't honor
6460                 # escaped newlines in comments.
6461                 s/^#?/#/;
6462                 $comment .= $spacing . $_;
6463             }
6464             else # $prev_state == IN_VAR_DEF
6465             {
6466               $last_var_value .= ' '
6467                 unless $last_var_value =~ /\s$/;
6468               $last_var_value .= $_;
6470               if (!/\\$/)
6471                 {
6472                   Automake::Variable::define ($last_var_name, VAR_MAKEFILE,
6473                                               $last_var_type, $cond,
6474                                               $last_var_value, $comment,
6475                                               $last_where, VAR_ASIS)
6476                     if $cond != FALSE;
6477                   $comment = $spacing = '';
6478                 }
6479             }
6480         }
6482         elsif (/$IF_PATTERN/o)
6483           {
6484             $cond = cond_stack_if ($1, $2, $where);
6485           }
6486         elsif (/$ELSE_PATTERN/o)
6487           {
6488             $cond = cond_stack_else ($1, $2, $where);
6489           }
6490         elsif (/$ENDIF_PATTERN/o)
6491           {
6492             $cond = cond_stack_endif ($1, $2, $where);
6493           }
6495         elsif (/$RULE_PATTERN/o)
6496         {
6497             # Found a rule.
6498             $prev_state = IN_RULE_DEF;
6500             # For now we have to output all definitions of user rules
6501             # and can't diagnose duplicates (see the comment in
6502             # Automake::Rule::define). So we go on and ignore the return value.
6503             Automake::Rule::define ($1, $amfile, RULE_USER, $cond, $where);
6505             check_variable_expansions ($_, $where);
6507             $output_trailer .= $comment . $spacing;
6508             my $cond = new Automake::Condition @cond_stack;
6509             $output_trailer .= $cond->subst_string;
6510             $output_trailer .= $_;
6511             $comment = $spacing = '';
6512         }
6513         elsif (/$ASSIGNMENT_PATTERN/o)
6514         {
6515             # Found a macro definition.
6516             $prev_state = IN_VAR_DEF;
6517             $last_var_name = $1;
6518             $last_var_type = $2;
6519             $last_var_value = $3;
6520             $last_where = $where->clone;
6521             if ($3 ne '' && substr ($3, -1) eq "\\")
6522               {
6523                 # We preserve the `\' because otherwise the long lines
6524                 # that are generated will be truncated by broken
6525                 # `sed's.
6526                 $last_var_value = $3 . "\n";
6527               }
6528             # Normally we try to output variable definitions in the
6529             # same format they were input.  However, POSIX compliant
6530             # systems are not required to support lines longer than
6531             # 2048 bytes (most notably, some sed implementation are
6532             # limited to 4000 bytes, and sed is used by config.status
6533             # to rewrite Makefile.in into Makefile).  Moreover nobody
6534             # would really write such long lines by hand since it is
6535             # hardly maintainable.  So if a line is longer that 1000
6536             # bytes (an arbitrary limit), assume it has been
6537             # automatically generated by some tools, and flatten the
6538             # variable definition.  Otherwise, keep the variable as it
6539             # as been input.
6540             $var_look = VAR_PRETTY if length ($last_var_value) >= 1000;
6542             if (!/\\$/)
6543               {
6544                 Automake::Variable::define ($last_var_name, VAR_MAKEFILE,
6545                                             $last_var_type, $cond,
6546                                             $last_var_value, $comment,
6547                                             $last_where, $var_look)
6548                   if $cond != FALSE;
6549                 $comment = $spacing = '';
6550                 $var_look = VAR_ASIS;
6551               }
6552         }
6553         elsif (/$INCLUDE_PATTERN/o)
6554         {
6555             my $path = $1;
6557             if ($path =~ s/^\$\(top_srcdir\)\///)
6558               {
6559                 push (@include_stack, "\$\(top_srcdir\)/$path");
6560                 # Distribute any included file.
6562                 # Always use the $(top_srcdir) prefix in DIST_COMMON,
6563                 # otherwise OSF make will implicitly copy the included
6564                 # file in the build tree during `make distdir' to satisfy
6565                 # the dependency.
6566                 # (subdircond2.test and subdircond3.test will fail.)
6567                 push_dist_common ("\$\(top_srcdir\)/$path");
6568               }
6569             else
6570               {
6571                 $path =~ s/\$\(srcdir\)\///;
6572                 push (@include_stack, "\$\(srcdir\)/$path");
6573                 # Always use the $(srcdir) prefix in DIST_COMMON,
6574                 # otherwise OSF make will implicitly copy the included
6575                 # file in the build tree during `make distdir' to satisfy
6576                 # the dependency.
6577                 # (subdircond2.test and subdircond3.test will fail.)
6578                 push_dist_common ("\$\(srcdir\)/$path");
6579                 $path = $relative_dir . "/" . $path if $relative_dir ne '.';
6580               }
6581             $where->push_context ("`$path' included from here");
6582             &read_am_file ($path, $where);
6583             $where->pop_context;
6584         }
6585         else
6586         {
6587             # This isn't an error; it is probably a continued rule.
6588             # In fact, this is what we assume.
6589             $prev_state = IN_RULE_DEF;
6590             check_variable_expansions ($_, $where);
6591             $output_trailer .= $comment . $spacing;
6592             my $cond = new Automake::Condition @cond_stack;
6593             $output_trailer .= $cond->subst_string;
6594             $output_trailer .= $_;
6595             $comment = $spacing = '';
6596             error $where, "`#' comment at start of rule is unportable"
6597               if $_ =~ /^\t\s*\#/;
6598         }
6600         $saw_bk = $new_saw_bk;
6601         $_ = $am_file->getline;
6602     }
6604     $output_trailer .= $comment;
6606     error ($where, "trailing backslash on last line")
6607       if $saw_bk;
6609     error ($where, (@cond_stack ? "unterminated conditionals: @cond_stack"
6610                     : "too many conditionals closed in include file"))
6611       if "@saved_cond_stack" ne "@cond_stack";
6615 # define_standard_variables ()
6616 # ----------------------------
6617 # A helper for read_main_am_file which initializes configure variables
6618 # and variables from header-vars.am.
6619 sub define_standard_variables
6621   my $saved_output_vars = $output_vars;
6622   my ($comments, undef, $rules) =
6623     file_contents_internal (1, "$libdir/am/header-vars.am",
6624                             new Automake::Location);
6626   foreach my $var (sort keys %configure_vars)
6627     {
6628       &define_configure_variable ($var);
6629     }
6631   $output_vars .= $comments . $rules;
6634 # Read main am file.
6635 sub read_main_am_file
6637     my ($amfile) = @_;
6639     # This supports the strange variable tricks we are about to play.
6640     prog_error (macros_dump () . "variable defined before read_main_am_file")
6641       if (scalar (variables) > 0);
6643     # Generate copyright header for generated Makefile.in.
6644     # We do discard the output of predefined variables, handled below.
6645     $output_vars = ("# $in_file_name generated by automake "
6646                    . $VERSION . " from $am_file_name.\n");
6647     $output_vars .= '# ' . subst ('configure_input') . "\n";
6648     $output_vars .= $gen_copyright;
6650     # We want to predefine as many variables as possible.  This lets
6651     # the user set them with `+=' in Makefile.am.
6652     &define_standard_variables;
6654     # Read user file, which might override some of our values.
6655     &read_am_file ($amfile, new Automake::Location);
6660 ################################################################
6662 # $FLATTENED
6663 # &flatten ($STRING)
6664 # ------------------
6665 # Flatten the $STRING and return the result.
6666 sub flatten
6668   $_ = shift;
6670   s/\\\n//somg;
6671   s/\s+/ /g;
6672   s/^ //;
6673   s/ $//;
6675   return $_;
6679 # transform_token ($TOKEN, \%PAIRS, $KEY)
6680 # =======================================
6681 # Return the value associated to $KEY in %PAIRS, as used on $TOKEN
6682 # (which should be ?KEY? or any of the special %% requests)..
6683 sub transform_token ($$$)
6685   my ($token, $transform, $key) = @_;
6686   my $res = $transform->{$key};
6687   prog_error "Unknown key `$key' in `$token'" unless defined $res;
6688   return $res;
6692 # transform ($TOKEN, \%PAIRS)
6693 # ===========================
6694 # If ($TOKEN, $VAL) is in %PAIRS:
6695 #   - replaces %KEY% with $VAL,
6696 #   - enables/disables ?KEY? and ?!KEY?,
6697 #   - replaces %?KEY% with TRUE or FALSE.
6698 #   - replaces %KEY?IFTRUE%, %KEY:IFFALSE%, and %KEY?IFTRUE:IFFALSE% with
6699 #     IFTRUE / IFFALSE, as appropriate.
6700 sub transform ($$)
6702   my ($token, $transform) = @_;
6704   # %KEY%.
6705   # Must be before the following pattern to exclude the case
6706   # when there is neither IFTRUE nor IFFALSE.
6707   if ($token =~ /^%([\w\-]+)%$/)
6708     {
6709       return transform_token ($token, $transform, $1);
6710     }
6711   # %KEY?IFTRUE%, %KEY:IFFALSE%, and %KEY?IFTRUE:IFFALSE%.
6712   elsif ($token =~ /^%([\w\-]+)(?:\?([^?:%]+))?(?::([^?:%]+))?%$/)
6713     {
6714       return transform_token ($token, $transform, $1) ? ($2 || '') : ($3 || '');
6715     }
6716   # %?KEY%.
6717   elsif ($token =~ /^%\?([\w\-]+)%$/)
6718     {
6719       return transform_token ($token, $transform, $1) ? 'TRUE' : 'FALSE';
6720     }
6721   # ?KEY? and ?!KEY?.
6722   elsif ($token =~ /^ \? (!?) ([\w\-]+) \? $/x)
6723     {
6724       my $neg = ($1 eq '!') ? 1 : 0;
6725       my $val = transform_token ($token, $transform, $2);
6726       return (!!$val == $neg) ? '##%' : '';
6727     }
6728   else
6729     {
6730       prog_error "Unknown request format: $token";
6731     }
6735 # @PARAGRAPHS
6736 # &make_paragraphs ($MAKEFILE, [%TRANSFORM])
6737 # ------------------------------------------
6738 # Load a $MAKEFILE, apply the %TRANSFORM, and return it as a list of
6739 # paragraphs.
6740 sub make_paragraphs ($%)
6742   my ($file, %transform) = @_;
6744   # Complete %transform with global options.
6745   # Note that %transform goes last, so it overrides global options.
6746   %transform = ('CYGNUS'      => !! option 'cygnus',
6747                  'MAINTAINER-MODE'
6748                  => $seen_maint_mode ? subst ('MAINTAINER_MODE_TRUE') : '',
6750                  'XZ'          => !! option 'dist-xz',
6751                  'LZMA'        => !! option 'dist-lzma',
6752                  'BZIP2'       => !! option 'dist-bzip2',
6753                  'COMPRESS'    => !! option 'dist-tarZ',
6754                  'GZIP'        =>  ! option 'no-dist-gzip',
6755                  'SHAR'        => !! option 'dist-shar',
6756                  'ZIP'         => !! option 'dist-zip',
6758                  'INSTALL-INFO' =>  ! option 'no-installinfo',
6759                  'INSTALL-MAN'  =>  ! option 'no-installman',
6760                  'HAVE-MANS'    => !! var ('MANS'),
6761                  'CK-NEWS'      => !! option 'check-news',
6763                  'SUBDIRS'      => !! var ('SUBDIRS'),
6764                  'TOPDIR_P'     => $relative_dir eq '.',
6766                  'BUILD'    => ($seen_canonical >= AC_CANONICAL_BUILD),
6767                  'HOST'     => ($seen_canonical >= AC_CANONICAL_HOST),
6768                  'TARGET'   => ($seen_canonical >= AC_CANONICAL_TARGET),
6770                  'LIBTOOL'      => !! var ('LIBTOOL'),
6771                  'NONLIBTOOL'   => 1,
6772                  'FIRST'        => ! $transformed_files{$file},
6773                 %transform);
6775   $transformed_files{$file} = 1;
6776   $_ = $am_file_cache{$file};
6778   if (! defined $_)
6779     {
6780       verb "reading $file";
6781       # Swallow the whole file.
6782       my $fc_file = new Automake::XFile "< $file";
6783       my $saved_dollar_slash = $/;
6784       undef $/;
6785       $_ = $fc_file->getline;
6786       $/ = $saved_dollar_slash;
6787       $fc_file->close;
6789       # Remove ##-comments.
6790       # Besides we don't need more than two consecutive new-lines.
6791       s/(?:$IGNORE_PATTERN|(?<=\n\n)\n+)//gom;
6793       $am_file_cache{$file} = $_;
6794     }
6796   # Substitute Automake template tokens.
6797   s/(?: % \?? [\w\-]+ %
6798       | % [\w\-]+ (?:\?[^?:%]+)? (?::[^?:%]+)? %
6799       | \? !? [\w\-]+ \?
6800     )/transform($&, \%transform)/gex;
6801   # transform() may have added some ##%-comments to strip.
6802   # (we use `##%' instead of `##' so we can distinguish ##%##%##% from
6803   # ####### and do not remove the latter.)
6804   s/^[ \t]*(?:##%)+.*\n//gm;
6806   # Split at unescaped new lines.
6807   my @lines = split (/(?<!\\)\n/, $_);
6808   my @res;
6810   while (defined ($_ = shift @lines))
6811     {
6812       my $paragraph = $_;
6813       # If we are a rule, eat as long as we start with a tab.
6814       if (/$RULE_PATTERN/smo)
6815         {
6816           while (defined ($_ = shift @lines) && $_ =~ /^\t/)
6817             {
6818               $paragraph .= "\n$_";
6819             }
6820           unshift (@lines, $_);
6821         }
6823       # If we are a comments, eat as much comments as you can.
6824       elsif (/$COMMENT_PATTERN/smo)
6825         {
6826           while (defined ($_ = shift @lines)
6827                  && $_ =~ /$COMMENT_PATTERN/smo)
6828             {
6829               $paragraph .= "\n$_";
6830             }
6831           unshift (@lines, $_);
6832         }
6834       push @res, $paragraph;
6835     }
6837   return @res;
6842 # ($COMMENT, $VARIABLES, $RULES)
6843 # &file_contents_internal ($IS_AM, $FILE, $WHERE, [%TRANSFORM])
6844 # -------------------------------------------------------------
6845 # Return contents of a file from $libdir/am, automatically skipping
6846 # macros or rules which are already known. $IS_AM iff the caller is
6847 # reading an Automake file (as opposed to the user's Makefile.am).
6848 sub file_contents_internal ($$$%)
6850     my ($is_am, $file, $where, %transform) = @_;
6852     $where->set ($file);
6854     my $result_vars = '';
6855     my $result_rules = '';
6856     my $comment = '';
6857     my $spacing = '';
6859     # The following flags are used to track rules spanning across
6860     # multiple paragraphs.
6861     my $is_rule = 0;            # 1 if we are processing a rule.
6862     my $discard_rule = 0;       # 1 if the current rule should not be output.
6864     # We save the conditional stack on entry, and then check to make
6865     # sure it is the same on exit.  This lets us conditionally include
6866     # other files.
6867     my @saved_cond_stack = @cond_stack;
6868     my $cond = new Automake::Condition (@cond_stack);
6870     foreach (make_paragraphs ($file, %transform))
6871     {
6872         # FIXME: no line number available.
6873         $where->set ($file);
6875         # Sanity checks.
6876         error $where, "blank line following trailing backslash:\n$_"
6877           if /\\$/;
6878         error $where, "comment following trailing backslash:\n$_"
6879           if /\\#/;
6881         if (/^$/)
6882         {
6883             $is_rule = 0;
6884             # Stick empty line before the incoming macro or rule.
6885             $spacing = "\n";
6886         }
6887         elsif (/$COMMENT_PATTERN/mso)
6888         {
6889             $is_rule = 0;
6890             # Stick comments before the incoming macro or rule.
6891             $comment = "$_\n";
6892         }
6894         # Handle inclusion of other files.
6895         elsif (/$INCLUDE_PATTERN/o)
6896         {
6897             if ($cond != FALSE)
6898               {
6899                 my $file = ($is_am ? "$libdir/am/" : '') . $1;
6900                 $where->push_context ("`$file' included from here");
6901                 # N-ary `.=' fails.
6902                 my ($com, $vars, $rules)
6903                   = file_contents_internal ($is_am, $file, $where, %transform);
6904                 $where->pop_context;
6905                 $comment .= $com;
6906                 $result_vars .= $vars;
6907                 $result_rules .= $rules;
6908               }
6909         }
6911         # Handling the conditionals.
6912         elsif (/$IF_PATTERN/o)
6913           {
6914             $cond = cond_stack_if ($1, $2, $file);
6915           }
6916         elsif (/$ELSE_PATTERN/o)
6917           {
6918             $cond = cond_stack_else ($1, $2, $file);
6919           }
6920         elsif (/$ENDIF_PATTERN/o)
6921           {
6922             $cond = cond_stack_endif ($1, $2, $file);
6923           }
6925         # Handling rules.
6926         elsif (/$RULE_PATTERN/mso)
6927         {
6928           $is_rule = 1;
6929           $discard_rule = 0;
6930           # Separate relationship from optional actions: the first
6931           # `new-line tab" not preceded by backslash (continuation
6932           # line).
6933           my $paragraph = $_;
6934           /^(.*?)(?:(?<!\\)\n(\t.*))?$/s;
6935           my ($relationship, $actions) = ($1, $2 || '');
6937           # Separate targets from dependencies: the first colon.
6938           $relationship =~ /^([^:]+\S+) *: *(.*)$/som;
6939           my ($targets, $dependencies) = ($1, $2);
6940           # Remove the escaped new lines.
6941           # I don't know why, but I have to use a tmp $flat_deps.
6942           my $flat_deps = &flatten ($dependencies);
6943           my @deps = split (' ', $flat_deps);
6945           foreach (split (' ', $targets))
6946             {
6947               # FIXME: 1. We are not robust to people defining several targets
6948               # at once, only some of them being in %dependencies.  The
6949               # actions from the targets in %dependencies are usually generated
6950               # from the content of %actions, but if some targets in $targets
6951               # are not in %dependencies the ELSE branch will output
6952               # a rule for all $targets (i.e. the targets which are both
6953               # in %dependencies and $targets will have two rules).
6955               # FIXME: 2. The logic here is not able to output a
6956               # multi-paragraph rule several time (e.g. for each condition
6957               # it is defined for) because it only knows the first paragraph.
6959               # FIXME: 3. We are not robust to people defining a subset
6960               # of a previously defined "multiple-target" rule.  E.g.
6961               # `foo:' after `foo bar:'.
6963               # Output only if not in FALSE.
6964               if (defined $dependencies{$_} && $cond != FALSE)
6965                 {
6966                   &depend ($_, @deps);
6967                   register_action ($_, $actions);
6968                 }
6969               else
6970                 {
6971                   # Free-lance dependency.  Output the rule for all the
6972                   # targets instead of one by one.
6973                   my @undefined_conds =
6974                     Automake::Rule::define ($targets, $file,
6975                                             $is_am ? RULE_AUTOMAKE : RULE_USER,
6976                                             $cond, $where);
6977                   for my $undefined_cond (@undefined_conds)
6978                     {
6979                       my $condparagraph = $paragraph;
6980                       $condparagraph =~ s/^/$undefined_cond->subst_string/gme;
6981                       $result_rules .= "$spacing$comment$condparagraph\n";
6982                     }
6983                   if (scalar @undefined_conds == 0)
6984                     {
6985                       # Remember to discard next paragraphs
6986                       # if they belong to this rule.
6987                       # (but see also FIXME: #2 above.)
6988                       $discard_rule = 1;
6989                     }
6990                   $comment = $spacing = '';
6991                   last;
6992                 }
6993             }
6994         }
6996         elsif (/$ASSIGNMENT_PATTERN/mso)
6997         {
6998             my ($var, $type, $val) = ($1, $2, $3);
6999             error $where, "variable `$var' with trailing backslash"
7000               if /\\$/;
7002             $is_rule = 0;
7004             Automake::Variable::define ($var,
7005                                         $is_am ? VAR_AUTOMAKE : VAR_MAKEFILE,
7006                                         $type, $cond, $val, $comment, $where,
7007                                         VAR_ASIS)
7008               if $cond != FALSE;
7010             $comment = $spacing = '';
7011         }
7012         else
7013         {
7014             # This isn't an error; it is probably some tokens which
7015             # configure is supposed to replace, such as `@SET-MAKE@',
7016             # or some part of a rule cut by an if/endif.
7017             if (! $cond->false && ! ($is_rule && $discard_rule))
7018               {
7019                 s/^/$cond->subst_string/gme;
7020                 $result_rules .= "$spacing$comment$_\n";
7021               }
7022             $comment = $spacing = '';
7023         }
7024     }
7026     error ($where, @cond_stack ?
7027            "unterminated conditionals: @cond_stack" :
7028            "too many conditionals closed in include file")
7029       if "@saved_cond_stack" ne "@cond_stack";
7031     return ($comment, $result_vars, $result_rules);
7035 # $CONTENTS
7036 # &file_contents ($BASENAME, $WHERE, [%TRANSFORM])
7037 # ------------------------------------------------
7038 # Return contents of a file from $libdir/am, automatically skipping
7039 # macros or rules which are already known.
7040 sub file_contents ($$%)
7042     my ($basename, $where, %transform) = @_;
7043     my ($comments, $variables, $rules) =
7044       file_contents_internal (1, "$libdir/am/$basename.am", $where,
7045                               %transform);
7046     return "$comments$variables$rules";
7050 # @PREFIX
7051 # &am_primary_prefixes ($PRIMARY, $CAN_DIST, @PREFIXES)
7052 # -----------------------------------------------------
7053 # Find all variable prefixes that are used for install directories.  A
7054 # prefix `zar' qualifies iff:
7056 # * `zardir' is a variable.
7057 # * `zar_PRIMARY' is a variable.
7059 # As a side effect, it looks for misspellings.  It is an error to have
7060 # a variable ending in a "reserved" suffix whose prefix is unknown, e.g.
7061 # "bni_PROGRAMS".  However, unusual prefixes are allowed if a variable
7062 # of the same name (with "dir" appended) exists.  For instance, if the
7063 # variable "zardir" is defined, then "zar_PROGRAMS" becomes valid.
7064 # This is to provide a little extra flexibility in those cases which
7065 # need it.
7066 sub am_primary_prefixes ($$@)
7068   my ($primary, $can_dist, @prefixes) = @_;
7070   local $_;
7071   my %valid = map { $_ => 0 } @prefixes;
7072   $valid{'EXTRA'} = 0;
7073   foreach my $var (variables $primary)
7074     {
7075       # Automake is allowed to define variables that look like primaries
7076       # but which aren't.  E.g. INSTALL_sh_DATA.
7077       # Autoconf can also define variables like INSTALL_DATA, so
7078       # ignore all configure variables (at least those which are not
7079       # redefined in Makefile.am).
7080       # FIXME: We should make sure that these variables are not
7081       # conditionally defined (or else adjust the condition below).
7082       my $def = $var->def (TRUE);
7083       next if $def && $def->owner != VAR_MAKEFILE;
7085       my $varname = $var->name;
7087       if ($varname =~ /^(nobase_)?(dist_|nodist_)?(.*)_[[:alnum:]]+$/)
7088         {
7089           my ($base, $dist, $X) = ($1 || '', $2 || '', $3 || '');
7090           if ($dist ne '' && ! $can_dist)
7091             {
7092               err_var ($var,
7093                        "invalid variable `$varname': `dist' is forbidden");
7094             }
7095           # Standard directories must be explicitly allowed.
7096           elsif (! defined $valid{$X} && exists $standard_prefix{$X})
7097             {
7098               err_var ($var,
7099                        "`${X}dir' is not a legitimate directory " .
7100                        "for `$primary'");
7101             }
7102           # A not explicitly valid directory is allowed if Xdir is defined.
7103           elsif (! defined $valid{$X} &&
7104                  $var->requires_variables ("`$varname' is used", "${X}dir"))
7105             {
7106               # Nothing to do.  Any error message has been output
7107               # by $var->requires_variables.
7108             }
7109           else
7110             {
7111               # Ensure all extended prefixes are actually used.
7112               $valid{"$base$dist$X"} = 1;
7113             }
7114         }
7115       else
7116         {
7117           prog_error "unexpected variable name: $varname";
7118         }
7119     }
7121   # Return only those which are actually defined.
7122   return sort grep { var ($_ . '_' . $primary) } keys %valid;
7126 # Handle `where_HOW' variable magic.  Does all lookups, generates
7127 # install code, and possibly generates code to define the primary
7128 # variable.  The first argument is the name of the .am file to munge,
7129 # the second argument is the primary variable (e.g. HEADERS), and all
7130 # subsequent arguments are possible installation locations.
7132 # Returns list of [$location, $value] pairs, where
7133 # $value's are the values in all where_HOW variable, and $location
7134 # there associated location (the place here their parent variables were
7135 # defined).
7137 # FIXME: this should be rewritten to be cleaner.  It should be broken
7138 # up into multiple functions.
7140 # Usage is: am_install_var (OPTION..., file, HOW, where...)
7141 sub am_install_var
7143   my (@args) = @_;
7145   my $do_require = 1;
7146   my $can_dist = 0;
7147   my $default_dist = 0;
7148   while (@args)
7149     {
7150       if ($args[0] eq '-noextra')
7151         {
7152           $do_require = 0;
7153         }
7154       elsif ($args[0] eq '-candist')
7155         {
7156           $can_dist = 1;
7157         }
7158       elsif ($args[0] eq '-defaultdist')
7159         {
7160           $default_dist = 1;
7161           $can_dist = 1;
7162         }
7163       elsif ($args[0] !~ /^-/)
7164         {
7165           last;
7166         }
7167       shift (@args);
7168     }
7170   my ($file, $primary, @prefix) = @args;
7172   # Now that configure substitutions are allowed in where_HOW
7173   # variables, it is an error to actually define the primary.  We
7174   # allow `JAVA', as it is customarily used to mean the Java
7175   # interpreter.  This is but one of several Java hacks.  Similarly,
7176   # `PYTHON' is customarily used to mean the Python interpreter.
7177   reject_var $primary, "`$primary' is an anachronism"
7178     unless $primary eq 'JAVA' || $primary eq 'PYTHON';
7180   # Get the prefixes which are valid and actually used.
7181   @prefix = am_primary_prefixes ($primary, $can_dist, @prefix);
7183   # If a primary includes a configure substitution, then the EXTRA_
7184   # form is required.  Otherwise we can't properly do our job.
7185   my $require_extra;
7187   my @used = ();
7188   my @result = ();
7190   foreach my $X (@prefix)
7191     {
7192       my $nodir_name = $X;
7193       my $one_name = $X . '_' . $primary;
7194       my $one_var = var $one_name;
7196       my $strip_subdir = 1;
7197       # If subdir prefix should be preserved, do so.
7198       if ($nodir_name =~ /^nobase_/)
7199         {
7200           $strip_subdir = 0;
7201           $nodir_name =~ s/^nobase_//;
7202         }
7204       # If files should be distributed, do so.
7205       my $dist_p = 0;
7206       if ($can_dist)
7207         {
7208           $dist_p = (($default_dist && $nodir_name !~ /^nodist_/)
7209                      || (! $default_dist && $nodir_name =~ /^dist_/));
7210           $nodir_name =~ s/^(dist|nodist)_//;
7211         }
7214       # Use the location of the currently processed variable.
7215       # We are not processing a particular condition, so pick the first
7216       # available.
7217       my $tmpcond = $one_var->conditions->one_cond;
7218       my $where = $one_var->rdef ($tmpcond)->location->clone;
7220       # Append actual contents of where_PRIMARY variable to
7221       # @result, skipping @substitutions@.
7222       foreach my $locvals ($one_var->value_as_list_recursive (location => 1))
7223         {
7224           my ($loc, $value) = @$locvals;
7225           # Skip configure substitutions.
7226           if ($value =~ /^\@.*\@$/)
7227             {
7228               if ($nodir_name eq 'EXTRA')
7229                 {
7230                   error ($where,
7231                          "`$one_name' contains configure substitution, "
7232                          . "but shouldn't");
7233                 }
7234               # Check here to make sure variables defined in
7235               # configure.ac do not imply that EXTRA_PRIMARY
7236               # must be defined.
7237               elsif (! defined $configure_vars{$one_name})
7238                 {
7239                   $require_extra = $one_name
7240                     if $do_require;
7241                 }
7242             }
7243           else
7244             {
7245               push (@result, $locvals);
7246             }
7247         }
7248       # A blatant hack: we rewrite each _PROGRAMS primary to include
7249       # EXEEXT.
7250       append_exeext { 1 } $one_name
7251         if $primary eq 'PROGRAMS';
7252       # "EXTRA" shouldn't be used when generating clean targets,
7253       # all, or install targets.  We used to warn if EXTRA_FOO was
7254       # defined uselessly, but this was annoying.
7255       next
7256         if $nodir_name eq 'EXTRA';
7258       if ($nodir_name eq 'check')
7259         {
7260           push (@check, '$(' . $one_name . ')');
7261         }
7262       else
7263         {
7264           push (@used, '$(' . $one_name . ')');
7265         }
7267       # Is this to be installed?
7268       my $install_p = $nodir_name ne 'noinst' && $nodir_name ne 'check';
7270       # If so, with install-exec? (or install-data?).
7271       my $exec_p = ($nodir_name =~ /$EXEC_DIR_PATTERN/o);
7273       my $check_options_p = $install_p && !! option 'std-options';
7275       # Use the location of the currently processed variable as context.
7276       $where->push_context ("while processing `$one_name'");
7278       # The variable containing all files to distribute.
7279       my $distvar = "\$($one_name)";
7280       $distvar = shadow_unconditionally ($one_name, $where)
7281         if ($dist_p && $one_var->has_conditional_contents);
7283       # Singular form of $PRIMARY.
7284       (my $one_primary = $primary) =~ s/S$//;
7285       $output_rules .= &file_contents ($file, $where,
7286                                        PRIMARY     => $primary,
7287                                        ONE_PRIMARY => $one_primary,
7288                                        DIR         => $X,
7289                                        NDIR        => $nodir_name,
7290                                        BASE        => $strip_subdir,
7292                                        EXEC      => $exec_p,
7293                                        INSTALL   => $install_p,
7294                                        DIST      => $dist_p,
7295                                        DISTVAR   => $distvar,
7296                                        'CK-OPTS' => $check_options_p);
7297     }
7299   # The JAVA variable is used as the name of the Java interpreter.
7300   # The PYTHON variable is used as the name of the Python interpreter.
7301   if (@used && $primary ne 'JAVA' && $primary ne 'PYTHON')
7302     {
7303       # Define it.
7304       define_pretty_variable ($primary, TRUE, INTERNAL, @used);
7305       $output_vars .= "\n";
7306     }
7308   err_var ($require_extra,
7309            "`$require_extra' contains configure substitution,\n"
7310            . "but `EXTRA_$primary' not defined")
7311     if ($require_extra && ! var ('EXTRA_' . $primary));
7313   # Push here because PRIMARY might be configure time determined.
7314   push (@all, '$(' . $primary . ')')
7315     if @used && $primary ne 'JAVA' && $primary ne 'PYTHON';
7317   # Make the result unique.  This lets the user use conditionals in
7318   # a natural way, but still lets us program lazily -- we don't have
7319   # to worry about handling a particular object more than once.
7320   # We will keep only one location per object.
7321   my %result = ();
7322   for my $pair (@result)
7323     {
7324       my ($loc, $val) = @$pair;
7325       $result{$val} = $loc;
7326     }
7327   my @l = sort keys %result;
7328   return map { [$result{$_}->clone, $_] } @l;
7332 ################################################################
7334 # Each key in this hash is the name of a directory holding a
7335 # Makefile.in.  These variables are local to `is_make_dir'.
7336 my %make_dirs = ();
7337 my $make_dirs_set = 0;
7339 sub is_make_dir
7341     my ($dir) = @_;
7342     if (! $make_dirs_set)
7343     {
7344         foreach my $iter (@configure_input_files)
7345         {
7346             $make_dirs{dirname ($iter)} = 1;
7347         }
7348         # We also want to notice Makefile.in's.
7349         foreach my $iter (@other_input_files)
7350         {
7351             if ($iter =~ /Makefile\.in$/)
7352             {
7353                 $make_dirs{dirname ($iter)} = 1;
7354             }
7355         }
7356         $make_dirs_set = 1;
7357     }
7358     return defined $make_dirs{$dir};
7361 ################################################################
7363 # Find the aux dir.  This should match the algorithm used by
7364 # ./configure. (See the Autoconf documentation for for
7365 # AC_CONFIG_AUX_DIR.)
7366 sub locate_aux_dir ()
7368   if (! $config_aux_dir_set_in_configure_ac)
7369     {
7370       # The default auxiliary directory is the first
7371       # of ., .., or ../.. that contains install-sh.
7372       # Assume . if install-sh doesn't exist yet.
7373       for my $dir (qw (. .. ../..))
7374         {
7375           if (-f "$dir/install-sh")
7376             {
7377               $config_aux_dir = $dir;
7378               last;
7379             }
7380         }
7381       $config_aux_dir = '.' unless $config_aux_dir;
7382     }
7383   # Avoid unsightly '/.'s.
7384   $am_config_aux_dir =
7385     '$(top_srcdir)' . ($config_aux_dir eq '.' ? "" : "/$config_aux_dir");
7386   $am_config_aux_dir =~ s,/*$,,;
7390 # &maybe_push_required_file ($DIR, $FILE, $FULLFILE)
7391 # --------------------------------------------------
7392 # See if we want to push this file onto dist_common.  This function
7393 # encodes the rules for deciding when to do so.
7394 sub maybe_push_required_file
7396   my ($dir, $file, $fullfile) = @_;
7398   if ($dir eq $relative_dir)
7399     {
7400       push_dist_common ($file);
7401       return 1;
7402     }
7403   elsif ($relative_dir eq '.' && ! &is_make_dir ($dir))
7404     {
7405       # If we are doing the topmost directory, and the file is in a
7406       # subdir which does not have a Makefile, then we distribute it
7407       # here.
7409       # If a required file is above the source tree, it is important
7410       # to prefix it with `$(srcdir)' so that no VPATH search is
7411       # performed.  Otherwise problems occur with Make implementations
7412       # that rewrite and simplify rules whose dependencies are found in a
7413       # VPATH location.  Here is an example with OSF1/Tru64 Make.
7414       #
7415       #   % cat Makefile
7416       #   VPATH = sub
7417       #   distdir: ../a
7418       #           echo ../a
7419       #   % ls
7420       #   Makefile a
7421       #   % make
7422       #   echo a
7423       #   a
7424       #
7425       # Dependency `../a' was found in `sub/../a', but this make
7426       # implementation simplified it as `a'.  (Note that the sub/
7427       # directory does not even exist.)
7428       #
7429       # This kind of VPATH rewriting seems hard to cancel.  The
7430       # distdir.am hack against VPATH rewriting works only when no
7431       # simplification is done, i.e., for dependencies which are in
7432       # subdirectories, not in enclosing directories.  Hence, in
7433       # the latter case we use a full path to make sure no VPATH
7434       # search occurs.
7435       $fullfile = '$(srcdir)/' . $fullfile
7436         if $dir =~ m,^\.\.(?:$|/),;
7438       push_dist_common ($fullfile);
7439       return 1;
7440     }
7441   return 0;
7445 # If a file name appears as a key in this hash, then it has already
7446 # been checked for.  This allows us not to report the same error more
7447 # than once.
7448 my %required_file_not_found = ();
7450 # &require_file_internal ($WHERE, $MYSTRICT, $DIRECTORY, @FILES)
7451 # --------------------------------------------------------------
7452 # Verify that the file must exist in $DIRECTORY, or install it.
7453 # $MYSTRICT is the strictness level at which this file becomes required.
7454 sub require_file_internal ($$$@)
7456   my ($where, $mystrict, $dir, @files) = @_;
7458   foreach my $file (@files)
7459     {
7460       my $fullfile = "$dir/$file";
7461       my $found_it = 0;
7462       my $dangling_sym = 0;
7464       if (-l $fullfile && ! -f $fullfile)
7465         {
7466           $dangling_sym = 1;
7467         }
7468       elsif (dir_has_case_matching_file ($dir, $file))
7469         {
7470           $found_it = 1;
7471           maybe_push_required_file ($dir, $file, $fullfile);
7472         }
7474       # `--force-missing' only has an effect if `--add-missing' is
7475       # specified.
7476       if ($found_it && (! $add_missing || ! $force_missing))
7477         {
7478           next;
7479         }
7480       else
7481         {
7482           # If we've already looked for it, we're done.  You might
7483           # wonder why we don't do this before searching for the
7484           # file.  If we do that, then something like
7485           # AC_OUTPUT(subdir/foo foo) will fail to put foo.in into
7486           # DIST_COMMON.
7487           if (! $found_it)
7488             {
7489               next if defined $required_file_not_found{$fullfile};
7490               $required_file_not_found{$fullfile} = 1;
7491             }
7493           if ($strictness >= $mystrict)
7494             {
7495               if ($dangling_sym && $add_missing)
7496                 {
7497                   unlink ($fullfile);
7498                 }
7500               my $trailer = '';
7501               my $trailer2 = '';
7502               my $suppress = 0;
7504               # Only install missing files according to our desired
7505               # strictness level.
7506               my $message = "required file `$fullfile' not found";
7507               if ($add_missing)
7508                 {
7509                   if (-f "$libdir/$file")
7510                     {
7511                       $suppress = 1;
7513                       # Install the missing file.  Symlink if we
7514                       # can, copy if we must.  Note: delete the file
7515                       # first, in case it is a dangling symlink.
7516                       $message = "installing `$fullfile'";
7518                       # The license file should not be volatile.
7519                       if ($file eq "COPYING")
7520                         {
7521                           $message .= " using GNU General Public License v3 file";
7522                           $trailer2 = "\n    Consider adding the COPYING file"
7523                                     . " to the version control system"
7524                                     . "\n    for your code, to avoid questions"
7525                                     . " about which license your project uses.";
7526                         }
7528                       # Windows Perl will hang if we try to delete a
7529                       # file that doesn't exist.
7530                       unlink ($fullfile) if -f $fullfile;
7531                       if ($symlink_exists && ! $copy_missing)
7532                         {
7533                           if (! symlink ("$libdir/$file", $fullfile))
7534                             {
7535                               $suppress = 0;
7536                               $trailer = "; error while making link: $!";
7537                             }
7538                         }
7539                       elsif (system ('cp', "$libdir/$file", $fullfile))
7540                         {
7541                           $suppress = 0;
7542                           $trailer = "\n    error while copying";
7543                         }
7544                       set_dir_cache_file ($dir, $file);
7545                     }
7547                   if (! maybe_push_required_file (dirname ($fullfile),
7548                                                   $file, $fullfile))
7549                     {
7550                       if (! $found_it && ! $automake_will_process_aux_dir)
7551                         {
7552                           # We have added the file but could not push it
7553                           # into DIST_COMMON, probably because this is
7554                           # an auxiliary file and we are not processing
7555                           # the top level Makefile.  Furthermore Automake
7556                           # hasn't been asked to create the Makefile.in
7557                           # that distributes the aux dir files.
7558                           error ($where, 'Please make a full run of automake'
7559                                  . " so $fullfile gets distributed.");
7560                         }
7561                     }
7562                 }
7563               else
7564                 {
7565                   $trailer = "\n  `automake --add-missing' can install `$file'"
7566                     if -f "$libdir/$file";
7567                 }
7569               # If --force-missing was specified, and we have
7570               # actually found the file, then do nothing.
7571               next
7572                 if $found_it && $force_missing;
7574               # If we couldn't install the file, but it is a target in
7575               # the Makefile, don't print anything.  This allows files
7576               # like README, AUTHORS, or THANKS to be generated.
7577               next
7578                 if !$suppress && rule $file;
7580               msg ($suppress ? 'note' : 'error', $where, "$message$trailer$trailer2");
7581             }
7582         }
7583     }
7586 # &require_file ($WHERE, $MYSTRICT, @FILES)
7587 # -----------------------------------------
7588 sub require_file ($$@)
7590     my ($where, $mystrict, @files) = @_;
7591     require_file_internal ($where, $mystrict, $relative_dir, @files);
7594 # &require_file_with_macro ($COND, $MACRO, $MYSTRICT, @FILES)
7595 # -----------------------------------------------------------
7596 sub require_file_with_macro ($$$@)
7598     my ($cond, $macro, $mystrict, @files) = @_;
7599     $macro = rvar ($macro) unless ref $macro;
7600     require_file ($macro->rdef ($cond)->location, $mystrict, @files);
7603 # &require_libsource_with_macro ($COND, $MACRO, $MYSTRICT, @FILES)
7604 # ----------------------------------------------------------------
7605 # Require an AC_LIBSOURCEd file.  If AC_CONFIG_LIBOBJ_DIR was called, it
7606 # must be in that directory.  Otherwise expect it in the current directory.
7607 sub require_libsource_with_macro ($$$@)
7609     my ($cond, $macro, $mystrict, @files) = @_;
7610     $macro = rvar ($macro) unless ref $macro;
7611     if ($config_libobj_dir)
7612       {
7613         require_file_internal ($macro->rdef ($cond)->location, $mystrict,
7614                                $config_libobj_dir, @files);
7615       }
7616     else
7617       {
7618         require_file ($macro->rdef ($cond)->location, $mystrict, @files);
7619       }
7622 # Queue to push require_conf_file requirements to.
7623 my $required_conf_file_queue;
7625 # &queue_required_conf_file ($QUEUE, $KEY, $DIR, $WHERE, $MYSTRICT, @FILES)
7626 # -------------------------------------------------------------------------
7627 sub queue_required_conf_file ($$$$@)
7629     my ($queue, $key, $dir, $where, $mystrict, @files) = @_;
7630     my @serial_loc;
7631     if (ref $where)
7632       {
7633         @serial_loc = (QUEUE_LOCATION, $where->serialize ());
7634       }
7635     else
7636       {
7637         @serial_loc = (QUEUE_STRING, $where);
7638       }
7639     $queue->enqueue ($key, $dir, @serial_loc, $mystrict, 0 + @files, @files);
7642 # &require_queued_conf_file ($QUEUE)
7643 # ----------------------------------
7644 sub require_queued_conf_file ($)
7646     my ($queue) = @_;
7647     my $where;
7648     my $dir = $queue->dequeue ();
7649     my $loc_key = $queue->dequeue ();
7650     if ($loc_key eq QUEUE_LOCATION)
7651       {
7652         $where = Automake::Location::deserialize ($queue);
7653       }
7654     elsif ($loc_key eq QUEUE_STRING)
7655       {
7656         $where = $queue->dequeue ();
7657       }
7658     else
7659       {
7660         prog_error "unexpected key $loc_key";
7661       }
7662     my $mystrict = $queue->dequeue ();
7663     my $nfiles = $queue->dequeue ();
7664     my @files;
7665     push @files, $queue->dequeue ()
7666       foreach (1 .. $nfiles);
7668     # Dequeuing happens outside of per-makefile context, so we have to
7669     # set the variables used by require_file_internal and the functions
7670     # it calls.  Gross!
7671     $relative_dir = $dir;
7672     require_file_internal ($where, $mystrict, $config_aux_dir, @files);
7675 # &require_conf_file ($WHERE, $MYSTRICT, @FILES)
7676 # ----------------------------------------------
7677 # Looks in configuration path, as specified by AC_CONFIG_AUX_DIR;
7678 # worker threads may queue up the action to be serialized by the master.
7680 # FIXME: this seriously relies on the semantics of require_file_internal
7681 # and maybe_push_required_file, in that we exploit the fact that only the
7682 # contents of the last handled output file may be impacted (which in turn
7683 # is dealt with by the master thread).
7684 sub require_conf_file ($$@)
7686     my ($where, $mystrict, @files) = @_;
7687     if (defined $required_conf_file_queue)
7688       {
7689         queue_required_conf_file ($required_conf_file_queue, QUEUE_CONF_FILE,
7690                                   $relative_dir, $where, $mystrict, @files);
7691       }
7692     else
7693       {
7694         require_file_internal ($where, $mystrict, $config_aux_dir, @files);
7695       }
7699 # &require_conf_file_with_macro ($COND, $MACRO, $MYSTRICT, @FILES)
7700 # ----------------------------------------------------------------
7701 sub require_conf_file_with_macro ($$$@)
7703     my ($cond, $macro, $mystrict, @files) = @_;
7704     require_conf_file (rvar ($macro)->rdef ($cond)->location,
7705                        $mystrict, @files);
7708 ################################################################
7710 # &require_build_directory ($DIRECTORY)
7711 # ------------------------------------
7712 # Emit rules to create $DIRECTORY if needed, and return
7713 # the file that any target requiring this directory should be made
7714 # dependent upon.
7715 # We don't want to emit the rule twice, and want to reuse it
7716 # for directories with equivalent names (e.g., `foo/bar' and `./foo//bar').
7717 sub require_build_directory ($)
7719   my $directory = shift;
7721   return $directory_map{$directory} if exists $directory_map{$directory};
7723   my $cdir = File::Spec->canonpath ($directory);
7725   if (exists $directory_map{$cdir})
7726     {
7727       my $stamp = $directory_map{$cdir};
7728       $directory_map{$directory} = $stamp;
7729       return $stamp;
7730     }
7732   my $dirstamp = "$cdir/\$(am__dirstamp)";
7734   $directory_map{$directory} = $dirstamp;
7735   $directory_map{$cdir} = $dirstamp;
7737   # Set a variable for the dirstamp basename.
7738   define_pretty_variable ('am__dirstamp', TRUE, INTERNAL,
7739                           '$(am__leading_dot)dirstamp');
7741   # Directory must be removed by `make distclean'.
7742   $clean_files{$dirstamp} = DIST_CLEAN;
7744   $output_rules .= ("$dirstamp:\n"
7745                     . "\t\@\$(MKDIR_P) $directory\n"
7746                     . "\t\@: > $dirstamp\n");
7748   return $dirstamp;
7751 # &require_build_directory_maybe ($FILE)
7752 # --------------------------------------
7753 # If $FILE lies in a subdirectory, emit a rule to create this
7754 # directory and return the file that $FILE should be made
7755 # dependent upon.  Otherwise, just return the empty string.
7756 sub require_build_directory_maybe ($)
7758     my $file = shift;
7759     my $directory = dirname ($file);
7761     if ($directory ne '.')
7762     {
7763         return require_build_directory ($directory);
7764     }
7765     else
7766     {
7767         return '';
7768     }
7771 ################################################################
7773 # Push a list of files onto dist_common.
7774 sub push_dist_common
7776   prog_error "push_dist_common run after handle_dist"
7777     if $handle_dist_run;
7778   Automake::Variable::define ('DIST_COMMON', VAR_AUTOMAKE, '+', TRUE, "@_",
7779                               '', INTERNAL, VAR_PRETTY);
7783 ################################################################
7785 # generate_makefile ($MAKEFILE_AM, $MAKEFILE_IN)
7786 # ----------------------------------------------
7787 # Generate a Makefile.in given the name of the corresponding Makefile and
7788 # the name of the file output by config.status.
7789 sub generate_makefile ($$)
7791   my ($makefile_am, $makefile_in) = @_;
7793   # Reset all the Makefile.am related variables.
7794   initialize_per_input;
7796   # AUTOMAKE_OPTIONS can contains -W flags to disable or enable
7797   # warnings for this file.  So hold any warning issued before
7798   # we have processed AUTOMAKE_OPTIONS.
7799   buffer_messages ('warning');
7801   # Name of input file ("Makefile.am") and output file
7802   # ("Makefile.in").  These have no directory components.
7803   $am_file_name = basename ($makefile_am);
7804   $in_file_name = basename ($makefile_in);
7806   # $OUTPUT is encoded.  If it contains a ":" then the first element
7807   # is the real output file, and all remaining elements are input
7808   # files.  We don't scan or otherwise deal with these input files,
7809   # other than to mark them as dependencies.  See
7810   # &scan_autoconf_files for details.
7811   my ($makefile, @inputs) = split (/:/, $output_files{$makefile_in});
7813   $relative_dir = dirname ($makefile);
7814   $am_relative_dir = dirname ($makefile_am);
7815   $topsrcdir = backname ($relative_dir);
7817   read_main_am_file ($makefile_am);
7818   if (handle_options)
7819     {
7820       # Process buffered warnings.
7821       flush_messages;
7822       # Fatal error.  Just return, so we can continue with next file.
7823       return;
7824     }
7825   # Process buffered warnings.
7826   flush_messages;
7828   # There are a few install-related variables that you should not define.
7829   foreach my $var ('PRE_INSTALL', 'POST_INSTALL', 'NORMAL_INSTALL')
7830     {
7831       my $v = var $var;
7832       if ($v)
7833         {
7834           my $def = $v->def (TRUE);
7835           prog_error "$var not defined in condition TRUE"
7836             unless $def;
7837           reject_var $var, "`$var' should not be defined"
7838             if $def->owner != VAR_AUTOMAKE;
7839         }
7840     }
7842   # Catch some obsolete variables.
7843   msg_var ('obsolete', 'INCLUDES',
7844            "`INCLUDES' is the old name for `AM_CPPFLAGS' (or `*_CPPFLAGS')")
7845     if var ('INCLUDES');
7847   # Must do this after reading .am file.
7848   define_variable ('subdir', $relative_dir, INTERNAL);
7850   # If DIST_SUBDIRS is defined, make sure SUBDIRS is, so that
7851   # recursive rules are enabled.
7852   define_pretty_variable ('SUBDIRS', TRUE, INTERNAL, '')
7853     if var 'DIST_SUBDIRS' && ! var 'SUBDIRS';
7855   # Check first, because we might modify some state.
7856   check_cygnus;
7857   check_gnu_standards;
7858   check_gnits_standards;
7860   handle_configure ($makefile_am, $makefile_in, $makefile, @inputs);
7861   handle_gettext;
7862   handle_libraries;
7863   handle_ltlibraries;
7864   handle_programs;
7865   handle_scripts;
7867   # These must be run after all the sources are scanned.  They
7868   # use variables defined by &handle_libraries, &handle_ltlibraries,
7869   # or &handle_programs.
7870   handle_compile;
7871   handle_languages;
7872   handle_libtool;
7874   # Variables used by distdir.am and tags.am.
7875   define_pretty_variable ('SOURCES', TRUE, INTERNAL, @sources);
7876   if (! option 'no-dist')
7877     {
7878       define_pretty_variable ('DIST_SOURCES', TRUE, INTERNAL, @dist_sources);
7879     }
7881   handle_multilib;
7882   handle_texinfo;
7883   handle_emacs_lisp;
7884   handle_python;
7885   handle_java;
7886   handle_man_pages;
7887   handle_data;
7888   handle_headers;
7889   handle_subdirs;
7890   handle_tags;
7891   handle_minor_options;
7892   # Must come after handle_programs so that %known_programs is up-to-date.
7893   handle_tests;
7895   # This must come after most other rules.
7896   handle_dist;
7898   handle_footer;
7899   do_check_merge_target;
7900   handle_all ($makefile);
7902   # FIXME: Gross!
7903   if (var ('lib_LTLIBRARIES') && var ('bin_PROGRAMS'))
7904     {
7905       $output_rules .= "install-binPROGRAMS: install-libLTLIBRARIES\n\n";
7906     }
7907   if (var ('nobase_lib_LTLIBRARIES') && var ('bin_PROGRAMS'))
7908     {
7909       $output_rules .= "install-binPROGRAMS: install-nobase_libLTLIBRARIES\n\n";
7910     }
7912   handle_install;
7913   handle_clean ($makefile);
7914   handle_factored_dependencies;
7916   # Comes last, because all the above procedures may have
7917   # defined or overridden variables.
7918   $output_vars .= output_variables;
7920   check_typos;
7922   my ($out_file) = $output_directory . '/' . $makefile_in;
7924   if ($exit_code != 0)
7925     {
7926       verb "not writing $out_file because of earlier errors";
7927       return;
7928     }
7930   if (! -d ($output_directory . '/' . $am_relative_dir))
7931     {
7932       mkdir ($output_directory . '/' . $am_relative_dir, 0755);
7933     }
7935   # We make sure that `all:' is the first target.
7936   my $output =
7937     "$output_vars$output_all$output_header$output_rules$output_trailer";
7939   # Decide whether we must update the output file or not.
7940   # We have to update in the following situations.
7941   #  * $force_generation is set.
7942   #  * any of the output dependencies is younger than the output
7943   #  * the contents of the output is different (this can happen
7944   #    if the project has been populated with a file listed in
7945   #    @common_files since the last run).
7946   # Output's dependencies are split in two sets:
7947   #  * dependencies which are also configure dependencies
7948   #    These do not change between each Makefile.am
7949   #  * other dependencies, specific to the Makefile.am being processed
7950   #    (such as the Makefile.am itself, or any Makefile fragment
7951   #    it includes).
7952   my $timestamp = mtime $out_file;
7953   if (! $force_generation
7954       && $configure_deps_greatest_timestamp < $timestamp
7955       && $output_deps_greatest_timestamp < $timestamp
7956       && $output eq contents ($out_file))
7957     {
7958       verb "$out_file unchanged";
7959       # No need to update.
7960       return;
7961     }
7963   if (-e $out_file)
7964     {
7965       unlink ($out_file)
7966         or fatal "cannot remove $out_file: $!\n";
7967     }
7969   my $gm_file = new Automake::XFile "> $out_file";
7970   verb "creating $out_file";
7971   print $gm_file $output;
7974 ################################################################
7979 ################################################################
7981 # Print usage information.
7982 sub usage ()
7984     print "Usage: $0 [OPTION] ... [Makefile]...
7986 Generate Makefile.in for configure from Makefile.am.
7988 Operation modes:
7989       --help               print this help, then exit
7990       --version            print version number, then exit
7991   -v, --verbose            verbosely list files processed
7992       --no-force           only update Makefile.in's that are out of date
7993   -W, --warnings=CATEGORY  report the warnings falling in CATEGORY
7995 Dependency tracking:
7996   -i, --ignore-deps      disable dependency tracking code
7997       --include-deps     enable dependency tracking code
7999 Flavors:
8000       --cygnus           assume program is part of Cygnus-style tree
8001       --foreign          set strictness to foreign
8002       --gnits            set strictness to gnits
8003       --gnu              set strictness to gnu
8005 Library files:
8006   -a, --add-missing      add missing standard files to package
8007       --libdir=DIR       directory storing library files
8008   -c, --copy             with -a, copy missing files (default is symlink)
8009   -f, --force-missing    force update of standard files
8012     Automake::ChannelDefs::usage;
8014     my ($last, @lcomm);
8015     $last = '';
8016     foreach my $iter (sort ((@common_files, @common_sometimes)))
8017     {
8018         push (@lcomm, $iter) unless $iter eq $last;
8019         $last = $iter;
8020     }
8022     my @four;
8023     print "\nFiles which are automatically distributed, if found:\n";
8024     format USAGE_FORMAT =
8025   @<<<<<<<<<<<<<<<<   @<<<<<<<<<<<<<<<<   @<<<<<<<<<<<<<<<<   @<<<<<<<<<<<<<<<<
8026   $four[0],           $four[1],           $four[2],           $four[3]
8028     $~ = "USAGE_FORMAT";
8030     my $cols = 4;
8031     my $rows = int(@lcomm / $cols);
8032     my $rest = @lcomm % $cols;
8034     if ($rest)
8035     {
8036         $rows++;
8037     }
8038     else
8039     {
8040         $rest = $cols;
8041     }
8043     for (my $y = 0; $y < $rows; $y++)
8044     {
8045         @four = ("", "", "", "");
8046         for (my $x = 0; $x < $cols; $x++)
8047         {
8048             last if $y + 1 == $rows && $x == $rest;
8050             my $idx = (($x > $rest)
8051                        ?  ($rows * $rest + ($rows - 1) * ($x - $rest))
8052                        : ($rows * $x));
8054             $idx += $y;
8055             $four[$x] = $lcomm[$idx];
8056         }
8057         write;
8058     }
8060     print "\nReport bugs to <bug-automake\@gnu.org>.\n";
8062     # --help always returns 0 per GNU standards.
8063     exit 0;
8067 # &version ()
8068 # -----------
8069 # Print version information
8070 sub version ()
8072   print <<EOF;
8073 automake (GNU $PACKAGE) $VERSION
8074 Copyright (C) 2009 Free Software Foundation, Inc.
8075 License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
8076 This is free software: you are free to change and redistribute it.
8077 There is NO WARRANTY, to the extent permitted by law.
8079 Written by Tom Tromey <tromey\@redhat.com>
8080        and Alexandre Duret-Lutz <adl\@gnu.org>.
8082   # --version always returns 0 per GNU standards.
8083   exit 0;
8086 ################################################################
8088 # Parse command line.
8089 sub parse_arguments ()
8091   # Start off as gnu.
8092   set_strictness ('gnu');
8094   my $cli_where = new Automake::Location;
8095   my %cli_options =
8096     (
8097      'libdir=s' => \$libdir,
8098      'gnu'              => sub { set_strictness ('gnu'); },
8099      'gnits'            => sub { set_strictness ('gnits'); },
8100      'cygnus'           => sub { set_global_option ('cygnus', $cli_where); },
8101      'foreign'          => sub { set_strictness ('foreign'); },
8102      'include-deps'     => sub { unset_global_option ('no-dependencies'); },
8103      'i|ignore-deps'    => sub { set_global_option ('no-dependencies',
8104                                                     $cli_where); },
8105      'no-force' => sub { $force_generation = 0; },
8106      'f|force-missing'  => \$force_missing,
8107      'o|output-dir=s'   => \$output_directory,
8108      'a|add-missing'    => \$add_missing,
8109      'c|copy'           => \$copy_missing,
8110      'v|verbose'        => sub { setup_channel 'verb', silent => 0; },
8111      'W|warnings=s'     => \&parse_warnings,
8112      # These long options (--Werror and --Wno-error) for backward
8113      # compatibility.  Use -Werror and -Wno-error today.
8114      'Werror'           => sub { parse_warnings 'W', 'error'; },
8115      'Wno-error'        => sub { parse_warnings 'W', 'no-error'; },
8116      );
8117   use Getopt::Long;
8118   Getopt::Long::config ("bundling", "pass_through");
8120   # See if --version or --help is used.  We want to process these before
8121   # anything else because the GNU Coding Standards require us to
8122   # `exit 0' after processing these options, and we can't guarantee this
8123   # if we treat other options first.  (Handling other options first
8124   # could produce error diagnostics, and in this condition it is
8125   # confusing if Automake does `exit 0'.)
8126   my %cli_options_1st_pass =
8127     (
8128      'version' => \&version,
8129      'help'    => \&usage,
8130      # Recognize all other options (and their arguments) but do nothing.
8131      map { $_ => sub {} } (keys %cli_options)
8132      );
8133   my @ARGV_backup = @ARGV;
8134   Getopt::Long::GetOptions %cli_options_1st_pass
8135     or exit 1;
8136   @ARGV = @ARGV_backup;
8138   # Now *really* process the options.  This time we know that --help
8139   # and --version are not present, but we specify them nonetheless so
8140   # that ambiguous abbreviation are diagnosed.
8141   Getopt::Long::GetOptions %cli_options, 'version' => sub {}, 'help' => sub {}
8142     or exit 1;
8144   if (defined $output_directory)
8145     {
8146       msg 'obsolete', "`--output-dir' is deprecated\n";
8147     }
8148   else
8149     {
8150       # In the next release we'll remove this entirely.
8151       $output_directory = '.';
8152     }
8154   return unless @ARGV;
8156   if ($ARGV[0] =~ /^-./)
8157     {
8158       my %argopts;
8159       for my $k (keys %cli_options)
8160         {
8161           if ($k =~ /(.*)=s$/)
8162             {
8163               map { $argopts{(length ($_) == 1)
8164                              ? "-$_" : "--$_" } = 1; } (split (/\|/, $1));
8165             }
8166         }
8167       if ($ARGV[0] eq '--')
8168         {
8169           shift @ARGV;
8170         }
8171       elsif (exists $argopts{$ARGV[0]})
8172         {
8173           fatal ("option `$ARGV[0]' requires an argument\n"
8174                  . "Try `$0 --help' for more information.");
8175         }
8176       else
8177         {
8178           fatal ("unrecognized option `$ARGV[0]'.\n"
8179                  . "Try `$0 --help' for more information.");
8180         }
8181     }
8183   my $errspec = 0;
8184   foreach my $arg (@ARGV)
8185     {
8186       fatal ("empty argument\nTry `$0 --help' for more information.")
8187         if ($arg eq '');
8189       # Handle $local:$input syntax.
8190       my ($local, @rest) = split (/:/, $arg);
8191       @rest = ("$local.in",) unless @rest;
8192       my $input = locate_am @rest;
8193       if ($input)
8194         {
8195           push @input_files, $input;
8196           $output_files{$input} = join (':', ($local, @rest));
8197         }
8198       else
8199         {
8200           error "no Automake input file found for `$arg'";
8201           $errspec = 1;
8202         }
8203     }
8204   fatal "no input file found among supplied arguments"
8205     if $errspec && ! @input_files;
8209 # handle_makefile ($MAKEFILE_IN)
8210 # ------------------------------
8211 # Deal with $MAKEFILE_IN.
8212 sub handle_makefile ($)
8214   my ($file) =  @_;
8215   ($am_file = $file) =~ s/\.in$//;
8216   if (! -f ($am_file . '.am'))
8217     {
8218       error "`$am_file.am' does not exist";
8219     }
8220   else
8221     {
8222       # Any warning setting now local to this Makefile.am.
8223       dup_channel_setup;
8225       generate_makefile ($am_file . '.am', $file);
8227       # Back out any warning setting.
8228       drop_channel_setup;
8229     }
8232 # handle_makefiles_serial ()
8233 # --------------------------
8234 # Deal with all makefiles, without threads.
8235 sub handle_makefiles_serial ()
8237   foreach my $file (@input_files)
8238     {
8239       handle_makefile ($file);
8240     }
8243 # get_number_of_threads ()
8244 # ------------------------
8245 # Logic for deciding how many worker threads to use.
8246 sub get_number_of_threads
8248   my $nthreads = $ENV{'AUTOMAKE_JOBS'} || 0;
8250   $nthreads = 0
8251     unless $nthreads =~ /^[0-9]+$/;
8253   # It doesn't make sense to use more threads than makefiles,
8254   my $max_threads = @input_files;
8256   # but a single worker thread is helpful for exposing bugs.
8257   if ($automake_will_process_aux_dir && $max_threads > 1)
8258     {
8259       $max_threads--;
8260     }
8261   if ($nthreads > $max_threads)
8262     {
8263       $nthreads = $max_threads;
8264     }
8265   return $nthreads;
8268 # handle_makefiles_threaded ($NTHREADS)
8269 # -------------------------------------
8270 # Deal with all makefiles, using threads.  The general strategy is to
8271 # spawn NTHREADS worker threads, dispatch makefiles to them, and let the
8272 # worker threads push back everything that needs serialization:
8273 # * warning and (normal) error messages, for stable stderr output
8274 #   order and content (avoiding duplicates, for example),
8275 # * races when installing aux files (and respective messages),
8276 # * races when collecting aux files for distribution.
8278 # The latter requires that the makefile that deals with the aux dir
8279 # files be handled last, done by the master thread.
8280 sub handle_makefiles_threaded ($)
8282   my ($nthreads) = @_;
8284   my @queued_input_files = @input_files;
8285   my $last_input_file = undef;
8286   if ($automake_will_process_aux_dir)
8287     {
8288       $last_input_file = pop @queued_input_files;
8289     }
8291   # The file queue distributes all makefiles, the message queues
8292   # collect all serializations needed for respective files.
8293   my $file_queue = Thread::Queue->new;
8294   my %msg_queues;
8295   foreach my $file (@queued_input_files)
8296     {
8297       $msg_queues{$file} = Thread::Queue->new;
8298     }
8300   verb "spawning $nthreads worker threads";
8301   my @threads = (1 .. $nthreads);
8302   foreach my $t (@threads)
8303     {
8304       $t = threads->new (sub
8305         {
8306           while (my $file = $file_queue->dequeue)
8307             {
8308               verb "handling $file";
8309               my $queue = $msg_queues{$file};
8310               setup_channel_queue ($queue, QUEUE_MESSAGE);
8311               $required_conf_file_queue = $queue;
8312               handle_makefile ($file);
8313               $queue->enqueue (undef);
8314               setup_channel_queue (undef, undef);
8315               $required_conf_file_queue = undef;
8316             }
8317           return $exit_code;
8318         });
8319     }
8321   # Queue all normal makefiles.
8322   verb "queuing " . @queued_input_files . " input files";
8323   $file_queue->enqueue (@queued_input_files, (undef) x @threads);
8325   # Collect and process serializations.
8326   foreach my $file (@queued_input_files)
8327     {
8328       verb "dequeuing messages for " . $file;
8329       reset_local_duplicates ();
8330       my $queue = $msg_queues{$file};
8331       while (my $key = $queue->dequeue)
8332         {
8333           if ($key eq QUEUE_MESSAGE)
8334             {
8335               pop_channel_queue ($queue);
8336             }
8337           elsif ($key eq QUEUE_CONF_FILE)
8338             {
8339               require_queued_conf_file ($queue);
8340             }
8341           else
8342             {
8343               prog_error "unexpected key $key";
8344             }
8345         }
8346     }
8348   foreach my $t (@threads)
8349     {
8350       my @exit_thread = $t->join;
8351       $exit_code = $exit_thread[0]
8352         if ($exit_thread[0] > $exit_code);
8353     }
8355   # The master processes the last file.
8356   if ($automake_will_process_aux_dir)
8357     {
8358       verb "processing last input file";
8359       handle_makefile ($last_input_file);
8360     }
8363 ################################################################
8365 # Parse the WARNINGS environment variable.
8366 parse_WARNINGS;
8368 # Parse command line.
8369 parse_arguments;
8371 $configure_ac = require_configure_ac;
8373 # Do configure.ac scan only once.
8374 scan_autoconf_files;
8376 if (! @input_files)
8377   {
8378     my $msg = '';
8379     $msg = "\nDid you forget AC_CONFIG_FILES([Makefile]) in $configure_ac?"
8380       if -f 'Makefile.am';
8381     fatal ("no `Makefile.am' found for any configure output$msg");
8382   }
8384 my $nthreads = get_number_of_threads ();
8386 if ($perl_threads && $nthreads >= 1)
8387   {
8388     handle_makefiles_threaded ($nthreads);
8389   }
8390 else
8391   {
8392     handle_makefiles_serial ();
8393   }
8395 exit $exit_code;
8398 ### Setup "GNU" style for perl-mode and cperl-mode.
8399 ## Local Variables:
8400 ## perl-indent-level: 2
8401 ## perl-continued-statement-offset: 2
8402 ## perl-continued-brace-offset: 0
8403 ## perl-brace-offset: 0
8404 ## perl-brace-imaginary-offset: 0
8405 ## perl-label-offset: -2
8406 ## cperl-indent-level: 2
8407 ## cperl-brace-offset: 0
8408 ## cperl-continued-brace-offset: 0
8409 ## cperl-label-offset: -2
8410 ## cperl-extra-newline-before-brace: t
8411 ## cperl-merge-trailing-else: nil
8412 ## cperl-continued-statement-offset: 2
8413 ## End: