Avoid racy depmodes with universal builds.
[automake.git] / automake.in
blobfe2ff3d788d4d2edfc94c05dfb16f4ee69743f08
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 compiler variable (CC).
92         'ccer' => "\$",
94         # Name of the linker variable (LD).
95         'lder' => "\$",
96         # Content of the linker variable ($(CC)).
97         'ld' => "\$",
99         # Flag to specify the output file (-o).
100         'output_flag' => "\$",
101         '_finish' => "\$",
103         # This is a subroutine which is called whenever we finally
104         # determine the context in which a source file will be
105         # compiled.
106         '_target_hook' => "\$",
108         # If TRUE, nodist_ sources will be compiled using specific rules
109         # (i.e. not inference rules).  The default is FALSE.
110         'nodist_specific' => "\$");
113 sub finish ($)
115   my ($self) = @_;
116   if (defined $self->_finish)
117     {
118       &{$self->_finish} (@_);
119     }
122 sub target_hook ($$$$%)
124     my ($self) = @_;
125     if (defined $self->_target_hook)
126     {
127         &{$self->_target_hook} (@_);
128     }
131 package Automake;
133 use strict;
134 use Automake::Config;
135 BEGIN
137   if ($perl_threads)
138     {
139       require threads;
140       import threads;
141       require Thread::Queue;
142       import Thread::Queue;
143     }
145 use Automake::General;
146 use Automake::XFile;
147 use Automake::Channels;
148 use Automake::ChannelDefs;
149 use Automake::Configure_ac;
150 use Automake::FileUtils;
151 use Automake::Location;
152 use Automake::Condition qw/TRUE FALSE/;
153 use Automake::DisjConditions;
154 use Automake::Options;
155 use Automake::Version;
156 use Automake::Variable;
157 use Automake::VarDef;
158 use Automake::Rule;
159 use Automake::RuleDef;
160 use Automake::Wrap 'makefile_wrap';
161 use File::Basename;
162 use File::Spec;
163 use Carp;
165 ## ----------- ##
166 ## Constants.  ##
167 ## ----------- ##
169 # Some regular expressions.  One reason to put them here is that it
170 # makes indentation work better in Emacs.
172 # Writing singled-quoted-$-terminated regexes is a pain because
173 # perl-mode thinks of $' as the ${'} variable (instead of a $ followed
174 # by a closing quote.  Letting perl-mode think the quote is not closed
175 # leads to all sort of misindentations.  On the other hand, defining
176 # regexes as double-quoted strings is far less readable.  So usually
177 # we will write:
179 #  $REGEX = '^regex_value' . "\$";
181 my $IGNORE_PATTERN = '^\s*##([^#\n].*)?\n';
182 my $WHITE_PATTERN = '^\s*' . "\$";
183 my $COMMENT_PATTERN = '^#';
184 my $TARGET_PATTERN='[$a-zA-Z0-9_.@%][-.a-zA-Z0-9_(){}/$+@%]*';
185 # A rule has three parts: a list of targets, a list of dependencies,
186 # and optionally actions.
187 my $RULE_PATTERN =
188   "^($TARGET_PATTERN(?:(?:\\\\\n|\\s)+$TARGET_PATTERN)*) *:([^=].*|)\$";
190 # Only recognize leading spaces, not leading tabs.  If we recognize
191 # leading tabs here then we need to make the reader smarter, because
192 # otherwise it will think rules like `foo=bar; \' are errors.
193 my $ASSIGNMENT_PATTERN = '^ *([^ \t=:+]*)\s*([:+]?)=\s*(.*)' . "\$";
194 # This pattern recognizes a Gnits version id and sets $1 if the
195 # release is an alpha release.  We also allow a suffix which can be
196 # used to extend the version number with a "fork" identifier.
197 my $GNITS_VERSION_PATTERN = '\d+\.\d+([a-z]|\.\d+)?(-[A-Za-z0-9]+)?';
199 my $IF_PATTERN = '^if\s+(!?)\s*([A-Za-z][A-Za-z0-9_]*)\s*(?:#.*)?' . "\$";
200 my $ELSE_PATTERN =
201   '^else(?:\s+(!?)\s*([A-Za-z][A-Za-z0-9_]*))?\s*(?:#.*)?' . "\$";
202 my $ENDIF_PATTERN =
203   '^endif(?:\s+(!?)\s*([A-Za-z][A-Za-z0-9_]*))?\s*(?:#.*)?' . "\$";
204 my $PATH_PATTERN = '(\w|[+/.-])+';
205 # This will pass through anything not of the prescribed form.
206 my $INCLUDE_PATTERN = ('^include\s+'
207                        . '((\$\(top_srcdir\)/' . $PATH_PATTERN . ')'
208                        . '|(\$\(srcdir\)/' . $PATH_PATTERN . ')'
209                        . '|([^/\$]' . $PATH_PATTERN . '))\s*(#.*)?' . "\$");
211 # Match `-d' as a command-line argument in a string.
212 my $DASH_D_PATTERN = "(^|\\s)-d(\\s|\$)";
213 # Directories installed during 'install-exec' phase.
214 my $EXEC_DIR_PATTERN =
215   '^(?:bin|sbin|libexec|sysconf|localstate|lib|pkglib|.*exec.*)' . "\$";
217 # Values for AC_CANONICAL_*
218 use constant AC_CANONICAL_BUILD  => 1;
219 use constant AC_CANONICAL_HOST   => 2;
220 use constant AC_CANONICAL_TARGET => 3;
222 # Values indicating when something should be cleaned.
223 use constant MOSTLY_CLEAN     => 0;
224 use constant CLEAN            => 1;
225 use constant DIST_CLEAN       => 2;
226 use constant MAINTAINER_CLEAN => 3;
228 # Libtool files.
229 my @libtool_files = qw(ltmain.sh config.guess config.sub);
230 # ltconfig appears here for compatibility with old versions of libtool.
231 my @libtool_sometimes = qw(ltconfig ltcf-c.sh ltcf-cxx.sh ltcf-gcj.sh);
233 # Commonly found files we look for and automatically include in
234 # DISTFILES.
235 my @common_files =
236     (qw(ABOUT-GNU ABOUT-NLS AUTHORS BACKLOG COPYING COPYING.DOC COPYING.LIB
237         COPYING.LESSER ChangeLog INSTALL NEWS README THANKS TODO
238         ansi2knr.1 ansi2knr.c compile config.guess config.rpath config.sub
239         depcomp elisp-comp install-sh libversion.in mdate-sh missing
240         mkinstalldirs py-compile texinfo.tex ylwrap),
241      @libtool_files, @libtool_sometimes);
243 # Commonly used files we auto-include, but only sometimes.  This list
244 # is used for the --help output only.
245 my @common_sometimes =
246   qw(aclocal.m4 acconfig.h config.h.top config.h.bot configure
247      configure.ac configure.in stamp-vti);
249 # Standard directories from the GNU Coding Standards, and additional
250 # pkg* directories from Automake.  Stored in a hash for fast member check.
251 my %standard_prefix =
252     map { $_ => 1 } (qw(bin data dataroot dvi exec html include info
253                         lib libexec lisp localstate man man1 man2 man3
254                         man4 man5 man6 man7 man8 man9 oldinclude pdf
255                         pkgdatadir pkgincludedir pkglibdir pkglibexecdir
256                         ps sbin sharedstate sysconf));
258 # Copyright on generated Makefile.ins.
259 my $gen_copyright = "\
260 # Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002,
261 # 2003, 2004, 2005, 2006, 2007, 2008, 2009  Free Software Foundation,
262 # Inc.
263 # This Makefile.in is free software; the Free Software Foundation
264 # gives unlimited permission to copy and/or distribute it,
265 # with or without modifications, as long as this notice is preserved.
267 # This program is distributed in the hope that it will be useful,
268 # but WITHOUT ANY WARRANTY, to the extent permitted by law; without
269 # even the implied warranty of MERCHANTABILITY or FITNESS FOR A
270 # PARTICULAR PURPOSE.
273 # These constants are returned by the lang_*_rewrite functions.
274 # LANG_SUBDIR means that the resulting object file should be in a
275 # subdir if the source file is.  In this case the file name cannot
276 # have `..' components.
277 use constant LANG_IGNORE  => 0;
278 use constant LANG_PROCESS => 1;
279 use constant LANG_SUBDIR  => 2;
281 # These are used when keeping track of whether an object can be built
282 # by two different paths.
283 use constant COMPILE_LIBTOOL  => 1;
284 use constant COMPILE_ORDINARY => 2;
286 # We can't always associate a location to a variable or a rule,
287 # when it's defined by Automake.  We use INTERNAL in this case.
288 use constant INTERNAL => new Automake::Location;
290 # Serialization keys for message queues.
291 use constant QUEUE_MESSAGE   => "msg";
292 use constant QUEUE_CONF_FILE => "conf file";
293 use constant QUEUE_LOCATION  => "location";
294 use constant QUEUE_STRING    => "string";
297 ## ---------------------------------- ##
298 ## Variables related to the options.  ##
299 ## ---------------------------------- ##
301 # TRUE if we should always generate Makefile.in.
302 my $force_generation = 1;
304 # From the Perl manual.
305 my $symlink_exists = (eval 'symlink ("", "");', $@ eq '');
307 # TRUE if missing standard files should be installed.
308 my $add_missing = 0;
310 # TRUE if we should copy missing files; otherwise symlink if possible.
311 my $copy_missing = 0;
313 # TRUE if we should always update files that we know about.
314 my $force_missing = 0;
317 ## ---------------------------------------- ##
318 ## Variables filled during files scanning.  ##
319 ## ---------------------------------------- ##
321 # Name of the configure.ac file.
322 my $configure_ac;
324 # Files found by scanning configure.ac for LIBOBJS.
325 my %libsources = ();
327 # Names used in AC_CONFIG_HEADER call.
328 my @config_headers = ();
330 # Names used in AC_CONFIG_LINKS call.
331 my @config_links = ();
333 # Directory where output files go.  Actually, output files are
334 # relative to this directory.
335 my $output_directory;
337 # List of Makefile.am's to process, and their corresponding outputs.
338 my @input_files = ();
339 my %output_files = ();
341 # Complete list of Makefile.am's that exist.
342 my @configure_input_files = ();
344 # List of files in AC_CONFIG_FILES/AC_OUTPUT without Makefile.am's,
345 # and their outputs.
346 my @other_input_files = ();
347 # Where each AC_CONFIG_FILES/AC_OUTPUT/AC_CONFIG_LINK/AC_CONFIG_HEADER appears.
348 # The keys are the files created by these macros.
349 my %ac_config_files_location = ();
350 # The condition under which AC_CONFIG_FOOS appears.
351 my %ac_config_files_condition = ();
353 # Directory to search for configure-required files.  This
354 # will be computed by &locate_aux_dir and can be set using
355 # AC_CONFIG_AUX_DIR in configure.ac.
356 # $CONFIG_AUX_DIR is the `raw' directory, valid only in the source-tree.
357 my $config_aux_dir = '';
358 my $config_aux_dir_set_in_configure_ac = 0;
359 # $AM_CONFIG_AUX_DIR is prefixed with $(top_srcdir), so it can be used
360 # in Makefiles.
361 my $am_config_aux_dir = '';
363 # Directory to search for AC_LIBSOURCE files, as set by AC_CONFIG_LIBOBJ_DIR
364 # in configure.ac.
365 my $config_libobj_dir = '';
367 # Whether AM_GNU_GETTEXT has been seen in configure.ac.
368 my $seen_gettext = 0;
369 # Whether AM_GNU_GETTEXT([external]) is used.
370 my $seen_gettext_external = 0;
371 # Where AM_GNU_GETTEXT appears.
372 my $ac_gettext_location;
373 # Whether AM_GNU_GETTEXT_INTL_SUBDIR has been seen.
374 my $seen_gettext_intl = 0;
376 # Lists of tags supported by Libtool.
377 my %libtool_tags = ();
378 # 1 if Libtool uses LT_SUPPORTED_TAG.  If it does, then it also
379 # uses AC_REQUIRE_AUX_FILE.
380 my $libtool_new_api = 0;
382 # Most important AC_CANONICAL_* macro seen so far.
383 my $seen_canonical = 0;
384 # Location of that macro.
385 my $canonical_location;
387 # Where AM_MAINTAINER_MODE appears.
388 my $seen_maint_mode;
390 # Actual version we've seen.
391 my $package_version = '';
393 # Where version is defined.
394 my $package_version_location;
396 # TRUE if we've seen AM_ENABLE_MULTILIB.
397 my $seen_multilib = 0;
399 # TRUE if we've seen AM_PROG_CC_C_O
400 my $seen_cc_c_o = 0;
402 # Location of AC_REQUIRE_AUX_FILE calls, indexed by their argument.
403 my %required_aux_file = ();
405 # Where AM_INIT_AUTOMAKE is called;
406 my $seen_init_automake = 0;
408 # TRUE if we've seen AM_AUTOMAKE_VERSION.
409 my $seen_automake_version = 0;
411 # Hash table of discovered configure substitutions.  Keys are names,
412 # values are `FILE:LINE' strings which are used by error message
413 # generation.
414 my %configure_vars = ();
416 # Ignored configure substitutions (i.e., variables not to be output in
417 # Makefile.in)
418 my %ignored_configure_vars = ();
420 # Files included by $configure_ac.
421 my @configure_deps = ();
423 # Greatest timestamp of configure's dependencies.
424 my $configure_deps_greatest_timestamp = 0;
426 # Hash table of AM_CONDITIONAL variables seen in configure.
427 my %configure_cond = ();
429 # This maps extensions onto language names.
430 my %extension_map = ();
432 # List of the DIST_COMMON files we discovered while reading
433 # configure.in
434 my $configure_dist_common = '';
436 # This maps languages names onto objects.
437 my %languages = ();
438 # Maps each linker variable onto a language object.
439 my %link_languages = ();
441 # maps extensions to needed source flags.
442 my %sourceflags = ();
444 # List of targets we must always output.
445 # FIXME: Complete, and remove falsely required targets.
446 my %required_targets =
447   (
448    'all'          => 1,
449    'dvi'          => 1,
450    'pdf'          => 1,
451    'ps'           => 1,
452    'info'         => 1,
453    'install-info' => 1,
454    'install'      => 1,
455    'install-data' => 1,
456    'install-exec' => 1,
457    'uninstall'    => 1,
459    # FIXME: Not required, temporary hacks.
460    # Well, actually they are sort of required: the -recursive
461    # targets will run them anyway...
462    'html-am'         => 1,
463    'dvi-am'          => 1,
464    'pdf-am'          => 1,
465    'ps-am'           => 1,
466    'info-am'         => 1,
467    'install-data-am' => 1,
468    'install-exec-am' => 1,
469    'install-html-am' => 1,
470    'install-dvi-am'  => 1,
471    'install-pdf-am'  => 1,
472    'install-ps-am'   => 1,
473    'install-info-am' => 1,
474    'installcheck-am' => 1,
475    'uninstall-am' => 1,
477    'install-man' => 1,
478   );
480 # Set to 1 if this run will create the Makefile.in that distributes
481 # the files in config_aux_dir.
482 my $automake_will_process_aux_dir = 0;
484 # The name of the Makefile currently being processed.
485 my $am_file = 'BUG';
488 ################################################################
490 ## ------------------------------------------ ##
491 ## Variables reset by &initialize_per_input.  ##
492 ## ------------------------------------------ ##
494 # Basename and relative dir of the input file.
495 my $am_file_name;
496 my $am_relative_dir;
498 # Same but wrt Makefile.in.
499 my $in_file_name;
500 my $relative_dir;
502 # Relative path to the top directory.
503 my $topsrcdir;
505 # Greatest timestamp of the output's dependencies (excluding
506 # configure's dependencies).
507 my $output_deps_greatest_timestamp;
509 # These variables are used when generating each Makefile.in.
510 # They hold the Makefile.in until it is ready to be printed.
511 my $output_vars;
512 my $output_all;
513 my $output_header;
514 my $output_rules;
515 my $output_trailer;
517 # This is the conditional stack, updated on if/else/endif, and
518 # used to build Condition objects.
519 my @cond_stack;
521 # This holds the set of included files.
522 my @include_stack;
524 # List of dependencies for the obvious targets.
525 my @all;
526 my @check;
527 my @check_tests;
529 # Keys in this hash table are files to delete.  The associated
530 # value tells when this should happen (MOSTLY_CLEAN, DIST_CLEAN, etc.)
531 my %clean_files;
533 # Keys in this hash table are object files or other files in
534 # subdirectories which need to be removed.  This only holds files
535 # which are created by compilations.  The value in the hash indicates
536 # when the file should be removed.
537 my %compile_clean_files;
539 # Keys in this hash table are directories where we expect to build a
540 # libtool object.  We use this information to decide what directories
541 # to delete.
542 my %libtool_clean_directories;
544 # Value of `$(SOURCES)', used by tags.am.
545 my @sources;
546 # Sources which go in the distribution.
547 my @dist_sources;
549 # This hash maps object file names onto their corresponding source
550 # file names.  This is used to ensure that each object is created
551 # by a single source file.
552 my %object_map;
554 # This hash maps object file names onto an integer value representing
555 # whether this object has been built via ordinary compilation or
556 # libtool compilation (the COMPILE_* constants).
557 my %object_compilation_map;
560 # This keeps track of the directories for which we've already
561 # created dirstamp code.  Keys are directories, values are stamp files.
562 # Several keys can share the same stamp files if they are equivalent
563 # (as are `.//foo' and `foo').
564 my %directory_map;
566 # All .P files.
567 my %dep_files;
569 # This is a list of all targets to run during "make dist".
570 my @dist_targets;
572 # Keep track of all programs declared in this Makefile, without
573 # $(EXEEXT).  @substitutions@ are not listed.
574 my %known_programs;
575 my %known_libraries;
577 # Keys in this hash are the basenames of files which must depend on
578 # ansi2knr.  Values are either the empty string, or the directory in
579 # which the ANSI source file appears; the directory must have a
580 # trailing `/'.
581 my %de_ansi_files;
583 # This keeps track of which extensions we've seen (that we care
584 # about).
585 my %extension_seen;
587 # This is random scratch space for the language finish functions.
588 # Don't randomly overwrite it; examine other uses of keys first.
589 my %language_scratch;
591 # We keep track of which objects need special (per-executable)
592 # handling on a per-language basis.
593 my %lang_specific_files;
595 # This is set when `handle_dist' has finished.  Once this happens,
596 # we should no longer push on dist_common.
597 my $handle_dist_run;
599 # Used to store a set of linkers needed to generate the sources currently
600 # under consideration.
601 my %linkers_used;
603 # True if we need `LINK' defined.  This is a hack.
604 my $need_link;
606 # Was get_object_extension run?
607 # FIXME: This is a hack. a better switch should be found.
608 my $get_object_extension_was_run;
610 # Record each file processed by make_paragraphs.
611 my %transformed_files;
614 ################################################################
616 ## ---------------------------------------------- ##
617 ## Variables not reset by &initialize_per_input.  ##
618 ## ---------------------------------------------- ##
620 # Cache each file processed by make_paragraphs.
621 # (This is different from %transformed_files because
622 # %transformed_files is reset for each file while %am_file_cache
623 # it global to the run.)
624 my %am_file_cache;
626 ################################################################
628 # var_SUFFIXES_trigger ($TYPE, $VALUE)
629 # ------------------------------------
630 # This is called by Automake::Variable::define() when SUFFIXES
631 # is defined ($TYPE eq '') or appended ($TYPE eq '+').
632 # The work here needs to be performed as a side-effect of the
633 # macro_define() call because SUFFIXES definitions impact
634 # on $KNOWN_EXTENSIONS_PATTERN which is used used when parsing
635 # the input am file.
636 sub var_SUFFIXES_trigger ($$)
638     my ($type, $value) = @_;
639     accept_extensions (split (' ', $value));
641 Automake::Variable::hook ('SUFFIXES', \&var_SUFFIXES_trigger);
643 ################################################################
645 ## --------------------------------- ##
646 ## Forward subroutine declarations.  ##
647 ## --------------------------------- ##
648 sub register_language (%);
649 sub file_contents_internal ($$$%);
650 sub define_files_variable ($\@$$);
653 # &initialize_per_input ()
654 # ------------------------
655 # (Re)-Initialize per-Makefile.am variables.
656 sub initialize_per_input ()
658     reset_local_duplicates ();
660     $am_file_name = undef;
661     $am_relative_dir = undef;
663     $in_file_name = undef;
664     $relative_dir = undef;
665     $topsrcdir = undef;
667     $output_deps_greatest_timestamp = 0;
669     $output_vars = '';
670     $output_all = '';
671     $output_header = '';
672     $output_rules = '';
673     $output_trailer = '';
675     Automake::Options::reset;
676     Automake::Variable::reset;
677     Automake::Rule::reset;
679     @cond_stack = ();
681     @include_stack = ();
683     @all = ();
684     @check = ();
685     @check_tests = ();
687     %clean_files = ();
688     %compile_clean_files = ();
690     # We always include `.'.  This isn't strictly correct.
691     %libtool_clean_directories = ('.' => 1);
693     @sources = ();
694     @dist_sources = ();
696     %object_map = ();
697     %object_compilation_map = ();
699     %directory_map = ();
701     %dep_files = ();
703     @dist_targets = ();
705     %known_programs = ();
706     %known_libraries= ();
708     %de_ansi_files = ();
710     %extension_seen = ();
712     %language_scratch = ();
714     %lang_specific_files = ();
716     $handle_dist_run = 0;
718     $need_link = 0;
720     $get_object_extension_was_run = 0;
722     %transformed_files = ();
726 ################################################################
728 # Initialize our list of languages that are internally supported.
730 # C.
731 register_language ('name' => 'c',
732                    'Name' => 'C',
733                    'config_vars' => ['CC'],
734                    'ansi' => 1,
735                    'autodep' => '',
736                    'flags' => ['CFLAGS', 'CPPFLAGS'],
737                    'ccer' => 'CC',
738                    'compiler' => 'COMPILE',
739                    'compile' => '$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS)',
740                    'lder' => 'CCLD',
741                    'ld' => '$(CC)',
742                    'linker' => 'LINK',
743                    'link' => '$(CCLD) $(AM_CFLAGS) $(CFLAGS) $(AM_LDFLAGS) $(LDFLAGS) -o $@',
744                    'compile_flag' => '-c',
745                    'libtool_tag' => 'CC',
746                    'extensions' => ['.c'],
747                    '_finish' => \&lang_c_finish);
749 # C++.
750 register_language ('name' => 'cxx',
751                    'Name' => 'C++',
752                    'config_vars' => ['CXX'],
753                    'linker' => 'CXXLINK',
754                    'link' => '$(CXXLD) $(AM_CXXFLAGS) $(CXXFLAGS) $(AM_LDFLAGS) $(LDFLAGS) -o $@',
755                    'autodep' => 'CXX',
756                    'flags' => ['CXXFLAGS', 'CPPFLAGS'],
757                    'compile' => '$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS)',
758                    'ccer' => 'CXX',
759                    'compiler' => 'CXXCOMPILE',
760                    'compile_flag' => '-c',
761                    'output_flag' => '-o',
762                    'libtool_tag' => 'CXX',
763                    'lder' => 'CXXLD',
764                    'ld' => '$(CXX)',
765                    'pure' => 1,
766                    'extensions' => ['.c++', '.cc', '.cpp', '.cxx', '.C']);
768 # Objective C.
769 register_language ('name' => 'objc',
770                    'Name' => 'Objective C',
771                    'config_vars' => ['OBJC'],
772                    'linker' => 'OBJCLINK',
773                    'link' => '$(OBJCLD) $(AM_OBJCFLAGS) $(OBJCFLAGS) $(AM_LDFLAGS) $(LDFLAGS) -o $@',
774                    'autodep' => 'OBJC',
775                    'flags' => ['OBJCFLAGS', 'CPPFLAGS'],
776                    'compile' => '$(OBJC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_OBJCFLAGS) $(OBJCFLAGS)',
777                    'ccer' => 'OBJC',
778                    'compiler' => 'OBJCCOMPILE',
779                    'compile_flag' => '-c',
780                    'output_flag' => '-o',
781                    'lder' => 'OBJCLD',
782                    'ld' => '$(OBJC)',
783                    'pure' => 1,
784                    'extensions' => ['.m']);
786 # Unified Parallel C.
787 register_language ('name' => 'upc',
788                    'Name' => 'Unified Parallel C',
789                    'config_vars' => ['UPC'],
790                    'linker' => 'UPCLINK',
791                    'link' => '$(UPCLD) $(AM_UPCFLAGS) $(UPCFLAGS) $(AM_LDFLAGS) $(LDFLAGS) -o $@',
792                    'autodep' => 'UPC',
793                    'flags' => ['UPCFLAGS', 'CPPFLAGS'],
794                    'compile' => '$(UPC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_UPCFLAGS) $(UPCFLAGS)',
795                    'ccer' => 'UPC',
796                    'compiler' => 'UPCCOMPILE',
797                    'compile_flag' => '-c',
798                    'output_flag' => '-o',
799                    'lder' => 'UPCLD',
800                    'ld' => '$(UPC)',
801                    'pure' => 1,
802                    'extensions' => ['.upc']);
804 # Headers.
805 register_language ('name' => 'header',
806                    'Name' => 'Header',
807                    'extensions' => ['.h', '.H', '.hxx', '.h++', '.hh',
808                                     '.hpp', '.inc'],
809                    # No output.
810                    'output_extensions' => sub { return () },
811                    # Nothing to do.
812                    '_finish' => sub { });
814 # Vala
815 register_language ('name' => 'vala',
816                    'Name' => 'Vala',
817                    'config_vars' => ['VALAC'],
818                    'flags' => ['VALAFLAGS'],
819                    'compile' => '$(VALAC) $(AM_VALAFLAGS) $(VALAFLAGS)',
820                    'ccer' => 'VALAC',
821                    'compiler' => 'VALACOMPILE',
822                    'extensions' => ['.vala'],
823                    'output_extensions' => sub { (my $ext = $_[0]) =~ s/vala$/c/;
824                                                 return ($ext,) },
825                    'rule_file' => 'vala',
826                    '_finish' => \&lang_vala_finish,
827                    '_target_hook' => \&lang_vala_target_hook,
828                    'nodist_specific' => 1);
830 # Yacc (C & C++).
831 register_language ('name' => 'yacc',
832                    'Name' => 'Yacc',
833                    'config_vars' => ['YACC'],
834                    'flags' => ['YFLAGS'],
835                    'compile' => '$(YACC) $(YFLAGS) $(AM_YFLAGS)',
836                    'ccer' => 'YACC',
837                    'compiler' => 'YACCCOMPILE',
838                    'extensions' => ['.y'],
839                    'output_extensions' => sub { (my $ext = $_[0]) =~ tr/y/c/;
840                                                 return ($ext,) },
841                    'rule_file' => 'yacc',
842                    '_finish' => \&lang_yacc_finish,
843                    '_target_hook' => \&lang_yacc_target_hook,
844                    'nodist_specific' => 1);
845 register_language ('name' => 'yaccxx',
846                    'Name' => 'Yacc (C++)',
847                    'config_vars' => ['YACC'],
848                    'rule_file' => 'yacc',
849                    'flags' => ['YFLAGS'],
850                    'ccer' => 'YACC',
851                    'compiler' => 'YACCCOMPILE',
852                    'compile' => '$(YACC) $(YFLAGS) $(AM_YFLAGS)',
853                    'extensions' => ['.y++', '.yy', '.yxx', '.ypp'],
854                    'output_extensions' => sub { (my $ext = $_[0]) =~ tr/y/c/;
855                                                 return ($ext,) },
856                    '_finish' => \&lang_yacc_finish,
857                    '_target_hook' => \&lang_yacc_target_hook,
858                    'nodist_specific' => 1);
860 # Lex (C & C++).
861 register_language ('name' => 'lex',
862                    'Name' => 'Lex',
863                    'config_vars' => ['LEX'],
864                    'rule_file' => 'lex',
865                    'flags' => ['LFLAGS'],
866                    'compile' => '$(LEX) $(LFLAGS) $(AM_LFLAGS)',
867                    'ccer' => 'LEX',
868                    'compiler' => 'LEXCOMPILE',
869                    'extensions' => ['.l'],
870                    'output_extensions' => sub { (my $ext = $_[0]) =~ tr/l/c/;
871                                                 return ($ext,) },
872                    '_finish' => \&lang_lex_finish,
873                    '_target_hook' => \&lang_lex_target_hook,
874                    'nodist_specific' => 1);
875 register_language ('name' => 'lexxx',
876                    'Name' => 'Lex (C++)',
877                    'config_vars' => ['LEX'],
878                    'rule_file' => 'lex',
879                    'flags' => ['LFLAGS'],
880                    'compile' => '$(LEX) $(LFLAGS) $(AM_LFLAGS)',
881                    'ccer' => 'LEX',
882                    'compiler' => 'LEXCOMPILE',
883                    'extensions' => ['.l++', '.ll', '.lxx', '.lpp'],
884                    'output_extensions' => sub { (my $ext = $_[0]) =~ tr/l/c/;
885                                                 return ($ext,) },
886                    '_finish' => \&lang_lex_finish,
887                    '_target_hook' => \&lang_lex_target_hook,
888                    'nodist_specific' => 1);
890 # Assembler.
891 register_language ('name' => 'asm',
892                    'Name' => 'Assembler',
893                    'config_vars' => ['CCAS', 'CCASFLAGS'],
895                    'flags' => ['CCASFLAGS'],
896                    # Users can set AM_CCASFLAGS to include DEFS, INCLUDES,
897                    # or anything else required.  They can also set CCAS.
898                    # Or simply use Preprocessed Assembler.
899                    'compile' => '$(CCAS) $(AM_CCASFLAGS) $(CCASFLAGS)',
900                    'ccer' => 'CCAS',
901                    'compiler' => 'CCASCOMPILE',
902                    'compile_flag' => '-c',
903                    'output_flag' => '-o',
904                    'extensions' => ['.s'],
906                    # With assembly we still use the C linker.
907                    '_finish' => \&lang_c_finish);
909 # Preprocessed Assembler.
910 register_language ('name' => 'cppasm',
911                    'Name' => 'Preprocessed Assembler',
912                    'config_vars' => ['CCAS', 'CCASFLAGS'],
914                    'autodep' => 'CCAS',
915                    'flags' => ['CCASFLAGS', 'CPPFLAGS'],
916                    'compile' => '$(CCAS) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CCASFLAGS) $(CCASFLAGS)',
917                    'ccer' => 'CPPAS',
918                    'compiler' => 'CPPASCOMPILE',
919                    'compile_flag' => '-c',
920                    'output_flag' => '-o',
921                    'extensions' => ['.S', '.sx'],
923                    # With assembly we still use the C linker.
924                    '_finish' => \&lang_c_finish);
926 # Fortran 77
927 register_language ('name' => 'f77',
928                    'Name' => 'Fortran 77',
929                    'config_vars' => ['F77'],
930                    'linker' => 'F77LINK',
931                    'link' => '$(F77LD) $(AM_FFLAGS) $(FFLAGS) $(AM_LDFLAGS) $(LDFLAGS) -o $@',
932                    'flags' => ['FFLAGS'],
933                    'compile' => '$(F77) $(AM_FFLAGS) $(FFLAGS)',
934                    'ccer' => 'F77',
935                    'compiler' => 'F77COMPILE',
936                    'compile_flag' => '-c',
937                    'output_flag' => '-o',
938                    'libtool_tag' => 'F77',
939                    'lder' => 'F77LD',
940                    'ld' => '$(F77)',
941                    'pure' => 1,
942                    'extensions' => ['.f', '.for']);
944 # Fortran
945 register_language ('name' => 'fc',
946                    'Name' => 'Fortran',
947                    'config_vars' => ['FC'],
948                    'linker' => 'FCLINK',
949                    'link' => '$(FCLD) $(AM_FCFLAGS) $(FCFLAGS) $(AM_LDFLAGS) $(LDFLAGS) -o $@',
950                    'flags' => ['FCFLAGS'],
951                    'compile' => '$(FC) $(AM_FCFLAGS) $(FCFLAGS)',
952                    'ccer' => 'FC',
953                    'compiler' => 'FCCOMPILE',
954                    'compile_flag' => '-c',
955                    'output_flag' => '-o',
956                    'libtool_tag' => 'FC',
957                    'lder' => 'FCLD',
958                    'ld' => '$(FC)',
959                    'pure' => 1,
960                    'extensions' => ['.f90', '.f95', '.f03', '.f08']);
962 # Preprocessed Fortran
963 register_language ('name' => 'ppfc',
964                    'Name' => 'Preprocessed Fortran',
965                    'config_vars' => ['FC'],
966                    'linker' => 'FCLINK',
967                    'link' => '$(FCLD) $(AM_FCFLAGS) $(FCFLAGS) $(AM_LDFLAGS) $(LDFLAGS) -o $@',
968                    'lder' => 'FCLD',
969                    'ld' => '$(FC)',
970                    'flags' => ['FCFLAGS', 'CPPFLAGS'],
971                    'ccer' => 'PPFC',
972                    'compiler' => 'PPFCCOMPILE',
973                    'compile' => '$(FC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_FCFLAGS) $(FCFLAGS)',
974                    'compile_flag' => '-c',
975                    'output_flag' => '-o',
976                    'libtool_tag' => 'FC',
977                    'pure' => 1,
978                    'extensions' => ['.F90','.F95', '.F03', '.F08']);
980 # Preprocessed Fortran 77
982 # The current support for preprocessing Fortran 77 just involves
983 # passing `$(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS)
984 # $(CPPFLAGS)' as additional flags to the Fortran 77 compiler, since
985 # this is how GNU Make does it; see the `GNU Make Manual, Edition 0.51
986 # for `make' Version 3.76 Beta' (specifically, from info file
987 # `(make)Catalogue of Rules').
989 # A better approach would be to write an Autoconf test
990 # (i.e. AC_PROG_FPP) for a Fortran 77 preprocessor, because not all
991 # Fortran 77 compilers know how to do preprocessing.  The Autoconf
992 # macro AC_PROG_FPP should test the Fortran 77 compiler first for
993 # preprocessing capabilities, and then fall back on cpp (if cpp were
994 # available).
995 register_language ('name' => 'ppf77',
996                    'Name' => 'Preprocessed Fortran 77',
997                    'config_vars' => ['F77'],
998                    'linker' => 'F77LINK',
999                    'link' => '$(F77LD) $(AM_FFLAGS) $(FFLAGS) $(AM_LDFLAGS) $(LDFLAGS) -o $@',
1000                    'lder' => 'F77LD',
1001                    'ld' => '$(F77)',
1002                    'flags' => ['FFLAGS', 'CPPFLAGS'],
1003                    'ccer' => 'PPF77',
1004                    'compiler' => 'PPF77COMPILE',
1005                    'compile' => '$(F77) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_FFLAGS) $(FFLAGS)',
1006                    'compile_flag' => '-c',
1007                    'output_flag' => '-o',
1008                    'libtool_tag' => 'F77',
1009                    'pure' => 1,
1010                    'extensions' => ['.F']);
1012 # Ratfor.
1013 register_language ('name' => 'ratfor',
1014                    'Name' => 'Ratfor',
1015                    'config_vars' => ['F77'],
1016                    'linker' => 'F77LINK',
1017                    'link' => '$(F77LD) $(AM_FFLAGS) $(FFLAGS) $(AM_LDFLAGS) $(LDFLAGS) -o $@',
1018                    'lder' => 'F77LD',
1019                    'ld' => '$(F77)',
1020                    'flags' => ['RFLAGS', 'FFLAGS'],
1021                    # FIXME also FFLAGS.
1022                    'compile' => '$(F77) $(AM_FFLAGS) $(FFLAGS) $(AM_RFLAGS) $(RFLAGS)',
1023                    'ccer' => 'F77',
1024                    'compiler' => 'RCOMPILE',
1025                    'compile_flag' => '-c',
1026                    'output_flag' => '-o',
1027                    'libtool_tag' => 'F77',
1028                    'pure' => 1,
1029                    'extensions' => ['.r']);
1031 # Java via gcj.
1032 register_language ('name' => 'java',
1033                    'Name' => 'Java',
1034                    'config_vars' => ['GCJ'],
1035                    'linker' => 'GCJLINK',
1036                    'link' => '$(GCJLD) $(AM_GCJFLAGS) $(GCJFLAGS) $(AM_LDFLAGS) $(LDFLAGS) -o $@',
1037                    'autodep' => 'GCJ',
1038                    'flags' => ['GCJFLAGS'],
1039                    'compile' => '$(GCJ) $(AM_GCJFLAGS) $(GCJFLAGS)',
1040                    'ccer' => 'GCJ',
1041                    'compiler' => 'GCJCOMPILE',
1042                    'compile_flag' => '-c',
1043                    'output_flag' => '-o',
1044                    'libtool_tag' => 'GCJ',
1045                    'lder' => 'GCJLD',
1046                    'ld' => '$(GCJ)',
1047                    'pure' => 1,
1048                    'extensions' => ['.java', '.class', '.zip', '.jar']);
1050 ################################################################
1052 # Error reporting functions.
1054 # err_am ($MESSAGE, [%OPTIONS])
1055 # -----------------------------
1056 # Uncategorized errors about the current Makefile.am.
1057 sub err_am ($;%)
1059   msg_am ('error', @_);
1062 # err_ac ($MESSAGE, [%OPTIONS])
1063 # -----------------------------
1064 # Uncategorized errors about configure.ac.
1065 sub err_ac ($;%)
1067   msg_ac ('error', @_);
1070 # msg_am ($CHANNEL, $MESSAGE, [%OPTIONS])
1071 # ---------------------------------------
1072 # Messages about about the current Makefile.am.
1073 sub msg_am ($$;%)
1075   my ($channel, $msg, %opts) = @_;
1076   msg $channel, "${am_file}.am", $msg, %opts;
1079 # msg_ac ($CHANNEL, $MESSAGE, [%OPTIONS])
1080 # ---------------------------------------
1081 # Messages about about configure.ac.
1082 sub msg_ac ($$;%)
1084   my ($channel, $msg, %opts) = @_;
1085   msg $channel, $configure_ac, $msg, %opts;
1088 ################################################################
1090 # subst ($TEXT)
1091 # -------------
1092 # Return a configure-style substitution using the indicated text.
1093 # We do this to avoid having the substitutions directly in automake.in;
1094 # when we do that they are sometimes removed and this causes confusion
1095 # and bugs.
1096 sub subst ($)
1098     my ($text) = @_;
1099     return '@' . $text . '@';
1102 ################################################################
1105 # $BACKPATH
1106 # &backname ($REL-DIR)
1107 # --------------------
1108 # If I `cd $REL-DIR', then to come back, I should `cd $BACKPATH'.
1109 # For instance `src/foo' => `../..'.
1110 # Works with non strictly increasing paths, i.e., `src/../lib' => `..'.
1111 sub backname ($)
1113     my ($file) = @_;
1114     my @res;
1115     foreach (split (/\//, $file))
1116     {
1117         next if $_ eq '.' || $_ eq '';
1118         if ($_ eq '..')
1119         {
1120             pop @res
1121               or prog_error ("trying to reverse path `$file' pointing outside tree");
1122         }
1123         else
1124         {
1125             push (@res, '..');
1126         }
1127     }
1128     return join ('/', @res) || '.';
1131 ################################################################
1133 # `silent-rules' mode handling functions.
1135 # verbose_var (NAME)
1136 # ------------------
1137 # The public variable stem used to implement `silent-rules'.
1138 sub verbose_var ($)
1140     my ($name) = @_;
1141     return 'AM_V_' . $name;
1144 # verbose_private_var (NAME)
1145 # --------------------------
1146 # The naming policy for the private variables for `silent-rules'.
1147 sub verbose_private_var ($)
1149     my ($name) = @_;
1150     return 'am__v_' . $name;
1153 # define_verbose_var (NAME, VAL)
1154 # ------------------------------
1155 # For `silent-rules' mode, setup VAR and dispatcher, to expand to VAL if silent.
1156 sub define_verbose_var ($$)
1158     my ($name, $val) = @_;
1159     my $var = verbose_var ($name);
1160     my $pvar = verbose_private_var ($name);
1161     if (option 'silent-rules')
1162       {
1163         # Using `$V' instead of `$(V)' breaks IRIX make.
1164         define_variable ($var, '$(' . $pvar . '_$(V))', INTERNAL);
1165         define_variable ($pvar . '_', '$(' . $pvar . '_$(AM_DEFAULT_VERBOSITY))', INTERNAL);
1166         define_variable ($pvar . '_0', $val, INTERNAL);
1167       }
1170 # Above should not be needed in the general automake code.
1172 # verbose_flag (NAME)
1173 # -------------------
1174 # Contents of %VERBOSE%: variable to expand before rule command.
1175 sub verbose_flag ($)
1177     my ($name) = @_;
1178     return '$(' . verbose_var ($name) . ')'
1179       if (option 'silent-rules');
1180     return '';
1183 # silent_flag
1184 # -----------
1185 # Contents of %SILENT%: variable to expand to `@' when silent.
1186 sub silent_flag ()
1188     return verbose_flag ('at');
1191 # define_verbose_tagvar (NAME)
1192 # ----------------------------
1193 # Engage the needed `silent-rules' machinery for tag NAME.
1194 sub define_verbose_tagvar ($)
1196     my ($name) = @_;
1197     if (option 'silent-rules')
1198       {
1199         define_verbose_var ($name, '@echo "  '. $name . ' ' x (6 - length ($name)) . '" $@;');
1200         define_verbose_var ('at', '@');
1201       }
1204 # define_verbose_libtool
1205 # ----------------------
1206 # Engage the needed `silent-rules' machinery for `libtool --silent'.
1207 sub define_verbose_libtool ()
1209     define_verbose_var ('lt', '--silent');
1210     return verbose_flag ('lt');
1214 ################################################################
1217 # Handle AUTOMAKE_OPTIONS variable.  Return 1 on error, 0 otherwise.
1218 sub handle_options
1220   my $var = var ('AUTOMAKE_OPTIONS');
1221   if ($var)
1222     {
1223       if ($var->has_conditional_contents)
1224         {
1225           msg_var ('unsupported', $var,
1226                    "`AUTOMAKE_OPTIONS' cannot have conditional contents");
1227         }
1228       foreach my $locvals ($var->value_as_list_recursive (cond_filter => TRUE,
1229                                                           location => 1))
1230         {
1231           my ($loc, $value) = @$locvals;
1232           return 1 if (process_option_list ($loc, $value))
1233         }
1234     }
1236   # Override portability-recursive warning.
1237   switch_warning ('no-portability-recursive')
1238     if option 'silent-rules';
1240   if ($strictness == GNITS)
1241     {
1242       set_option ('readme-alpha', INTERNAL);
1243       set_option ('std-options', INTERNAL);
1244       set_option ('check-news', INTERNAL);
1245     }
1247   return 0;
1250 # shadow_unconditionally ($varname, $where)
1251 # -----------------------------------------
1252 # Return a $(variable) that contains all possible values
1253 # $varname can take.
1254 # If the VAR wasn't defined conditionally, return $(VAR).
1255 # Otherwise we create an am__VAR_DIST variable which contains
1256 # all possible values, and return $(am__VAR_DIST).
1257 sub shadow_unconditionally ($$)
1259   my ($varname, $where) = @_;
1260   my $var = var $varname;
1261   if ($var->has_conditional_contents)
1262     {
1263       $varname = "am__${varname}_DIST";
1264       my @files = uniq ($var->value_as_list_recursive);
1265       define_pretty_variable ($varname, TRUE, $where, @files);
1266     }
1267   return "\$($varname)"
1270 # get_object_extension ($EXTENSION)
1271 # ---------------------------------
1272 # Prefix $EXTENSION with $U if ansi2knr is in use.
1273 sub get_object_extension ($)
1275     my ($extension) = @_;
1277     # Check for automatic de-ANSI-fication.
1278     $extension = '$U' . $extension
1279       if option 'ansi2knr';
1281     $get_object_extension_was_run = 1;
1283     return $extension;
1286 # check_user_variables (@LIST)
1287 # ----------------------------
1288 # Make sure each variable VAR in @LIST does not exist, suggest using AM_VAR
1289 # otherwise.
1290 sub check_user_variables (@)
1292   my @dont_override = @_;
1293   foreach my $flag (@dont_override)
1294     {
1295       my $var = var $flag;
1296       if ($var)
1297         {
1298           for my $cond ($var->conditions->conds)
1299             {
1300               if ($var->rdef ($cond)->owner == VAR_MAKEFILE)
1301                 {
1302                   msg_cond_var ('gnu', $cond, $flag,
1303                                 "`$flag' is a user variable, "
1304                                 . "you should not override it;\n"
1305                                 . "use `AM_$flag' instead.");
1306                 }
1307             }
1308         }
1309     }
1312 # Call finish function for each language that was used.
1313 sub handle_languages
1315     if (! option 'no-dependencies')
1316     {
1317         # Include auto-dep code.  Don't include it if DEP_FILES would
1318         # be empty.
1319         if (&saw_sources_p (0) && keys %dep_files)
1320         {
1321             # Set location of depcomp.
1322             &define_variable ('depcomp',
1323                               "\$(SHELL) $am_config_aux_dir/depcomp",
1324                               INTERNAL);
1325             &define_variable ('am__depfiles_maybe', 'depfiles', INTERNAL);
1327             require_conf_file ("$am_file.am", FOREIGN, 'depcomp');
1329             my @deplist = sort keys %dep_files;
1330             # Generate each `include' individually.  Irix 6 make will
1331             # not properly include several files resulting from a
1332             # variable expansion; generating many separate includes
1333             # seems safest.
1334             $output_rules .= "\n";
1335             foreach my $iter (@deplist)
1336             {
1337                 $output_rules .= (subst ('AMDEP_TRUE')
1338                                   . subst ('am__include')
1339                                   . ' '
1340                                   . subst ('am__quote')
1341                                   . $iter
1342                                   . subst ('am__quote')
1343                                   . "\n");
1344             }
1346             # Compute the set of directories to remove in distclean-depend.
1347             my @depdirs = uniq (map { dirname ($_) } @deplist);
1348             $output_rules .= &file_contents ('depend',
1349                                              new Automake::Location,
1350                                              DEPDIRS => "@depdirs");
1351         }
1352     }
1353     else
1354     {
1355         &define_variable ('depcomp', '', INTERNAL);
1356         &define_variable ('am__depfiles_maybe', '', INTERNAL);
1357     }
1359     my %done;
1361     # Is the c linker needed?
1362     my $needs_c = 0;
1363     foreach my $ext (sort keys %extension_seen)
1364     {
1365         next unless $extension_map{$ext};
1367         my $lang = $languages{$extension_map{$ext}};
1369         my $rule_file = $lang->rule_file || 'depend2';
1371         # Get information on $LANG.
1372         my $pfx = $lang->autodep;
1373         my $fpfx = ($pfx eq '') ? 'CC' : $pfx;
1375         my ($AMDEP, $FASTDEP) =
1376           (option 'no-dependencies' || $lang->autodep eq 'no')
1377           ? ('FALSE', 'FALSE') : ('AMDEP', "am__fastdep$fpfx");
1379         my $verbose = verbose_flag ($lang->ccer || 'GEN');
1380         my $silent = silent_flag ();
1382         my %transform = ('EXT'     => $ext,
1383                          'PFX'     => $pfx,
1384                          'FPFX'    => $fpfx,
1385                          'AMDEP'   => $AMDEP,
1386                          'FASTDEP' => $FASTDEP,
1387                          '-c'      => $lang->compile_flag || '',
1388                          # These are not used, but they need to be defined
1389                          # so &transform do not complain.
1390                          SUBDIROBJ     => 0,
1391                          'DERIVED-EXT' => 'BUG',
1392                          DIST_SOURCE   => 1,
1393                          VERBOSE   => $verbose,
1394                          SILENT    => $silent,
1395                         );
1397         # Generate the appropriate rules for this extension.
1398         if (((! option 'no-dependencies') && $lang->autodep ne 'no')
1399             || defined $lang->compile)
1400         {
1401             # Some C compilers don't support -c -o.  Use it only if really
1402             # needed.
1403             my $output_flag = $lang->output_flag || '';
1404             $output_flag = '-o'
1405               if (! $output_flag
1406                   && $lang->name eq 'c'
1407                   && option 'subdir-objects');
1409             # Compute a possible derived extension.
1410             # This is not used by depend2.am.
1411             my $der_ext = (&{$lang->output_extensions} ($ext))[0];
1413             # When we output an inference rule like `.c.o:' we
1414             # have two cases to consider: either subdir-objects
1415             # is used, or it is not.
1416             #
1417             # In the latter case the rule is used to build objects
1418             # in the current directory, and dependencies always
1419             # go into `./$(DEPDIR)/'.  We can hard-code this value.
1420             #
1421             # In the former case the rule can be used to build
1422             # objects in sub-directories too.  Dependencies should
1423             # go into the appropriate sub-directories, e.g.,
1424             # `sub/$(DEPDIR)/'.  The value of this directory
1425             # needs to be computed on-the-fly.
1426             #
1427             # DEPBASE holds the name of this directory, plus the
1428             # basename part of the object file (extensions Po, TPo,
1429             # Plo, TPlo will be added later as appropriate).  It is
1430             # either hardcoded, or a shell variable (`$depbase') that
1431             # will be computed by the rule.
1432             my $depbase =
1433               option ('subdir-objects') ? '$$depbase' : '$(DEPDIR)/$*';
1434             $output_rules .=
1435               file_contents ($rule_file,
1436                              new Automake::Location,
1437                              %transform,
1438                              GENERIC   => 1,
1440                              'DERIVED-EXT' => $der_ext,
1442                              DEPBASE   => $depbase,
1443                              BASE      => '$*',
1444                              SOURCE    => '$<',
1445                              SOURCEFLAG => $sourceflags{$ext} || '',
1446                              OBJ       => '$@',
1447                              OBJOBJ    => '$@',
1448                              LTOBJ     => '$@',
1450                              COMPILE   => '$(' . $lang->compiler . ')',
1451                              LTCOMPILE => '$(LT' . $lang->compiler . ')',
1452                              -o        => $output_flag,
1453                              SUBDIROBJ => !! option 'subdir-objects');
1454         }
1456         # Now include code for each specially handled object with this
1457         # language.
1458         my %seen_files = ();
1459         foreach my $file (@{$lang_specific_files{$lang->name}})
1460         {
1461             my ($derived, $source, $obj, $myext, $srcext, %file_transform) = @$file;
1463             # We might see a given object twice, for instance if it is
1464             # used under different conditions.
1465             next if defined $seen_files{$obj};
1466             $seen_files{$obj} = 1;
1468             prog_error ("found " . $lang->name .
1469                         " in handle_languages, but compiler not defined")
1470               unless defined $lang->compile;
1472             my $obj_compile = $lang->compile;
1474             # Rewrite each occurrence of `AM_$flag' in the compile
1475             # rule into `${derived}_$flag' if it exists.
1476             for my $flag (@{$lang->flags})
1477               {
1478                 my $val = "${derived}_$flag";
1479                 $obj_compile =~ s/\(AM_$flag\)/\($val\)/
1480                   if set_seen ($val);
1481               }
1483             my $libtool_tag = '';
1484             if ($lang->libtool_tag && exists $libtool_tags{$lang->libtool_tag})
1485               {
1486                 $libtool_tag = '--tag=' . $lang->libtool_tag . ' '
1487               }
1489             my $ptltflags = "${derived}_LIBTOOLFLAGS";
1490             $ptltflags = 'AM_LIBTOOLFLAGS' unless set_seen $ptltflags;
1492             my $ltverbose = define_verbose_libtool ();
1493             my $obj_ltcompile =
1494               "\$(LIBTOOL) $ltverbose $libtool_tag\$($ptltflags) \$(LIBTOOLFLAGS) "
1495               . "--mode=compile $obj_compile";
1497             # We _need_ `-o' for per object rules.
1498             my $output_flag = $lang->output_flag || '-o';
1500             my $depbase = dirname ($obj);
1501             $depbase = ''
1502                 if $depbase eq '.';
1503             $depbase .= '/'
1504                 unless $depbase eq '';
1505             $depbase .= '$(DEPDIR)/' . basename ($obj);
1507             # Support for deansified files in subdirectories is ugly
1508             # enough to deserve an explanation.
1509             #
1510             # A Note about normal ansi2knr processing first.  On
1511             #
1512             #   AUTOMAKE_OPTIONS = ansi2knr
1513             #   bin_PROGRAMS = foo
1514             #   foo_SOURCES = foo.c
1515             #
1516             # we generate rules similar to:
1517             #
1518             #   foo: foo$U.o; link ...
1519             #   foo$U.o: foo$U.c; compile ...
1520             #   foo_.c: foo.c; ansi2knr ...
1521             #
1522             # this is fairly compact, and will call ansi2knr depending
1523             # on the value of $U (`' or `_').
1524             #
1525             # It's harder with subdir sources. On
1526             #
1527             #   AUTOMAKE_OPTIONS = ansi2knr
1528             #   bin_PROGRAMS = foo
1529             #   foo_SOURCES = sub/foo.c
1530             #
1531             # we have to create foo_.c in the current directory.
1532             # (Unless the user asks 'subdir-objects'.)  This is important
1533             # in case the same file (`foo.c') is compiled from other
1534             # directories with different cpp options: foo_.c would
1535             # be preprocessed for only one set of options if it were
1536             # put in the subdirectory.
1537             #
1538             # Because foo$U.o must be built from either foo_.c or
1539             # sub/foo.c we can't be as concise as in the first example.
1540             # Instead we output
1541             #
1542             #   foo: foo$U.o; link ...
1543             #   foo_.o: foo_.c; compile ...
1544             #   foo.o: sub/foo.c; compile ...
1545             #   foo_.c: foo.c; ansi2knr ...
1546             #
1547             # This is why we'll now transform $rule_file twice
1548             # if we detect this case.
1549             # A first time we output the compile rule with `$U'
1550             # replaced by `_' and the source directory removed,
1551             # and another time we simply remove `$U'.
1552             #
1553             # Note that at this point $source (as computed by
1554             # &handle_single_transform) is `sub/foo$U.c'.
1555             # This can be confusing: it can be used as-is when
1556             # subdir-objects is set, otherwise you have to know
1557             # it really means `foo_.c' or `sub/foo.c'.
1558             my $objdir = dirname ($obj);
1559             my $srcdir = dirname ($source);
1560             if ($lang->ansi && $obj =~ /\$U/)
1561               {
1562                 prog_error "`$obj' contains \$U, but `$source' doesn't."
1563                   if $source !~ /\$U/;
1565                 (my $source_ = $source) =~ s/\$U/_/g;
1566                 # Output an additional rule if _.c and .c are not in
1567                 # the same directory.  (_.c is always in $objdir.)
1568                 if ($objdir ne $srcdir)
1569                   {
1570                     (my $obj_ = $obj) =~ s/\$U/_/g;
1571                     (my $depbase_ = $depbase) =~ s/\$U/_/g;
1572                     $source_ = basename ($source_);
1574                     $output_rules .=
1575                       file_contents ($rule_file,
1576                                      new Automake::Location,
1577                                      %transform,
1578                                      GENERIC   => 0,
1580                                      DEPBASE   => $depbase_,
1581                                      BASE      => $obj_,
1582                                      SOURCE    => $source_,
1583                                      SOURCEFLAG => $sourceflags{$srcext} || '',
1584                                      OBJ       => "$obj_$myext",
1585                                      OBJOBJ    => "$obj_.obj",
1586                                      LTOBJ     => "$obj_.lo",
1588                                      COMPILE   => $obj_compile,
1589                                      LTCOMPILE => $obj_ltcompile,
1590                                      -o        => $output_flag,
1591                                      %file_transform);
1592                     $obj =~ s/\$U//g;
1593                     $depbase =~ s/\$U//g;
1594                     $source =~ s/\$U//g;
1595                   }
1596               }
1598             $output_rules .=
1599               file_contents ($rule_file,
1600                              new Automake::Location,
1601                              %transform,
1602                              GENERIC   => 0,
1604                              DEPBASE   => $depbase,
1605                              BASE      => $obj,
1606                              SOURCE    => $source,
1607                              SOURCEFLAG => $sourceflags{$srcext} || '',
1608                              # Use $myext and not `.o' here, in case
1609                              # we are actually building a new source
1610                              # file -- e.g. via yacc.
1611                              OBJ       => "$obj$myext",
1612                              OBJOBJ    => "$obj.obj",
1613                              LTOBJ     => "$obj.lo",
1615                              VERBOSE   => $verbose,
1616                              SILENT    => $silent,
1617                              COMPILE   => $obj_compile,
1618                              LTCOMPILE => $obj_ltcompile,
1619                              -o        => $output_flag,
1620                              %file_transform);
1621         }
1623         # The rest of the loop is done once per language.
1624         next if defined $done{$lang};
1625         $done{$lang} = 1;
1627         # Load the language dependent Makefile chunks.
1628         my %lang = map { uc ($_) => 0 } keys %languages;
1629         $lang{uc ($lang->name)} = 1;
1630         $output_rules .= file_contents ('lang-compile',
1631                                         new Automake::Location,
1632                                         %transform, %lang);
1634         # If the source to a program consists entirely of code from a
1635         # `pure' language, for instance C++ or Fortran 77, then we
1636         # don't need the C compiler code.  However if we run into
1637         # something unusual then we do generate the C code.  There are
1638         # probably corner cases here that do not work properly.
1639         # People linking Java code to Fortran code deserve pain.
1640         $needs_c ||= ! $lang->pure;
1642         define_compiler_variable ($lang)
1643           if ($lang->compile);
1645         define_linker_variable ($lang)
1646           if ($lang->link);
1648         require_variables ("$am_file.am", $lang->Name . " source seen",
1649                            TRUE, @{$lang->config_vars});
1651         # Call the finisher.
1652         $lang->finish;
1654         # Flags listed in `->flags' are user variables (per GNU Standards),
1655         # they should not be overridden in the Makefile...
1656         my @dont_override = @{$lang->flags};
1657         # ... and so is LDFLAGS.
1658         push @dont_override, 'LDFLAGS' if $lang->link;
1660         check_user_variables @dont_override;
1661     }
1663     # If the project is entirely C++ or entirely Fortran 77 (i.e., 1
1664     # suffix rule was learned), don't bother with the C stuff.  But if
1665     # anything else creeps in, then use it.
1666     $needs_c = 1
1667       if $need_link || suffix_rules_count > 1;
1669     if ($needs_c)
1670       {
1671         &define_compiler_variable ($languages{'c'})
1672           unless defined $done{$languages{'c'}};
1673         define_linker_variable ($languages{'c'});
1674       }
1676     # Always provide the user with `AM_V_GEN' for `silent-rules' mode.
1677     define_verbose_tagvar ('GEN');
1681 # append_exeext { PREDICATE } $MACRO
1682 # ----------------------------------
1683 # Append $(EXEEXT) to each filename in $F appearing in the Makefile
1684 # variable $MACRO if &PREDICATE($F) is true.  @substitutions@ are
1685 # ignored.
1687 # This is typically used on all filenames of *_PROGRAMS, and filenames
1688 # of TESTS that are programs.
1689 sub append_exeext (&$)
1691   my ($pred, $macro) = @_;
1693   transform_variable_recursively
1694     ($macro, $macro, 'am__EXEEXT', 0, INTERNAL,
1695      sub {
1696        my ($subvar, $val, $cond, $full_cond) = @_;
1697        # Append $(EXEEXT) unless the user did it already, or it's a
1698        # @substitution@.
1699        $val .= '$(EXEEXT)'
1700          if $val !~ /(?:\$\(EXEEXT\)$|^[@]\w+[@]$)/ && &$pred ($val);
1701        return $val;
1702      });
1706 # Check to make sure a source defined in LIBOBJS is not explicitly
1707 # mentioned.  This is a separate function (as opposed to being inlined
1708 # in handle_source_transform) because it isn't always appropriate to
1709 # do this check.
1710 sub check_libobjs_sources
1712   my ($one_file, $unxformed) = @_;
1714   foreach my $prefix ('', 'EXTRA_', 'dist_', 'nodist_',
1715                       'dist_EXTRA_', 'nodist_EXTRA_')
1716     {
1717       my @files;
1718       my $varname = $prefix . $one_file . '_SOURCES';
1719       my $var = var ($varname);
1720       if ($var)
1721         {
1722           @files = $var->value_as_list_recursive;
1723         }
1724       elsif ($prefix eq '')
1725         {
1726           @files = ($unxformed . '.c');
1727         }
1728       else
1729         {
1730           next;
1731         }
1733       foreach my $file (@files)
1734         {
1735           err_var ($prefix . $one_file . '_SOURCES',
1736                    "automatically discovered file `$file' should not" .
1737                    " be explicitly mentioned")
1738             if defined $libsources{$file};
1739         }
1740     }
1744 # @OBJECTS
1745 # handle_single_transform ($VAR, $TOPPARENT, $DERIVED, $OBJ, $FILE, %TRANSFORM)
1746 # -----------------------------------------------------------------------------
1747 # Does much of the actual work for handle_source_transform.
1748 # Arguments are:
1749 #   $VAR is the name of the variable that the source filenames come from
1750 #   $TOPPARENT is the name of the _SOURCES variable which is being processed
1751 #   $DERIVED is the name of resulting executable or library
1752 #   $OBJ is the object extension (e.g., `$U.lo')
1753 #   $FILE the source file to transform
1754 #   %TRANSFORM contains extras arguments to pass to file_contents
1755 #     when producing explicit rules
1756 # Result is a list of the names of objects
1757 # %linkers_used will be updated with any linkers needed
1758 sub handle_single_transform ($$$$$%)
1760     my ($var, $topparent, $derived, $obj, $_file, %transform) = @_;
1761     my @files = ($_file);
1762     my @result = ();
1763     my $nonansi_obj = $obj;
1764     $nonansi_obj =~ s/\$U//g;
1766     # Turn sources into objects.  We use a while loop like this
1767     # because we might add to @files in the loop.
1768     while (scalar @files > 0)
1769     {
1770         $_ = shift @files;
1772         # Configure substitutions in _SOURCES variables are errors.
1773         if (/^\@.*\@$/)
1774         {
1775           my $parent_msg = '';
1776           $parent_msg = "\nand is referred to from `$topparent'"
1777             if $topparent ne $var->name;
1778           err_var ($var,
1779                    "`" . $var->name . "' includes configure substitution `$_'"
1780                    . $parent_msg . ";\nconfigure " .
1781                    "substitutions are not allowed in _SOURCES variables");
1782           next;
1783         }
1785         # If the source file is in a subdirectory then the `.o' is put
1786         # into the current directory, unless the subdir-objects option
1787         # is in effect.
1789         # Split file name into base and extension.
1790         next if ! /^(?:(.*)\/)?([^\/]*)($KNOWN_EXTENSIONS_PATTERN)$/;
1791         my $full = $_;
1792         my $directory = $1 || '';
1793         my $base = $2;
1794         my $extension = $3;
1796         # We must generate a rule for the object if it requires its own flags.
1797         my $renamed = 0;
1798         my ($linker, $object);
1800         # This records whether we've seen a derived source file (e.g.
1801         # yacc output).
1802         my $derived_source = 0;
1804         # This holds the `aggregate context' of the file we are
1805         # currently examining.  If the file is compiled with
1806         # per-object flags, then it will be the name of the object.
1807         # Otherwise it will be `AM'.  This is used by the target hook
1808         # language function.
1809         my $aggregate = 'AM';
1811         $extension = &derive_suffix ($extension, $nonansi_obj);
1812         my $lang;
1813         if ($extension_map{$extension} &&
1814             ($lang = $languages{$extension_map{$extension}}))
1815         {
1816             # Found the language, so see what it says.
1817             &saw_extension ($extension);
1819             # Do we have per-executable flags for this executable?
1820             my $have_per_exec_flags = 0;
1821             my @peflags = @{$lang->flags};
1822             push @peflags, 'LIBTOOLFLAGS' if $nonansi_obj eq '.lo';
1823             foreach my $flag (@peflags)
1824               {
1825                 if (set_seen ("${derived}_$flag"))
1826                   {
1827                     $have_per_exec_flags = 1;
1828                     last;
1829                   }
1830               }
1832             # Note: computed subr call.  The language rewrite function
1833             # should return one of the LANG_* constants.  It could
1834             # also return a list whose first value is such a constant
1835             # and whose second value is a new source extension which
1836             # should be applied.  This means this particular language
1837             # generates another source file which we must then process
1838             # further.
1839             my $subr = \&{'lang_' . $lang->name . '_rewrite'};
1840             my ($r, $source_extension)
1841                 = &$subr ($directory, $base, $extension,
1842                           $nonansi_obj, $have_per_exec_flags, $var);
1843             # Skip this entry if we were asked not to process it.
1844             next if $r == LANG_IGNORE;
1846             # Now extract linker and other info.
1847             $linker = $lang->linker;
1849             my $this_obj_ext;
1850             if (defined $source_extension)
1851             {
1852                 $this_obj_ext = $source_extension;
1853                 $derived_source = 1;
1854             }
1855             elsif ($lang->ansi)
1856             {
1857                 $this_obj_ext = $obj;
1858             }
1859             else
1860             {
1861                 $this_obj_ext = $nonansi_obj;
1862             }
1863             $object = $base . $this_obj_ext;
1865             if ($have_per_exec_flags)
1866             {
1867                 # We have a per-executable flag in effect for this
1868                 # object.  In this case we rewrite the object's
1869                 # name to ensure it is unique.
1871                 # We choose the name `DERIVED_OBJECT' to ensure
1872                 # (1) uniqueness, and (2) continuity between
1873                 # invocations.  However, this will result in a
1874                 # name that is too long for losing systems, in
1875                 # some situations.  So we provide _SHORTNAME to
1876                 # override.
1878                 my $dname = $derived;
1879                 my $var = var ($derived . '_SHORTNAME');
1880                 if ($var)
1881                 {
1882                     # FIXME: should use the same Condition as
1883                     # the _SOURCES variable.  But this is really
1884                     # silly overkill -- nobody should have
1885                     # conditional shortnames.
1886                     $dname = $var->variable_value;
1887                 }
1888                 $object = $dname . '-' . $object;
1890                 prog_error ($lang->name . " flags defined without compiler")
1891                   if ! defined $lang->compile;
1893                 $renamed = 1;
1894             }
1896             # If rewrite said it was ok, put the object into a
1897             # subdir.
1898             if ($r == LANG_SUBDIR && $directory ne '')
1899             {
1900                 $object = $directory . '/' . $object;
1901             }
1903             # If the object file has been renamed (because per-target
1904             # flags are used) we cannot compile the file with an
1905             # inference rule: we need an explicit rule.
1906             #
1907             # If the source is in a subdirectory and the object is in
1908             # the current directory, we also need an explicit rule.
1909             #
1910             # If both source and object files are in a subdirectory
1911             # (this happens when the subdir-objects option is used),
1912             # then the inference will work.
1913             #
1914             # The latter case deserves a historical note.  When the
1915             # subdir-objects option was added on 1999-04-11 it was
1916             # thought that inferences rules would work for
1917             # subdirectory objects too.  Later, on 1999-11-22,
1918             # automake was changed to output explicit rules even for
1919             # subdir-objects.  Nobody remembers why, but this occurred
1920             # soon after the merge of the user-dep-gen-branch so it
1921             # might be related.  In late 2003 people complained about
1922             # the size of the generated Makefile.ins (libgcj, with
1923             # 2200+ subdir objects was reported to have a 9MB
1924             # Makefile), so we now rely on inference rules again.
1925             # Maybe we'll run across the same issue as in the past,
1926             # but at least this time we can document it.  However since
1927             # dependency tracking has evolved it is possible that
1928             # our old problem no longer exists.
1929             # Using inference rules for subdir-objects has been tested
1930             # with GNU make, Solaris make, Ultrix make, BSD make,
1931             # HP-UX make, and OSF1 make successfully.
1932             if ($renamed
1933                 || ($directory ne '' && ! option 'subdir-objects')
1934                 # We must also use specific rules for a nodist_ source
1935                 # if its language requests it.
1936                 || ($lang->nodist_specific && ! $transform{'DIST_SOURCE'}))
1937             {
1938                 my $obj_sans_ext = substr ($object, 0,
1939                                            - length ($this_obj_ext));
1940                 my $full_ansi;
1941                 if ($directory ne '')
1942                   {
1943                         $full_ansi = $directory . '/' . $base . $extension;
1944                   }
1945                 else
1946                   {
1947                         $full_ansi = $base . $extension;
1948                   }
1950                 if ($lang->ansi && option 'ansi2knr')
1951                   {
1952                     $full_ansi =~ s/$KNOWN_EXTENSIONS_PATTERN$/\$U$&/;
1953                     $obj_sans_ext .= '$U';
1954                   }
1956                 my @specifics = ($full_ansi, $obj_sans_ext,
1957                                  # Only use $this_obj_ext in the derived
1958                                  # source case because in the other case we
1959                                  # *don't* want $(OBJEXT) to appear here.
1960                                  ($derived_source ? $this_obj_ext : '.o'),
1961                                  $extension);
1963                 # If we renamed the object then we want to use the
1964                 # per-executable flag name.  But if this is simply a
1965                 # subdir build then we still want to use the AM_ flag
1966                 # name.
1967                 if ($renamed)
1968                   {
1969                     unshift @specifics, $derived;
1970                     $aggregate = $derived;
1971                   }
1972                 else
1973                   {
1974                     unshift @specifics, 'AM';
1975                   }
1977                 # Each item on this list is a reference to a list consisting
1978                 # of four values followed by additional transform flags for
1979                 # file_contents.   The four values are the derived flag prefix
1980                 # (e.g. for `foo_CFLAGS', it is `foo'), the name of the
1981                 # source file, the base name of the output file, and
1982                 # the extension for the object file.
1983                 push (@{$lang_specific_files{$lang->name}},
1984                       [@specifics, %transform]);
1985             }
1986         }
1987         elsif ($extension eq $nonansi_obj)
1988         {
1989             # This is probably the result of a direct suffix rule.
1990             # In this case we just accept the rewrite.
1991             $object = "$base$extension";
1992             $object = "$directory/$object" if $directory ne '';
1993             $linker = '';
1994         }
1995         else
1996         {
1997             # No error message here.  Used to have one, but it was
1998             # very unpopular.
1999             # FIXME: we could potentially do more processing here,
2000             # perhaps treating the new extension as though it were a
2001             # new source extension (as above).  This would require
2002             # more restructuring than is appropriate right now.
2003             next;
2004         }
2006         err_am "object `$object' created by `$full' and `$object_map{$object}'"
2007           if (defined $object_map{$object}
2008               && $object_map{$object} ne $full);
2010         my $comp_val = (($object =~ /\.lo$/)
2011                         ? COMPILE_LIBTOOL : COMPILE_ORDINARY);
2012         (my $comp_obj = $object) =~ s/\.lo$/.\$(OBJEXT)/;
2013         if (defined $object_compilation_map{$comp_obj}
2014             && $object_compilation_map{$comp_obj} != 0
2015             # Only see the error once.
2016             && ($object_compilation_map{$comp_obj}
2017                 != (COMPILE_LIBTOOL | COMPILE_ORDINARY))
2018             && $object_compilation_map{$comp_obj} != $comp_val)
2019           {
2020             err_am "object `$comp_obj' created both with libtool and without";
2021           }
2022         $object_compilation_map{$comp_obj} |= $comp_val;
2024         if (defined $lang)
2025         {
2026             # Let the language do some special magic if required.
2027             $lang->target_hook ($aggregate, $object, $full, %transform);
2028         }
2030         if ($derived_source)
2031           {
2032             prog_error ($lang->name . " has automatic dependency tracking")
2033               if $lang->autodep ne 'no';
2034             # Make sure this new source file is handled next.  That will
2035             # make it appear to be at the right place in the list.
2036             unshift (@files, $object);
2037             # Distribute derived sources unless the source they are
2038             # derived from is not.
2039             &push_dist_common ($object)
2040               unless ($topparent =~ /^(?:nobase_)?nodist_/);
2041             next;
2042           }
2044         $linkers_used{$linker} = 1;
2046         push (@result, $object);
2048         if (! defined $object_map{$object})
2049         {
2050             my @dep_list = ();
2051             $object_map{$object} = $full;
2053             # If resulting object is in subdir, we need to make
2054             # sure the subdir exists at build time.
2055             if ($object =~ /\//)
2056             {
2057                 # FIXME: check that $DIRECTORY is somewhere in the
2058                 # project
2060                 # For Java, the way we're handling it right now, a
2061                 # `..' component doesn't make sense.
2062                 if ($lang && $lang->name eq 'java' && $object =~ /(\/|^)\.\.\//)
2063                   {
2064                     err_am "`$full' should not contain a `..' component";
2065                   }
2067                 # Make sure object is removed by `make mostlyclean'.
2068                 $compile_clean_files{$object} = MOSTLY_CLEAN;
2069                 # If we have a libtool object then we also must remove
2070                 # the ordinary .o.
2071                 if ($object =~ /\.lo$/)
2072                 {
2073                     (my $xobj = $object) =~ s,lo$,\$(OBJEXT),;
2074                     $compile_clean_files{$xobj} = MOSTLY_CLEAN;
2076                     # Remove any libtool object in this directory.
2077                     $libtool_clean_directories{$directory} = 1;
2078                 }
2080                 push (@dep_list, require_build_directory ($directory));
2082                 # If we're generating dependencies, we also want
2083                 # to make sure that the appropriate subdir of the
2084                 # .deps directory is created.
2085                 push (@dep_list,
2086                       require_build_directory ($directory . '/$(DEPDIR)'))
2087                   unless option 'no-dependencies';
2088             }
2090             &pretty_print_rule ($object . ':', "\t", @dep_list)
2091                 if scalar @dep_list > 0;
2092         }
2094         # Transform .o or $o file into .P file (for automatic
2095         # dependency code).
2096         if ($lang && $lang->autodep ne 'no')
2097         {
2098             my $depfile = $object;
2099             $depfile =~ s/\.([^.]*)$/.P$1/;
2100             $depfile =~ s/\$\(OBJEXT\)$/o/;
2101             $dep_files{dirname ($depfile) . '/$(DEPDIR)/'
2102                          . basename ($depfile)} = 1;
2103         }
2104     }
2106     return @result;
2110 # $LINKER
2111 # define_objects_from_sources ($VAR, $OBJVAR, $NODEFINE, $ONE_FILE,
2112 #                              $OBJ, $PARENT, $TOPPARENT, $WHERE, %TRANSFORM)
2113 # ---------------------------------------------------------------------------
2114 # Define an _OBJECTS variable for a _SOURCES variable (or subvariable)
2116 # Arguments are:
2117 #   $VAR is the name of the _SOURCES variable
2118 #   $OBJVAR is the name of the _OBJECTS variable if known (otherwise
2119 #     it will be generated and returned).
2120 #   $NODEFINE is a boolean: if true, $OBJVAR will not be defined (but
2121 #     work done to determine the linker will be).
2122 #   $ONE_FILE is the canonical (transformed) name of object to build
2123 #   $OBJ is the object extension (i.e. either `.o' or `.lo').
2124 #   $TOPPARENT is the _SOURCES variable being processed.
2125 #   $WHERE context into which this definition is done
2126 #   %TRANSFORM extra arguments to pass to file_contents when producing
2127 #     rules
2129 # Result is a pair ($LINKER, $OBJVAR):
2130 #    $LINKER is a boolean, true if a linker is needed to deal with the objects
2131 sub define_objects_from_sources ($$$$$$$%)
2133   my ($var, $objvar, $nodefine, $one_file,
2134       $obj, $topparent, $where, %transform) = @_;
2136   my $needlinker = "";
2138   transform_variable_recursively
2139     ($var, $objvar, 'am__objects', $nodefine, $where,
2140      # The transform code to run on each filename.
2141      sub {
2142        my ($subvar, $val, $cond, $full_cond) = @_;
2143        my @trans = handle_single_transform ($subvar, $topparent,
2144                                             $one_file, $obj, $val,
2145                                             %transform);
2146        $needlinker = "true" if @trans;
2147        return @trans;
2148      });
2150   return $needlinker;
2154 # handle_source_transform ($CANON_TARGET, $TARGET, $OBJEXT, $WHERE, %TRANSFORM)
2155 # -----------------------------------------------------------------------------
2156 # Handle SOURCE->OBJECT transform for one program or library.
2157 # Arguments are:
2158 #   canonical (transformed) name of target to build
2159 #   actual target of object to build
2160 #   object extension (i.e., either `.o' or `$o')
2161 #   location of the source variable
2162 #   extra arguments to pass to file_contents when producing rules
2163 # Return the name of the linker variable that must be used.
2164 # Empty return means just use `LINK'.
2165 sub handle_source_transform ($$$$%)
2167     # one_file is canonical name.  unxformed is given name.  obj is
2168     # object extension.
2169     my ($one_file, $unxformed, $obj, $where, %transform) = @_;
2171     my $linker = '';
2173     # No point in continuing if _OBJECTS is defined.
2174     return if reject_var ($one_file . '_OBJECTS',
2175                           $one_file . '_OBJECTS should not be defined');
2177     my %used_pfx = ();
2178     my $needlinker;
2179     %linkers_used = ();
2180     foreach my $prefix ('', 'EXTRA_', 'dist_', 'nodist_',
2181                         'dist_EXTRA_', 'nodist_EXTRA_')
2182     {
2183         my $varname = $prefix . $one_file . "_SOURCES";
2184         my $var = var $varname;
2185         next unless $var;
2187         # We are going to define _OBJECTS variables using the prefix.
2188         # Then we glom them all together.  So we can't use the null
2189         # prefix here as we need it later.
2190         my $xpfx = ($prefix eq '') ? 'am_' : $prefix;
2192         # Keep track of which prefixes we saw.
2193         $used_pfx{$xpfx} = 1
2194           unless $prefix =~ /EXTRA_/;
2196         push @sources, "\$($varname)";
2197         push @dist_sources, shadow_unconditionally ($varname, $where)
2198           unless (option ('no-dist') || $prefix =~ /^nodist_/);
2200         $needlinker |=
2201             define_objects_from_sources ($varname,
2202                                          $xpfx . $one_file . '_OBJECTS',
2203                                          $prefix =~ /EXTRA_/,
2204                                          $one_file, $obj, $varname, $where,
2205                                          DIST_SOURCE => ($prefix !~ /^nodist_/),
2206                                          %transform);
2207     }
2208     if ($needlinker)
2209     {
2210         $linker ||= &resolve_linker (%linkers_used);
2211     }
2213     my @keys = sort keys %used_pfx;
2214     if (scalar @keys == 0)
2215     {
2216         # The default source for libfoo.la is libfoo.c, but for
2217         # backward compatibility we first look at libfoo_la.c,
2218         # if no default source suffix is given.
2219         my $old_default_source = "$one_file.c";
2220         my $ext_var = var ('AM_DEFAULT_SOURCE_EXT');
2221         my $default_source_ext = $ext_var ? variable_value ($ext_var) : '.c';
2222         msg_var ('unsupported', $ext_var, $ext_var->name . " can assume at most one value")
2223           if $default_source_ext =~ /[\t ]/;
2224         (my $default_source = $unxformed) =~ s,(\.[^./\\]*)?$,$default_source_ext,;
2225         if ($old_default_source ne $default_source
2226             && !$ext_var
2227             && (rule $old_default_source
2228                 || rule '$(srcdir)/' . $old_default_source
2229                 || rule '${srcdir}/' . $old_default_source
2230                 || -f $old_default_source))
2231           {
2232             my $loc = $where->clone;
2233             $loc->pop_context;
2234             msg ('obsolete', $loc,
2235                  "the default source for `$unxformed' has been changed "
2236                  . "to `$default_source'.\n(Using `$old_default_source' for "
2237                  . "backward compatibility.)");
2238             $default_source = $old_default_source;
2239           }
2240         # If a rule exists to build this source with a $(srcdir)
2241         # prefix, use that prefix in our variables too.  This is for
2242         # the sake of BSD Make.
2243         if (rule '$(srcdir)/' . $default_source
2244             || rule '${srcdir}/' . $default_source)
2245           {
2246             $default_source = '$(srcdir)/' . $default_source;
2247           }
2249         &define_variable ($one_file . "_SOURCES", $default_source, $where);
2250         push (@sources, $default_source);
2251         push (@dist_sources, $default_source);
2253         %linkers_used = ();
2254         my (@result) =
2255           handle_single_transform ($one_file . '_SOURCES',
2256                                    $one_file . '_SOURCES',
2257                                    $one_file, $obj,
2258                                    $default_source, %transform);
2259         $linker ||= &resolve_linker (%linkers_used);
2260         define_pretty_variable ($one_file . '_OBJECTS', TRUE, $where, @result);
2261     }
2262     else
2263     {
2264         @keys = map { '$(' . $_ . $one_file . '_OBJECTS)' } @keys;
2265         define_pretty_variable ($one_file . '_OBJECTS', TRUE, $where, @keys);
2266     }
2268     # If we want to use `LINK' we must make sure it is defined.
2269     if ($linker eq '')
2270     {
2271         $need_link = 1;
2272     }
2274     return $linker;
2278 # handle_lib_objects ($XNAME, $VAR)
2279 # ---------------------------------
2280 # Special-case ALLOCA and LIBOBJS substitutions in _LDADD or _LIBADD variables.
2281 # Also, generate _DEPENDENCIES variable if appropriate.
2282 # Arguments are:
2283 #   transformed name of object being built, or empty string if no object
2284 #   name of _LDADD/_LIBADD-type variable to examine
2285 # Returns 1 if LIBOBJS seen, 0 otherwise.
2286 sub handle_lib_objects
2288   my ($xname, $varname) = @_;
2290   my $var = var ($varname);
2291   prog_error "handle_lib_objects: `$varname' undefined"
2292     unless $var;
2293   prog_error "handle_lib_objects: unexpected variable name `$varname'"
2294     unless $varname =~ /^(.*)(?:LIB|LD)ADD$/;
2295   my $prefix = $1 || 'AM_';
2297   my $seen_libobjs = 0;
2298   my $flagvar = 0;
2300   transform_variable_recursively
2301     ($varname, $xname . '_DEPENDENCIES', 'am__DEPENDENCIES',
2302      ! $xname, INTERNAL,
2303      # Transformation function, run on each filename.
2304      sub {
2305        my ($subvar, $val, $cond, $full_cond) = @_;
2307        if ($val =~ /^-/)
2308          {
2309            # Skip -lfoo and -Ldir silently; these are explicitly allowed.
2310            if ($val !~ /^-[lL]/ &&
2311                # Skip -dlopen and -dlpreopen; these are explicitly allowed
2312                # for Libtool libraries or programs.  (Actually we are a bit
2313                # laxe here since this code also applies to non-libtool
2314                # libraries or programs, for which -dlopen and -dlopreopen
2315                # are pure nonsense.  Diagnosing this doesn't seem very
2316                # important: the developer will quickly get complaints from
2317                # the linker.)
2318                $val !~ /^-dl(?:pre)?open$/ &&
2319                # Only get this error once.
2320                ! $flagvar)
2321              {
2322                $flagvar = 1;
2323                # FIXME: should display a stack of nested variables
2324                # as context when $var != $subvar.
2325                err_var ($var, "linker flags such as `$val' belong in "
2326                         . "`${prefix}LDFLAGS");
2327              }
2328            return ();
2329          }
2330        elsif ($val !~ /^\@.*\@$/)
2331          {
2332            # Assume we have a file of some sort, and output it into the
2333            # dependency variable.  Autoconf substitutions are not output;
2334            # rarely is a new dependency substituted into e.g. foo_LDADD
2335            # -- but bad things (e.g. -lX11) are routinely substituted.
2336            # Note that LIBOBJS and ALLOCA are exceptions to this rule,
2337            # and handled specially below.
2338            return $val;
2339          }
2340        elsif ($val =~ /^\@(LT)?LIBOBJS\@$/)
2341          {
2342            handle_LIBOBJS ($subvar, $cond, $1);
2343            $seen_libobjs = 1;
2344            return $val;
2345          }
2346        elsif ($val =~ /^\@(LT)?ALLOCA\@$/)
2347          {
2348            handle_ALLOCA ($subvar, $cond, $1);
2349            return $val;
2350          }
2351        else
2352          {
2353            return ();
2354          }
2355      });
2357   return $seen_libobjs;
2360 # handle_LIBOBJS_or_ALLOCA ($VAR)
2361 # -------------------------------
2362 # Definitions common to LIBOBJS and ALLOCA.
2363 # VAR should be one of LIBOBJS, LTLIBOBJS, ALLOCA, or LTALLOCA.
2364 sub handle_LIBOBJS_or_ALLOCA ($)
2366   my ($var) = @_;
2368   my $dir = '';
2370   # If LIBOBJS files must be built in another directory we have
2371   # to define LIBOBJDIR and ensure the files get cleaned.
2372   # Otherwise LIBOBJDIR can be left undefined, and the cleaning
2373   # is achieved by `rm -f *.$(OBJEXT)' in compile.am.
2374   if ($config_libobj_dir
2375       && $relative_dir ne $config_libobj_dir)
2376     {
2377       if (option 'subdir-objects')
2378         {
2379           # In the top-level Makefile we do not use $(top_builddir), because
2380           # we are already there, and since the targets are built without
2381           # a $(top_builddir), it helps BSD Make to match them with
2382           # dependencies.
2383           $dir = "$config_libobj_dir/" if $config_libobj_dir ne '.';
2384           $dir = "$topsrcdir/$dir" if $relative_dir ne '.';
2385           define_variable ('LIBOBJDIR', "$dir", INTERNAL);
2386           $clean_files{"\$($var)"} = MOSTLY_CLEAN;
2387           # If LTLIBOBJS is used, we must also clear LIBOBJS (which might
2388           # be created by libtool as a side-effect of creating LTLIBOBJS).
2389           $clean_files{"\$($var)"} = MOSTLY_CLEAN if $var =~ s/^LT//;
2390         }
2391       else
2392         {
2393           error ("`\$($var)' cannot be used outside `$config_libobj_dir' if"
2394                  . " `subdir-objects' is not set");
2395         }
2396     }
2398   return $dir;
2401 sub handle_LIBOBJS ($$$)
2403   my ($var, $cond, $lt) = @_;
2404   my $myobjext = $lt ? 'lo' : 'o';
2405   $lt ||= '';
2407   $var->requires_variables ("\@${lt}LIBOBJS\@ used", $lt . 'LIBOBJS')
2408     if ! keys %libsources;
2410   my $dir = handle_LIBOBJS_or_ALLOCA "${lt}LIBOBJS";
2412   foreach my $iter (keys %libsources)
2413     {
2414       if ($iter =~ /\.[cly]$/)
2415         {
2416           &saw_extension ($&);
2417           &saw_extension ('.c');
2418         }
2420       if ($iter =~ /\.h$/)
2421         {
2422           require_libsource_with_macro ($cond, $var, FOREIGN, $iter);
2423         }
2424       elsif ($iter ne 'alloca.c')
2425         {
2426           my $rewrite = $iter;
2427           $rewrite =~ s/\.c$/.P$myobjext/;
2428           $dep_files{$dir . '$(DEPDIR)/' . $rewrite} = 1;
2429           $rewrite = "^" . quotemeta ($iter) . "\$";
2430           # Only require the file if it is not a built source.
2431           my $bs = var ('BUILT_SOURCES');
2432           if (! $bs || ! grep (/$rewrite/, $bs->value_as_list_recursive))
2433             {
2434               require_libsource_with_macro ($cond, $var, FOREIGN, $iter);
2435             }
2436         }
2437     }
2440 sub handle_ALLOCA ($$$)
2442   my ($var, $cond, $lt) = @_;
2443   my $myobjext = $lt ? 'lo' : 'o';
2444   $lt ||= '';
2445   my $dir = handle_LIBOBJS_or_ALLOCA "${lt}ALLOCA";
2447   $var->requires_variables ("\@${lt}ALLOCA\@ used", $lt . 'ALLOCA');
2448   $dep_files{$dir . '$(DEPDIR)/alloca.P' . $myobjext} = 1;
2449   require_libsource_with_macro ($cond, $var, FOREIGN, 'alloca.c');
2450   &saw_extension ('.c');
2453 # Canonicalize the input parameter
2454 sub canonicalize
2456     my ($string) = @_;
2457     $string =~ tr/A-Za-z0-9_\@/_/c;
2458     return $string;
2461 # Canonicalize a name, and check to make sure the non-canonical name
2462 # is never used.  Returns canonical name.  Arguments are name and a
2463 # list of suffixes to check for.
2464 sub check_canonical_spelling
2466   my ($name, @suffixes) = @_;
2468   my $xname = &canonicalize ($name);
2469   if ($xname ne $name)
2470     {
2471       foreach my $xt (@suffixes)
2472         {
2473           reject_var ("$name$xt", "use `$xname$xt', not `$name$xt'");
2474         }
2475     }
2477   return $xname;
2481 # handle_compile ()
2482 # -----------------
2483 # Set up the compile suite.
2484 sub handle_compile ()
2486     return
2487       unless $get_object_extension_was_run;
2489     # Boilerplate.
2490     my $default_includes = '';
2491     if (! option 'nostdinc')
2492       {
2493         my @incs = ('-I.', subst ('am__isrc'));
2495         my $var = var 'CONFIG_HEADER';
2496         if ($var)
2497           {
2498             foreach my $hdr (split (' ', $var->variable_value))
2499               {
2500                 push @incs, '-I' . dirname ($hdr);
2501               }
2502           }
2503         # We want `-I. -I$(srcdir)', but the latter -I is redundant
2504         # and unaesthetic in non-VPATH builds.  We use `-I.@am__isrc@`
2505         # instead.  It will be replaced by '-I.' or '-I. -I$(srcdir)'.
2506         # Items in CONFIG_HEADER are never in $(srcdir) so it is safe
2507         # to just put @am__isrc@ right after `-I.', without a space.
2508         ($default_includes = ' ' . uniq (@incs)) =~ s/ @/@/;
2509       }
2511     my (@mostly_rms, @dist_rms);
2512     foreach my $item (sort keys %compile_clean_files)
2513     {
2514         if ($compile_clean_files{$item} == MOSTLY_CLEAN)
2515         {
2516             push (@mostly_rms, "\t-rm -f $item");
2517         }
2518         elsif ($compile_clean_files{$item} == DIST_CLEAN)
2519         {
2520             push (@dist_rms, "\t-rm -f $item");
2521         }
2522         else
2523         {
2524           prog_error 'invalid entry in %compile_clean_files';
2525         }
2526     }
2528     my ($coms, $vars, $rules) =
2529       &file_contents_internal (1, "$libdir/am/compile.am",
2530                                new Automake::Location,
2531                                ('DEFAULT_INCLUDES' => $default_includes,
2532                                 'MOSTLYRMS' => join ("\n", @mostly_rms),
2533                                 'DISTRMS' => join ("\n", @dist_rms)));
2534     $output_vars .= $vars;
2535     $output_rules .= "$coms$rules";
2537     # Check for automatic de-ANSI-fication.
2538     if (option 'ansi2knr')
2539       {
2540         my ($ansi2knr_filename, $ansi2knr_where) = @{option 'ansi2knr'};
2541         my $ansi2knr_dir = '';
2543         require_variables ($ansi2knr_where, "option `ansi2knr' is used",
2544                            TRUE, "ANSI2KNR", "U");
2546         # topdir is where ansi2knr should be.
2547         if ($ansi2knr_filename eq 'ansi2knr')
2548           {
2549             # Only require ansi2knr files if they should appear in
2550             # this directory.
2551             require_file ($ansi2knr_where, FOREIGN,
2552                           'ansi2knr.c', 'ansi2knr.1');
2554             # ansi2knr needs to be built before subdirs, so unshift it.
2555             unshift (@all, '$(ANSI2KNR)');
2556           }
2557         else
2558           {
2559             $ansi2knr_dir = dirname ($ansi2knr_filename);
2560           }
2562         $output_rules .= &file_contents ('ansi2knr',
2563                                          new Automake::Location,
2564                                          'ANSI2KNR-DIR' => $ansi2knr_dir);
2566     }
2569 # handle_libtool ()
2570 # -----------------
2571 # Handle libtool rules.
2572 sub handle_libtool
2574   return unless var ('LIBTOOL');
2576   # Libtool requires some files, but only at top level.
2577   # (Starting with Libtool 2.0 we do not have to bother.  These
2578   # requirements are done with AC_REQUIRE_AUX_FILE.)
2579   require_conf_file_with_macro (TRUE, 'LIBTOOL', FOREIGN, @libtool_files)
2580     if $relative_dir eq '.' && ! $libtool_new_api;
2582   my @libtool_rms;
2583   foreach my $item (sort keys %libtool_clean_directories)
2584     {
2585       my $dir = ($item eq '.') ? '' : "$item/";
2586       # .libs is for Unix, _libs for DOS.
2587       push (@libtool_rms, "\t-rm -rf ${dir}.libs ${dir}_libs");
2588     }
2590   check_user_variables 'LIBTOOLFLAGS';
2592   # Output the libtool compilation rules.
2593   $output_rules .= &file_contents ('libtool',
2594                                    new Automake::Location,
2595                                    LTRMS => join ("\n", @libtool_rms));
2598 # handle_programs ()
2599 # ------------------
2600 # Handle C programs.
2601 sub handle_programs
2603   my @proglist = &am_install_var ('progs', 'PROGRAMS',
2604                                   'bin', 'sbin', 'libexec', 'pkglib',
2605                                   'noinst', 'check');
2606   return if ! @proglist;
2608   my $seen_global_libobjs =
2609     var ('LDADD') && &handle_lib_objects ('', 'LDADD');
2611   foreach my $pair (@proglist)
2612     {
2613       my ($where, $one_file) = @$pair;
2615       my $seen_libobjs = 0;
2616       my $obj = get_object_extension '.$(OBJEXT)';
2618       $known_programs{$one_file} = $where;
2620       # Canonicalize names and check for misspellings.
2621       my $xname = &check_canonical_spelling ($one_file, '_LDADD', '_LDFLAGS',
2622                                              '_SOURCES', '_OBJECTS',
2623                                              '_DEPENDENCIES');
2625       $where->push_context ("while processing program `$one_file'");
2626       $where->set (INTERNAL->get);
2628       my $linker = &handle_source_transform ($xname, $one_file, $obj, $where,
2629                                              NONLIBTOOL => 1, LIBTOOL => 0);
2631       if (var ($xname . "_LDADD"))
2632         {
2633           $seen_libobjs = &handle_lib_objects ($xname, $xname . '_LDADD');
2634         }
2635       else
2636         {
2637           # User didn't define prog_LDADD override.  So do it.
2638           &define_variable ($xname . '_LDADD', '$(LDADD)', $where);
2640           # This does a bit too much work.  But we need it to
2641           # generate _DEPENDENCIES when appropriate.
2642           if (var ('LDADD'))
2643             {
2644               $seen_libobjs = &handle_lib_objects ($xname, 'LDADD');
2645             }
2646         }
2648       reject_var ($xname . '_LIBADD',
2649                   "use `${xname}_LDADD', not `${xname}_LIBADD'");
2651       set_seen ($xname . '_DEPENDENCIES');
2652       set_seen ($xname . '_LDFLAGS');
2654       # Determine program to use for link.
2655       my($xlink, $vlink) = &define_per_target_linker_variable ($linker, $xname);
2656       $vlink = verbose_flag ($vlink || 'GEN');
2658       # If the resulting program lies into a subdirectory,
2659       # make sure this directory will exist.
2660       my $dirstamp = require_build_directory_maybe ($one_file);
2662       $libtool_clean_directories{dirname ($one_file)} = 1;
2664       $output_rules .= &file_contents ('program',
2665                                        $where,
2666                                        PROGRAM  => $one_file,
2667                                        XPROGRAM => $xname,
2668                                        XLINK    => $xlink,
2669                                        VERBOSE  => $vlink,
2670                                        DIRSTAMP => $dirstamp,
2671                                        EXEEXT   => '$(EXEEXT)');
2673       if ($seen_libobjs || $seen_global_libobjs)
2674         {
2675           if (var ($xname . '_LDADD'))
2676             {
2677               &check_libobjs_sources ($xname, $xname . '_LDADD');
2678             }
2679           elsif (var ('LDADD'))
2680             {
2681               &check_libobjs_sources ($xname, 'LDADD');
2682             }
2683         }
2684     }
2688 # handle_libraries ()
2689 # -------------------
2690 # Handle libraries.
2691 sub handle_libraries
2693   my @liblist = &am_install_var ('libs', 'LIBRARIES',
2694                                  'lib', 'pkglib', 'noinst', 'check');
2695   return if ! @liblist;
2697   my @prefix = am_primary_prefixes ('LIBRARIES', 0, 'lib', 'pkglib',
2698                                     'noinst', 'check');
2700   if (@prefix)
2701     {
2702       my $var = rvar ($prefix[0] . '_LIBRARIES');
2703       $var->requires_variables ('library used', 'RANLIB');
2704     }
2706   &define_variable ('AR', 'ar', INTERNAL);
2707   &define_variable ('ARFLAGS', 'cru', INTERNAL);
2708   &define_verbose_tagvar ('AR');
2710   foreach my $pair (@liblist)
2711     {
2712       my ($where, $onelib) = @$pair;
2714       my $seen_libobjs = 0;
2715       # Check that the library fits the standard naming convention.
2716       my $bn = basename ($onelib);
2717       if ($bn !~ /^lib.*\.a$/)
2718         {
2719           $bn =~ s/^(?:lib)?(.*?)(?:\.[^.]*)?$/lib$1.a/;
2720           my $suggestion = dirname ($onelib) . "/$bn";
2721           $suggestion =~ s|^\./||g;
2722           msg ('error-gnu/warn', $where,
2723                "`$onelib' is not a standard library name\n"
2724                . "did you mean `$suggestion'?")
2725         }
2727       ($known_libraries{$onelib} = $bn) =~ s/\.a$//;
2729       $where->push_context ("while processing library `$onelib'");
2730       $where->set (INTERNAL->get);
2732       my $obj = get_object_extension '.$(OBJEXT)';
2734       # Canonicalize names and check for misspellings.
2735       my $xlib = &check_canonical_spelling ($onelib, '_LIBADD', '_SOURCES',
2736                                             '_OBJECTS', '_DEPENDENCIES',
2737                                             '_AR');
2739       if (! var ($xlib . '_AR'))
2740         {
2741           &define_variable ($xlib . '_AR', '$(AR) $(ARFLAGS)', $where);
2742         }
2744       # Generate support for conditional object inclusion in
2745       # libraries.
2746       if (var ($xlib . '_LIBADD'))
2747         {
2748           if (&handle_lib_objects ($xlib, $xlib . '_LIBADD'))
2749             {
2750               $seen_libobjs = 1;
2751             }
2752         }
2753       else
2754         {
2755           &define_variable ($xlib . "_LIBADD", '', $where);
2756         }
2758       reject_var ($xlib . '_LDADD',
2759                   "use `${xlib}_LIBADD', not `${xlib}_LDADD'");
2761       # Make sure we at look at this.
2762       set_seen ($xlib . '_DEPENDENCIES');
2764       &handle_source_transform ($xlib, $onelib, $obj, $where,
2765                                 NONLIBTOOL => 1, LIBTOOL => 0);
2767       # If the resulting library lies into a subdirectory,
2768       # make sure this directory will exist.
2769       my $dirstamp = require_build_directory_maybe ($onelib);
2770       my $verbose = verbose_flag ('AR');
2771       my $silent = silent_flag ();
2773       $output_rules .= &file_contents ('library',
2774                                        $where,
2775                                        VERBOSE  => $verbose,
2776                                        SILENT   => $silent,
2777                                        LIBRARY  => $onelib,
2778                                        XLIBRARY => $xlib,
2779                                        DIRSTAMP => $dirstamp);
2781       if ($seen_libobjs)
2782         {
2783           if (var ($xlib . '_LIBADD'))
2784             {
2785               &check_libobjs_sources ($xlib, $xlib . '_LIBADD');
2786             }
2787         }
2788     }
2792 # handle_ltlibraries ()
2793 # ---------------------
2794 # Handle shared libraries.
2795 sub handle_ltlibraries
2797   my @liblist = &am_install_var ('ltlib', 'LTLIBRARIES',
2798                                  'noinst', 'lib', 'pkglib', 'check');
2799   return if ! @liblist;
2801   my @prefix = am_primary_prefixes ('LTLIBRARIES', 0, 'lib', 'pkglib',
2802                                     'noinst', 'check');
2804   if (@prefix)
2805     {
2806       my $var = rvar ($prefix[0] . '_LTLIBRARIES');
2807       $var->requires_variables ('Libtool library used', 'LIBTOOL');
2808     }
2810   my %instdirs = ();
2811   my %instsubdirs = ();
2812   my %instconds = ();
2813   my %liblocations = ();        # Location (in Makefile.am) of each library.
2815   foreach my $key (@prefix)
2816     {
2817       # Get the installation directory of each library.
2818       my $dir = $key;
2819       my $strip_subdir = 1;
2820       if ($dir =~ /^nobase_/)
2821         {
2822           $dir =~ s/^nobase_//;
2823           $strip_subdir = 0;
2824         }
2825       my $var = rvar ($key . '_LTLIBRARIES');
2827       # We reject libraries which are installed in several places
2828       # in the same condition, because we can only specify one
2829       # `-rpath' option.
2830       $var->traverse_recursively
2831         (sub
2832          {
2833            my ($var, $val, $cond, $full_cond) = @_;
2834            my $hcond = $full_cond->human;
2835            my $where = $var->rdef ($cond)->location;
2836            my $ldir = '';
2837            $ldir = '/' . dirname ($val)
2838              if (!$strip_subdir);
2839            # A library cannot be installed in different directory
2840            # in overlapping conditions.
2841            if (exists $instconds{$val})
2842              {
2843                my ($msg, $acond) =
2844                  $instconds{$val}->ambiguous_p ($val, $full_cond);
2846                if ($msg)
2847                  {
2848                    error ($where, $msg, partial => 1);
2849                    my $dirtxt = "installed " . ($strip_subdir ? "in" : "below") . " `$dir'";
2850                    $dirtxt = "built for `$dir'"
2851                      if $dir eq 'EXTRA' || $dir eq 'noinst' || $dir eq 'check';
2852                    my $dircond =
2853                      $full_cond->true ? "" : " in condition $hcond";
2855                    error ($where, "`$val' should be $dirtxt$dircond ...",
2856                           partial => 1);
2858                    my $hacond = $acond->human;
2859                    my $adir = $instdirs{$val}{$acond};
2860                    my $adirtxt = "installed in `$adir'";
2861                    $adirtxt = "built for `$adir'"
2862                      if ($adir eq 'EXTRA' || $adir eq 'noinst'
2863                          || $adir eq 'check');
2864                    my $adircond = $acond->true ? "" : " in condition $hacond";
2866                    my $onlyone = ($dir ne $adir) ?
2867                      ("\nLibtool libraries can be built for only one "
2868                       . "destination.") : "";
2870                    error ($liblocations{$val}{$acond},
2871                           "... and should also be $adirtxt$adircond.$onlyone");
2872                    return;
2873                  }
2874              }
2875            else
2876              {
2877                $instconds{$val} = new Automake::DisjConditions;
2878              }
2879            $instdirs{$val}{$full_cond} = $dir;
2880            $instsubdirs{$val}{$full_cond} = $ldir;
2881            $liblocations{$val}{$full_cond} = $where;
2882            $instconds{$val} = $instconds{$val}->merge ($full_cond);
2883          },
2884          sub
2885          {
2886            return ();
2887          },
2888          skip_ac_subst => 1);
2889     }
2891   foreach my $pair (@liblist)
2892     {
2893       my ($where, $onelib) = @$pair;
2895       my $seen_libobjs = 0;
2896       my $obj = get_object_extension '.lo';
2898       # Canonicalize names and check for misspellings.
2899       my $xlib = &check_canonical_spelling ($onelib, '_LIBADD', '_LDFLAGS',
2900                                             '_SOURCES', '_OBJECTS',
2901                                             '_DEPENDENCIES');
2903       # Check that the library fits the standard naming convention.
2904       my $libname_rx = '^lib.*\.la';
2905       my $ldvar = var ("${xlib}_LDFLAGS") || var ('AM_LDFLAGS');
2906       my $ldvar2 = var ('LDFLAGS');
2907       if (($ldvar && grep (/-module/, $ldvar->value_as_list_recursive))
2908           || ($ldvar2 && grep (/-module/, $ldvar2->value_as_list_recursive)))
2909         {
2910           # Relax name checking for libtool modules.
2911           $libname_rx = '\.la';
2912         }
2914       my $bn = basename ($onelib);
2915       if ($bn !~ /$libname_rx$/)
2916         {
2917           my $type = 'library';
2918           if ($libname_rx eq '\.la')
2919             {
2920               $bn =~ s/^(lib|)(.*?)(?:\.[^.]*)?$/$1$2.la/;
2921               $type = 'module';
2922             }
2923           else
2924             {
2925               $bn =~ s/^(?:lib)?(.*?)(?:\.[^.]*)?$/lib$1.la/;
2926             }
2927           my $suggestion = dirname ($onelib) . "/$bn";
2928           $suggestion =~ s|^\./||g;
2929           msg ('error-gnu/warn', $where,
2930                "`$onelib' is not a standard libtool $type name\n"
2931                . "did you mean `$suggestion'?")
2932         }
2934       ($known_libraries{$onelib} = $bn) =~ s/\.la$//;
2936       $where->push_context ("while processing Libtool library `$onelib'");
2937       $where->set (INTERNAL->get);
2939       # Make sure we look at these.
2940       set_seen ($xlib . '_LDFLAGS');
2941       set_seen ($xlib . '_DEPENDENCIES');
2943       # Generate support for conditional object inclusion in
2944       # libraries.
2945       if (var ($xlib . '_LIBADD'))
2946         {
2947           if (&handle_lib_objects ($xlib, $xlib . '_LIBADD'))
2948             {
2949               $seen_libobjs = 1;
2950             }
2951         }
2952       else
2953         {
2954           &define_variable ($xlib . "_LIBADD", '', $where);
2955         }
2957       reject_var ("${xlib}_LDADD",
2958                   "use `${xlib}_LIBADD', not `${xlib}_LDADD'");
2961       my $linker = &handle_source_transform ($xlib, $onelib, $obj, $where,
2962                                              NONLIBTOOL => 0, LIBTOOL => 1);
2964       # Determine program to use for link.
2965       my($xlink, $vlink) = &define_per_target_linker_variable ($linker, $xlib);
2966       $vlink = verbose_flag ($vlink || 'GEN');
2968       my $rpathvar = "am_${xlib}_rpath";
2969       my $rpath = "\$($rpathvar)";
2970       foreach my $rcond ($instconds{$onelib}->conds)
2971         {
2972           my $val;
2973           if ($instdirs{$onelib}{$rcond} eq 'EXTRA'
2974               || $instdirs{$onelib}{$rcond} eq 'noinst'
2975               || $instdirs{$onelib}{$rcond} eq 'check')
2976             {
2977               # It's an EXTRA_ library, so we can't specify -rpath,
2978               # because we don't know where the library will end up.
2979               # The user probably knows, but generally speaking automake
2980               # doesn't -- and in fact configure could decide
2981               # dynamically between two different locations.
2982               $val = '';
2983             }
2984           else
2985             {
2986               $val = ('-rpath $(' . $instdirs{$onelib}{$rcond} . 'dir)');
2987               $val .= $instsubdirs{$onelib}{$rcond}
2988                 if defined $instsubdirs{$onelib}{$rcond};
2989             }
2990           if ($rcond->true)
2991             {
2992               # If $rcond is true there is only one condition and
2993               # there is no point defining an helper variable.
2994               $rpath = $val;
2995             }
2996           else
2997             {
2998               define_pretty_variable ($rpathvar, $rcond, INTERNAL, $val);
2999             }
3000         }
3002       # If the resulting library lies into a subdirectory,
3003       # make sure this directory will exist.
3004       my $dirstamp = require_build_directory_maybe ($onelib);
3006       # Remember to cleanup .libs/ in this directory.
3007       my $dirname = dirname $onelib;
3008       $libtool_clean_directories{$dirname} = 1;
3010       $output_rules .= &file_contents ('ltlibrary',
3011                                        $where,
3012                                        LTLIBRARY  => $onelib,
3013                                        XLTLIBRARY => $xlib,
3014                                        RPATH      => $rpath,
3015                                        XLINK      => $xlink,
3016                                        VERBOSE    => $vlink,
3017                                        DIRSTAMP   => $dirstamp);
3018       if ($seen_libobjs)
3019         {
3020           if (var ($xlib . '_LIBADD'))
3021             {
3022               &check_libobjs_sources ($xlib, $xlib . '_LIBADD');
3023             }
3024         }
3025     }
3028 # See if any _SOURCES variable were misspelled.
3029 sub check_typos ()
3031   # It is ok if the user sets this particular variable.
3032   set_seen 'AM_LDFLAGS';
3034   foreach my $primary ('SOURCES', 'LIBADD', 'LDADD', 'LDFLAGS', 'DEPENDENCIES')
3035     {
3036       foreach my $var (variables $primary)
3037         {
3038           my $varname = $var->name;
3039           # A configure variable is always legitimate.
3040           next if exists $configure_vars{$varname};
3042           for my $cond ($var->conditions->conds)
3043             {
3044               $varname =~ /^(?:nobase_)?(?:dist_|nodist_)?(.*)_[[:alnum:]]+$/;
3045               msg_var ('syntax', $var, "variable `$varname' is defined but no"
3046                        . " program or\nlibrary has `$1' as canonical name"
3047                        . " (possible typo)")
3048                 unless $var->rdef ($cond)->seen;
3049             }
3050         }
3051     }
3055 # Handle scripts.
3056 sub handle_scripts
3058     # NOTE we no longer automatically clean SCRIPTS, because it is
3059     # useful to sometimes distribute scripts verbatim.  This happens
3060     # e.g. in Automake itself.
3061     &am_install_var ('-candist', 'scripts', 'SCRIPTS',
3062                      'bin', 'sbin', 'libexec', 'pkgdata',
3063                      'noinst', 'check');
3069 ## ------------------------ ##
3070 ## Handling Texinfo files.  ##
3071 ## ------------------------ ##
3073 # ($OUTFILE, $VFILE, @CLEAN_FILES)
3074 # &scan_texinfo_file ($FILENAME)
3075 # ------------------------------
3076 # $OUTFILE     - name of the info file produced by $FILENAME.
3077 # $VFILE       - name of the version.texi file used (undef if none).
3078 # @CLEAN_FILES - list of byproducts (indexes etc.)
3079 sub scan_texinfo_file ($)
3081   my ($filename) = @_;
3083   # Some of the following extensions are always created, no matter
3084   # whether indexes are used or not.  Other (like cps, fns, ... pgs)
3085   # are only created when they are used.  We used to scan $FILENAME
3086   # for their use, but that is not enough: they could be used in
3087   # included files.  We can't scan included files because we don't
3088   # know the include path.  Therefore we always erase these files, no
3089   # matter whether they are used or not.
3090   #
3091   # (tmp is only created if an @macro is used and a certain e-TeX
3092   # feature is not available.)
3093   my %clean_suffixes =
3094     map { $_ => 1 } (qw(aux log toc tmp
3095                         cp cps
3096                         fn fns
3097                         ky kys
3098                         vr vrs
3099                         tp tps
3100                         pg pgs)); # grep 'new.*index' texinfo.tex
3102   my $texi = new Automake::XFile "< $filename";
3103   verb "reading $filename";
3105   my ($outfile, $vfile);
3106   while ($_ = $texi->getline)
3107     {
3108       if (/^\@setfilename +(\S+)/)
3109         {
3110           # Honor only the first @setfilename.  (It's possible to have
3111           # more occurrences later if the manual shows examples of how
3112           # to use @setfilename...)
3113           next if $outfile;
3115           $outfile = $1;
3116           if ($outfile =~ /\.([^.]+)$/ && $1 ne 'info')
3117             {
3118               error ("$filename:$.",
3119                      "output `$outfile' has unrecognized extension");
3120               return;
3121             }
3122         }
3123       # A "version.texi" file is actually any file whose name matches
3124       # "vers*.texi".
3125       elsif (/^\@include\s+(vers[^.]*\.texi)\s*$/)
3126         {
3127           $vfile = $1;
3128         }
3130       # Try to find new or unused indexes.
3132       # Creating a new category of index.
3133       elsif (/^\@def(code)?index (\w+)/)
3134         {
3135           $clean_suffixes{$2} = 1;
3136           $clean_suffixes{"$2s"} = 1;
3137         }
3139       # Merging an index into an another.
3140       elsif (/^\@syn(code)?index (\w+) (\w+)/)
3141         {
3142           delete $clean_suffixes{"$2s"};
3143           $clean_suffixes{"$3s"} = 1;
3144         }
3146     }
3148   if (! $outfile)
3149     {
3150       err_am "`$filename' missing \@setfilename";
3151       return;
3152     }
3154   my $infobase = basename ($filename);
3155   $infobase =~ s/\.te?xi(nfo)?$//;
3156   return ($outfile, $vfile,
3157           map { "$infobase.$_" } (sort keys %clean_suffixes));
3161 # ($DIRSTAMP, @CLEAN_FILES)
3162 # output_texinfo_build_rules ($SOURCE, $DEST, $INSRC, @DEPENDENCIES)
3163 # ------------------------------------------------------------------
3164 # SOURCE - the source Texinfo file
3165 # DEST - the destination Info file
3166 # INSRC - wether DEST should be built in the source tree
3167 # DEPENDENCIES - known dependencies
3168 sub output_texinfo_build_rules ($$$@)
3170   my ($source, $dest, $insrc, @deps) = @_;
3172   # Split `a.texi' into `a' and `.texi'.
3173   my ($spfx, $ssfx) = ($source =~ /^(.*?)(\.[^.]*)?$/);
3174   my ($dpfx, $dsfx) = ($dest =~ /^(.*?)(\.[^.]*)?$/);
3176   $ssfx ||= "";
3177   $dsfx ||= "";
3179   # We can output two kinds of rules: the "generic" rules use Make
3180   # suffix rules and are appropriate when $source and $dest do not lie
3181   # in a sub-directory; the "specific" rules are needed in the other
3182   # case.
3183   #
3184   # The former are output only once (this is not really apparent here,
3185   # but just remember that some logic deeper in Automake will not
3186   # output the same rule twice); while the later need to be output for
3187   # each Texinfo source.
3188   my $generic;
3189   my $makeinfoflags;
3190   my $sdir = dirname $source;
3191   if ($sdir eq '.' && dirname ($dest) eq '.')
3192     {
3193       $generic = 1;
3194       $makeinfoflags = '-I $(srcdir)';
3195     }
3196   else
3197     {
3198       $generic = 0;
3199       $makeinfoflags = "-I $sdir -I \$(srcdir)/$sdir";
3200     }
3202   # A directory can contain two kinds of info files: some built in the
3203   # source tree, and some built in the build tree.  The rules are
3204   # different in each case.  However we cannot output two different
3205   # set of generic rules.  Because in-source builds are more usual, we
3206   # use generic rules in this case and fall back to "specific" rules
3207   # for build-dir builds.  (It should not be a problem to invert this
3208   # if needed.)
3209   $generic = 0 unless $insrc;
3211   # We cannot use a suffix rule to build info files with an empty
3212   # extension.  Otherwise we would output a single suffix inference
3213   # rule, with separate dependencies, as in
3214   #
3215   #    .texi:
3216   #             $(MAKEINFO) ...
3217   #    foo.info: foo.texi
3218   #
3219   # which confuse Solaris make.  (See the Autoconf manual for
3220   # details.)  Therefore we use a specific rule in this case.  This
3221   # applies to info files only (dvi and pdf files always have an
3222   # extension).
3223   my $generic_info = ($generic && $dsfx) ? 1 : 0;
3225   # If the resulting file lie into a subdirectory,
3226   # make sure this directory will exist.
3227   my $dirstamp = require_build_directory_maybe ($dest);
3229   my $dipfx = ($insrc ? '$(srcdir)/' : '') . $dpfx;
3231   $output_rules .= file_contents ('texibuild',
3232                                   new Automake::Location,
3233                                   DEPS             => "@deps",
3234                                   DEST_PREFIX      => $dpfx,
3235                                   DEST_INFO_PREFIX => $dipfx,
3236                                   DEST_SUFFIX      => $dsfx,
3237                                   DIRSTAMP         => $dirstamp,
3238                                   GENERIC          => $generic,
3239                                   GENERIC_INFO     => $generic_info,
3240                                   INSRC            => $insrc,
3241                                   MAKEINFOFLAGS    => $makeinfoflags,
3242                                   SOURCE           => ($generic
3243                                                        ? '$<' : $source),
3244                                   SOURCE_INFO      => ($generic_info
3245                                                        ? '$<' : $source),
3246                                   SOURCE_REAL      => $source,
3247                                   SOURCE_SUFFIX    => $ssfx,
3248                                   );
3249   return ($dirstamp, "$dpfx.dvi", "$dpfx.pdf", "$dpfx.ps", "$dpfx.html");
3253 # ($MOSTLYCLEAN, $TEXICLEAN, $MAINTCLEAN)
3254 # handle_texinfo_helper ($info_texinfos)
3255 # --------------------------------------
3256 # Handle all Texinfo source; helper for handle_texinfo.
3257 sub handle_texinfo_helper ($)
3259   my ($info_texinfos) = @_;
3260   my (@infobase, @info_deps_list, @texi_deps);
3261   my %versions;
3262   my $done = 0;
3263   my (@mostly_cleans, @texi_cleans, @maint_cleans) = ('', '', '');
3265   # Build a regex matching user-cleaned files.
3266   my $d = var 'DISTCLEANFILES';
3267   my $c = var 'CLEANFILES';
3268   my @f = ();
3269   push @f, $d->value_as_list_recursive (inner_expand => 1) if $d;
3270   push @f, $c->value_as_list_recursive (inner_expand => 1) if $c;
3271   @f = map { s|[^A-Za-z_0-9*\[\]\-]|\\$&|g; s|\*|[^/]*|g; $_; } @f;
3272   my $user_cleaned_files = '^(?:' . join ('|', @f) . ')$';
3274   foreach my $texi
3275       ($info_texinfos->value_as_list_recursive (inner_expand => 1))
3276     {
3277       my $infobase = $texi;
3278       $infobase =~ s/\.(txi|texinfo|texi)$//;
3280       if ($infobase eq $texi)
3281         {
3282           # FIXME: report line number.
3283           err_am "texinfo file `$texi' has unrecognized extension";
3284           next;
3285         }
3287       push @infobase, $infobase;
3289       # If 'version.texi' is referenced by input file, then include
3290       # automatic versioning capability.
3291       my ($out_file, $vtexi, @clean_files) =
3292         scan_texinfo_file ("$relative_dir/$texi")
3293         or next;
3294       push (@mostly_cleans, @clean_files);
3296       # If the Texinfo source is in a subdirectory, create the
3297       # resulting info in this subdirectory.  If it is in the current
3298       # directory, try hard to not prefix "./" because it breaks the
3299       # generic rules.
3300       my $outdir = dirname ($texi) . '/';
3301       $outdir = "" if $outdir eq './';
3302       $out_file =  $outdir . $out_file;
3304       # Until Automake 1.6.3, .info files were built in the
3305       # source tree.  This was an obstacle to the support of
3306       # non-distributed .info files, and non-distributed .texi
3307       # files.
3308       #
3309       # * Non-distributed .texi files is important in some packages
3310       #   where .texi files are built at make time, probably using
3311       #   other binaries built in the package itself, maybe using
3312       #   tools or information found on the build host.  Because
3313       #   these files are not distributed they are always rebuilt
3314       #   at make time; they should therefore not lie in the source
3315       #   directory.  One plan was to support this using
3316       #   nodist_info_TEXINFOS or something similar.  (Doing this
3317       #   requires some sanity checks.  For instance Automake should
3318       #   not allow:
3319       #      dist_info_TEXINFOS = foo.texi
3320       #      nodist_foo_TEXINFOS = included.texi
3321       #   because a distributed file should never depend on a
3322       #   non-distributed file.)
3323       #
3324       # * If .texi files are not distributed, then .info files should
3325       #   not be distributed either.  There are also cases where one
3326       #   wants to distribute .texi files, but does not want to
3327       #   distribute the .info files.  For instance the Texinfo package
3328       #   distributes the tool used to build these files; it would
3329       #   be a waste of space to distribute them.  It's not clear
3330       #   which syntax we should use to indicate that .info files should
3331       #   not be distributed.  Akim Demaille suggested that eventually
3332       #   we switch to a new syntax:
3333       #   |  Maybe we should take some inspiration from what's already
3334       #   |  done in the rest of Automake.  Maybe there is too much
3335       #   |  syntactic sugar here, and you want
3336       #   |     nodist_INFO = bar.info
3337       #   |     dist_bar_info_SOURCES = bar.texi
3338       #   |     bar_texi_DEPENDENCIES = foo.texi
3339       #   |  with a bit of magic to have bar.info represent the whole
3340       #   |  bar*info set.  That's a lot more verbose that the current
3341       #   |  situation, but it is # not new, hence the user has less
3342       #   |  to learn.
3343       #   |
3344       #   |  But there is still too much room for meaningless specs:
3345       #   |     nodist_INFO = bar.info
3346       #   |     dist_bar_info_SOURCES = bar.texi
3347       #   |     dist_PS = bar.ps something-written-by-hand.ps
3348       #   |     nodist_bar_ps_SOURCES = bar.texi
3349       #   |     bar_texi_DEPENDENCIES = foo.texi
3350       #   |  here bar.texi is dist_ in line 2, and nodist_ in 4.
3351       #
3352       # Back to the point, it should be clear that in order to support
3353       # non-distributed .info files, we need to build them in the
3354       # build tree, not in the source tree (non-distributed .texi
3355       # files are less of a problem, because we do not output build
3356       # rules for them).  In Automake 1.7 .info build rules have been
3357       # largely cleaned up so that .info files get always build in the
3358       # build tree, even when distributed.  The idea was that
3359       #   (1) if during a VPATH build the .info file was found to be
3360       #       absent or out-of-date (in the source tree or in the
3361       #       build tree), Make would rebuild it in the build tree.
3362       #       If an up-to-date source-tree of the .info file existed,
3363       #       make would not rebuild it in the build tree.
3364       #   (2) having two copies of .info files, one in the source tree
3365       #       and one (newer) in the build tree is not a problem
3366       #       because `make dist' always pick files in the build tree
3367       #       first.
3368       # However it turned out the be a bad idea for several reasons:
3369       #   * Tru64, OpenBSD, and FreeBSD (not NetBSD) Make do not behave
3370       #     like GNU Make on point (1) above.  These implementations
3371       #     of Make would always rebuild .info files in the build
3372       #     tree, even if such files were up to date in the source
3373       #     tree.  Consequently, it was impossible to perform a VPATH
3374       #     build of a package containing Texinfo files using these
3375       #     Make implementations.
3376       #     (Refer to the Autoconf Manual, section "Limitation of
3377       #     Make", paragraph "VPATH", item "target lookup", for
3378       #     an account of the differences between these
3379       #     implementations.)
3380       #   * The GNU Coding Standards require these files to be built
3381       #     in the source-tree (when they are distributed, that is).
3382       #   * Keeping a fresher copy of distributed files in the
3383       #     build tree can be annoying during development because
3384       #     - if the files is kept under CVS, you really want it
3385       #       to be updated in the source tree
3386       #     - it is confusing that `make distclean' does not erase
3387       #       all files in the build tree.
3388       #
3389       # Consequently, starting with Automake 1.8, .info files are
3390       # built in the source tree again.  Because we still plan to
3391       # support non-distributed .info files at some point, we
3392       # have a single variable ($INSRC) that controls whether
3393       # the current .info file must be built in the source tree
3394       # or in the build tree.  Actually this variable is switched
3395       # off for .info files that appear to be cleaned; this is
3396       # for backward compatibility with package such as Texinfo,
3397       # which do things like
3398       #   info_TEXINFOS = texinfo.txi info-stnd.texi info.texi
3399       #   DISTCLEANFILES = texinfo texinfo-* info*.info*
3400       #   # Do not create info files for distribution.
3401       #   dist-info:
3402       # in order not to distribute .info files.
3403       my $insrc = ($out_file =~ $user_cleaned_files) ? 0 : 1;
3405       my $soutdir = '$(srcdir)/' . $outdir;
3406       $outdir = $soutdir if $insrc;
3408       # If user specified file_TEXINFOS, then use that as explicit
3409       # dependency list.
3410       @texi_deps = ();
3411       push (@texi_deps, "$soutdir$vtexi") if $vtexi;
3413       my $canonical = canonicalize ($infobase);
3414       if (var ($canonical . "_TEXINFOS"))
3415         {
3416           push (@texi_deps, '$(' . $canonical . '_TEXINFOS)');
3417           push_dist_common ('$(' . $canonical . '_TEXINFOS)');
3418         }
3420       my ($dirstamp, @cfiles) =
3421         output_texinfo_build_rules ($texi, $out_file, $insrc, @texi_deps);
3422       push (@texi_cleans, @cfiles);
3424       push (@info_deps_list, $out_file);
3426       # If a vers*.texi file is needed, emit the rule.
3427       if ($vtexi)
3428         {
3429           err_am ("`$vtexi', included in `$texi', "
3430                   . "also included in `$versions{$vtexi}'")
3431             if defined $versions{$vtexi};
3432           $versions{$vtexi} = $texi;
3434           # We number the stamp-vti files.  This is doable since the
3435           # actual names don't matter much.  We only number starting
3436           # with the second one, so that the common case looks nice.
3437           my $vti = ($done ? $done : 'vti');
3438           ++$done;
3440           # This is ugly, but it is our historical practice.
3441           if ($config_aux_dir_set_in_configure_ac)
3442             {
3443               require_conf_file_with_macro (TRUE, 'info_TEXINFOS', FOREIGN,
3444                                             'mdate-sh');
3445             }
3446           else
3447             {
3448               require_file_with_macro (TRUE, 'info_TEXINFOS',
3449                                        FOREIGN, 'mdate-sh');
3450             }
3452           my $conf_dir;
3453           if ($config_aux_dir_set_in_configure_ac)
3454             {
3455               $conf_dir = "$am_config_aux_dir/";
3456             }
3457           else
3458             {
3459               $conf_dir = '$(srcdir)/';
3460             }
3461           $output_rules .= file_contents ('texi-vers',
3462                                           new Automake::Location,
3463                                           TEXI     => $texi,
3464                                           VTI      => $vti,
3465                                           STAMPVTI => "${soutdir}stamp-$vti",
3466                                           VTEXI    => "$soutdir$vtexi",
3467                                           MDDIR    => $conf_dir,
3468                                           DIRSTAMP => $dirstamp);
3469         }
3470     }
3472   # Handle location of texinfo.tex.
3473   my $need_texi_file = 0;
3474   my $texinfodir;
3475   if (var ('TEXINFO_TEX'))
3476     {
3477       # The user defined TEXINFO_TEX so assume he knows what he is
3478       # doing.
3479       $texinfodir = ('$(srcdir)/'
3480                      . dirname (variable_value ('TEXINFO_TEX')));
3481     }
3482   elsif (option 'cygnus')
3483     {
3484       $texinfodir = '$(top_srcdir)/../texinfo';
3485       define_variable ('TEXINFO_TEX', "$texinfodir/texinfo.tex", INTERNAL);
3486     }
3487   elsif ($config_aux_dir_set_in_configure_ac)
3488     {
3489       $texinfodir = $am_config_aux_dir;
3490       define_variable ('TEXINFO_TEX', "$texinfodir/texinfo.tex", INTERNAL);
3491       $need_texi_file = 2; # so that we require_conf_file later
3492     }
3493   else
3494     {
3495       $texinfodir = '$(srcdir)';
3496       $need_texi_file = 1;
3497     }
3498   define_variable ('am__TEXINFO_TEX_DIR', $texinfodir, INTERNAL);
3500   push (@dist_targets, 'dist-info');
3502   if (! option 'no-installinfo')
3503     {
3504       # Make sure documentation is made and installed first.  Use
3505       # $(INFO_DEPS), not 'info', because otherwise recursive makes
3506       # get run twice during "make all".
3507       unshift (@all, '$(INFO_DEPS)');
3508     }
3510   define_files_variable ("DVIS", @infobase, 'dvi', INTERNAL);
3511   define_files_variable ("PDFS", @infobase, 'pdf', INTERNAL);
3512   define_files_variable ("PSS", @infobase, 'ps', INTERNAL);
3513   define_files_variable ("HTMLS", @infobase, 'html', INTERNAL);
3515   # This next isn't strictly needed now -- the places that look here
3516   # could easily be changed to look in info_TEXINFOS.  But this is
3517   # probably better, in case noinst_TEXINFOS is ever supported.
3518   define_variable ("TEXINFOS", variable_value ('info_TEXINFOS'), INTERNAL);
3520   # Do some error checking.  Note that this file is not required
3521   # when in Cygnus mode; instead we defined TEXINFO_TEX explicitly
3522   # up above.
3523   if ($need_texi_file && ! option 'no-texinfo.tex')
3524     {
3525       if ($need_texi_file > 1)
3526         {
3527           require_conf_file_with_macro (TRUE, 'info_TEXINFOS', FOREIGN,
3528                                         'texinfo.tex');
3529         }
3530       else
3531         {
3532           require_file_with_macro (TRUE, 'info_TEXINFOS', FOREIGN,
3533                                    'texinfo.tex');
3534         }
3535     }
3537   return (makefile_wrap ("", "\t  ", @mostly_cleans),
3538           makefile_wrap ("", "\t  ", @texi_cleans),
3539           makefile_wrap ("", "\t  ", @maint_cleans));
3543 # handle_texinfo ()
3544 # -----------------
3545 # Handle all Texinfo source.
3546 sub handle_texinfo ()
3548   reject_var 'TEXINFOS', "`TEXINFOS' is an anachronism; use `info_TEXINFOS'";
3549   # FIXME: I think this is an obsolete future feature name.
3550   reject_var 'html_TEXINFOS', "HTML generation not yet supported";
3552   my $info_texinfos = var ('info_TEXINFOS');
3553   my ($mostlyclean, $clean, $maintclean) = ('', '', '');
3554   if ($info_texinfos)
3555     {
3556       ($mostlyclean, $clean, $maintclean) = handle_texinfo_helper ($info_texinfos);
3557       chomp $mostlyclean;
3558       chomp $clean;
3559       chomp $maintclean;
3560     }
3562   $output_rules .=  file_contents ('texinfos',
3563                                    new Automake::Location,
3564                                    MOSTLYCLEAN   => $mostlyclean,
3565                                    TEXICLEAN     => $clean,
3566                                    MAINTCLEAN    => $maintclean,
3567                                    'LOCAL-TEXIS' => !!$info_texinfos);
3571 # Handle any man pages.
3572 sub handle_man_pages
3574   reject_var 'MANS', "`MANS' is an anachronism; use `man_MANS'";
3576   # Find all the sections in use.  We do this by first looking for
3577   # "standard" sections, and then looking for any additional
3578   # sections used in man_MANS.
3579   my (%sections, %notrans_sections, %trans_sections,
3580       %notrans_vars, %trans_vars, %notrans_sect_vars, %trans_sect_vars);
3581   # We handle nodist_ for uniformity.  man pages aren't distributed
3582   # by default so it isn't actually very important.
3583   foreach my $npfx ('', 'notrans_')
3584     {
3585       foreach my $pfx ('', 'dist_', 'nodist_')
3586         {
3587           # Add more sections as needed.
3588           foreach my $section ('0'..'9', 'n', 'l')
3589             {
3590               my $varname = $npfx . $pfx . 'man' . $section . '_MANS';
3591               if (var ($varname))
3592                 {
3593                   $sections{$section} = 1;
3594                   $varname = '$(' . $varname . ')';
3595                   if ($npfx eq 'notrans_')
3596                     {
3597                       $notrans_sections{$section} = 1;
3598                       $notrans_sect_vars{$varname} = 1;
3599                     }
3600                   else
3601                     {
3602                       $trans_sections{$section} = 1;
3603                       $trans_sect_vars{$varname} = 1;
3604                     }
3606                   &push_dist_common ($varname)
3607                     if $pfx eq 'dist_';
3608                 }
3609             }
3611           my $varname = $npfx . $pfx . 'man_MANS';
3612           my $var = var ($varname);
3613           if ($var)
3614             {
3615               foreach ($var->value_as_list_recursive)
3616                 {
3617                   # A page like `foo.1c' goes into man1dir.
3618                   if (/\.([0-9a-z])([a-z]*)$/)
3619                     {
3620                       $sections{$1} = 1;
3621                       if ($npfx eq 'notrans_')
3622                         {
3623                           $notrans_sections{$1} = 1;
3624                         }
3625                       else
3626                         {
3627                           $trans_sections{$1} = 1;
3628                         }
3629                     }
3630                 }
3632               $varname = '$(' . $varname . ')';
3633               if ($npfx eq 'notrans_')
3634                 {
3635                   $notrans_vars{$varname} = 1;
3636                 }
3637               else
3638                 {
3639                   $trans_vars{$varname} = 1;
3640                 }
3641               &push_dist_common ($varname)
3642                 if $pfx eq 'dist_';
3643             }
3644         }
3645     }
3647   return unless %sections;
3649   my @unsorted_deps;
3651   # Build section independent variables.
3652   my $have_notrans = %notrans_vars;
3653   my @notrans_list = sort keys %notrans_vars;
3654   my $have_trans = %trans_vars;
3655   my @trans_list = sort keys %trans_vars;
3657   # Now for each section, generate an install and uninstall rule.
3658   # Sort sections so output is deterministic.
3659   foreach my $section (sort keys %sections)
3660     {
3661       # Build section dependent variables.
3662       my $notrans_mans = $have_notrans || exists $notrans_sections{$section};
3663       my $trans_mans = $have_trans || exists $trans_sections{$section};
3664       my (%notrans_this_sect, %trans_this_sect);
3665       my $expr = 'man' . $section . '_MANS';
3666       foreach my $varname (keys %notrans_sect_vars)
3667         {
3668           if ($varname =~ /$expr/)
3669             {
3670               $notrans_this_sect{$varname} = 1;
3671             }
3672         }
3673       foreach my $varname (keys %trans_sect_vars)
3674         {
3675           if ($varname =~ /$expr/)
3676             {
3677               $trans_this_sect{$varname} = 1;
3678             }
3679         }
3680       my @notrans_sect_list = sort keys %notrans_this_sect;
3681       my @trans_sect_list = sort keys %trans_this_sect;
3682       @unsorted_deps = (keys %notrans_vars, keys %trans_vars,
3683                         keys %notrans_this_sect, keys %trans_this_sect);
3684       my @deps = sort @unsorted_deps;
3685       $output_rules .= &file_contents ('mans',
3686                                        new Automake::Location,
3687                                        SECTION           => $section,
3688                                        DEPS              => "@deps",
3689                                        NOTRANS_MANS      => $notrans_mans,
3690                                        NOTRANS_SECT_LIST => "@notrans_sect_list",
3691                                        HAVE_NOTRANS      => $have_notrans,
3692                                        NOTRANS_LIST      => "@notrans_list",
3693                                        TRANS_MANS        => $trans_mans,
3694                                        TRANS_SECT_LIST   => "@trans_sect_list",
3695                                        HAVE_TRANS        => $have_trans,
3696                                        TRANS_LIST        => "@trans_list");
3697     }
3699   @unsorted_deps  = (keys %notrans_vars, keys %trans_vars,
3700                      keys %notrans_sect_vars, keys %trans_sect_vars);
3701   my @mans = sort @unsorted_deps;
3702   $output_vars .= file_contents ('mans-vars',
3703                                  new Automake::Location,
3704                                  MANS => "@mans");
3706   push (@all, '$(MANS)')
3707     unless option 'no-installman';
3710 # Handle DATA variables.
3711 sub handle_data
3713     &am_install_var ('-noextra', '-candist', 'data', 'DATA',
3714                      'data', 'dataroot', 'dvi', 'html', 'pdf', 'ps',
3715                      'sysconf', 'sharedstate', 'localstate',
3716                      'pkgdata', 'lisp', 'noinst', 'check');
3719 # Handle TAGS.
3720 sub handle_tags
3722     my @tag_deps = ();
3723     my @ctag_deps = ();
3724     if (var ('SUBDIRS'))
3725     {
3726         $output_rules .= ("tags-recursive:\n"
3727                           . "\tlist=\'\$(SUBDIRS)\'; for subdir in \$\$list; do \\\n"
3728                           # Never fail here if a subdir fails; it
3729                           # isn't important.
3730                           . "\t  test \"\$\$subdir\" = . || (\$(am__cd) \$\$subdir"
3731                           . " && \$(MAKE) \$(AM_MAKEFLAGS) tags); \\\n"
3732                           . "\tdone\n");
3733         push (@tag_deps, 'tags-recursive');
3734         &depend ('.PHONY', 'tags-recursive');
3735         &depend ('.MAKE', 'tags-recursive');
3737         $output_rules .= ("ctags-recursive:\n"
3738                           . "\tlist=\'\$(SUBDIRS)\'; for subdir in \$\$list; do \\\n"
3739                           # Never fail here if a subdir fails; it
3740                           # isn't important.
3741                           . "\t  test \"\$\$subdir\" = . || (\$(am__cd) \$\$subdir"
3742                           . " && \$(MAKE) \$(AM_MAKEFLAGS) ctags); \\\n"
3743                           . "\tdone\n");
3744         push (@ctag_deps, 'ctags-recursive');
3745         &depend ('.PHONY', 'ctags-recursive');
3746         &depend ('.MAKE', 'ctags-recursive');
3747     }
3749     if (&saw_sources_p (1)
3750         || var ('ETAGS_ARGS')
3751         || @tag_deps)
3752     {
3753         my @config;
3754         foreach my $spec (@config_headers)
3755         {
3756             my ($out, @ins) = split_config_file_spec ($spec);
3757             foreach my $in (@ins)
3758               {
3759                 # If the config header source is in this directory,
3760                 # require it.
3761                 push @config, basename ($in)
3762                   if $relative_dir eq dirname ($in);
3763               }
3764         }
3765         $output_rules .= &file_contents ('tags',
3766                                          new Automake::Location,
3767                                          CONFIG    => "@config",
3768                                          TAGSDIRS  => "@tag_deps",
3769                                          CTAGSDIRS => "@ctag_deps");
3771         set_seen 'TAGS_DEPENDENCIES';
3772     }
3773     elsif (reject_var ('TAGS_DEPENDENCIES',
3774                        "doesn't make sense to define `TAGS_DEPENDENCIES'"
3775                        . "without\nsources or `ETAGS_ARGS'"))
3776     {
3777     }
3778     else
3779     {
3780         # Every Makefile must define some sort of TAGS rule.
3781         # Otherwise, it would be possible for a top-level "make TAGS"
3782         # to fail because some subdirectory failed.
3783         $output_rules .= "tags: TAGS\nTAGS:\n\n";
3784         # Ditto ctags.
3785         $output_rules .= "ctags: CTAGS\nCTAGS:\n\n";
3786     }
3789 # Handle multilib support.
3790 sub handle_multilib
3792   if ($seen_multilib && $relative_dir eq '.')
3793     {
3794       $output_rules .= &file_contents ('multilib', new Automake::Location);
3795       push (@all, 'all-multi');
3796     }
3800 # user_phony_rule ($NAME)
3801 # -----------------------
3802 # Return false if rule $NAME does not exist.  Otherwise,
3803 # declare it as phony, complete its definition (in case it is
3804 # conditional), and return its Automake::Rule instance.
3805 sub user_phony_rule ($)
3807   my ($name) = @_;
3808   my $rule = rule $name;
3809   if ($rule)
3810     {
3811       depend ('.PHONY', $name);
3812       # Define $NAME in all condition where it is not already defined,
3813       # so that it is always OK to depend on $NAME.
3814       for my $c ($rule->not_always_defined_in_cond (TRUE)->conds)
3815         {
3816           Automake::Rule::define ($name, 'internal', RULE_AUTOMAKE,
3817                                   $c, INTERNAL);
3818           $output_rules .= $c->subst_string . "$name:\n";
3819         }
3820     }
3821   return $rule;
3825 # $BOOLEAN
3826 # &for_dist_common ($A, $B)
3827 # -------------------------
3828 # Subroutine for &handle_dist: sort files to dist.
3830 # We put README first because it then becomes easier to make a
3831 # Usenet-compliant shar file (in these, README must be first).
3833 # FIXME: do more ordering of files here.
3834 sub for_dist_common
3836     return 0
3837         if $a eq $b;
3838     return -1
3839         if $a eq 'README';
3840     return 1
3841         if $b eq 'README';
3842     return $a cmp $b;
3845 # handle_dist
3846 # -----------
3847 # Handle 'dist' target.
3848 sub handle_dist ()
3850   # Substitutions for distdir.am
3851   my %transform;
3853   # Define DIST_SUBDIRS.  This must always be done, regardless of the
3854   # no-dist setting: target like `distclean' or `maintainer-clean' use it.
3855   my $subdirs = var ('SUBDIRS');
3856   if ($subdirs)
3857     {
3858       # If SUBDIRS is conditionally defined, then set DIST_SUBDIRS
3859       # to all possible directories, and use it.  If DIST_SUBDIRS is
3860       # defined, just use it.
3862       # Note that we check DIST_SUBDIRS first on purpose, so that
3863       # we don't call has_conditional_contents for now reason.
3864       # (In the past one project used so many conditional subdirectories
3865       # that calling has_conditional_contents on SUBDIRS caused
3866       # automake to grow to 150Mb -- this should not happen with
3867       # the current implementation of has_conditional_contents,
3868       # but it's more efficient to avoid the call anyway.)
3869       if (var ('DIST_SUBDIRS'))
3870         {
3871         }
3872       elsif ($subdirs->has_conditional_contents)
3873         {
3874           define_pretty_variable
3875             ('DIST_SUBDIRS', TRUE, INTERNAL,
3876              uniq ($subdirs->value_as_list_recursive));
3877         }
3878       else
3879         {
3880           # We always define this because that is what `distclean'
3881           # wants.
3882           define_pretty_variable ('DIST_SUBDIRS', TRUE, INTERNAL,
3883                                   '$(SUBDIRS)');
3884         }
3885     }
3887   # The remaining definitions are only required when a dist target is used.
3888   return if option 'no-dist';
3890   # At least one of the archive formats must be enabled.
3891   if ($relative_dir eq '.')
3892     {
3893       my $archive_defined = option 'no-dist-gzip' ? 0 : 1;
3894       $archive_defined ||=
3895         grep { option "dist-$_" } qw(shar zip tarZ bzip2 lzma xz);
3896       error (option 'no-dist-gzip',
3897              "no-dist-gzip specified but no dist-* specified, "
3898              . "at least one archive format must be enabled")
3899         unless $archive_defined;
3900     }
3902   # Look for common files that should be included in distribution.
3903   # If the aux dir is set, and it does not have a Makefile.am, then
3904   # we check for these files there as well.
3905   my $check_aux = 0;
3906   if ($relative_dir eq '.'
3907       && $config_aux_dir_set_in_configure_ac)
3908     {
3909       if (! &is_make_dir ($config_aux_dir))
3910         {
3911           $check_aux = 1;
3912         }
3913     }
3914   foreach my $cfile (@common_files)
3915     {
3916       if (dir_has_case_matching_file ($relative_dir, $cfile)
3917           # The file might be absent, but if it can be built it's ok.
3918           || rule $cfile)
3919         {
3920           &push_dist_common ($cfile);
3921         }
3923       # Don't use `elsif' here because a file might meaningfully
3924       # appear in both directories.
3925       if ($check_aux && dir_has_case_matching_file ($config_aux_dir, $cfile))
3926         {
3927           &push_dist_common ("$config_aux_dir/$cfile")
3928         }
3929     }
3931   # We might copy elements from $configure_dist_common to
3932   # %dist_common if we think we need to.  If the file appears in our
3933   # directory, we would have discovered it already, so we don't
3934   # check that.  But if the file is in a subdir without a Makefile,
3935   # we want to distribute it here if we are doing `.'.  Ugly!
3936   if ($relative_dir eq '.')
3937     {
3938       foreach my $file (split (' ' , $configure_dist_common))
3939         {
3940           push_dist_common ($file)
3941             unless is_make_dir (dirname ($file));
3942         }
3943     }
3945   # Files to distributed.  Don't use ->value_as_list_recursive
3946   # as it recursively expands `$(dist_pkgdata_DATA)' etc.
3947   my @dist_common = split (' ', rvar ('DIST_COMMON')->variable_value);
3948   @dist_common = uniq (sort for_dist_common (@dist_common));
3949   variable_delete 'DIST_COMMON';
3950   define_pretty_variable ('DIST_COMMON', TRUE, INTERNAL, @dist_common);
3952   # Now that we've processed DIST_COMMON, disallow further attempts
3953   # to set it.
3954   $handle_dist_run = 1;
3956   # Scan EXTRA_DIST to see if we need to distribute anything from a
3957   # subdir.  If so, add it to the list.  I didn't want to do this
3958   # originally, but there were so many requests that I finally
3959   # relented.
3960   my $extra_dist = var ('EXTRA_DIST');
3962   $transform{'DISTCHECK-HOOK'} = !! rule 'distcheck-hook';
3963   $transform{'GETTEXT'} = $seen_gettext && !$seen_gettext_external;
3965   # If the target `dist-hook' exists, make sure it is run.  This
3966   # allows users to do random weird things to the distribution
3967   # before it is packaged up.
3968   push (@dist_targets, 'dist-hook')
3969     if user_phony_rule 'dist-hook';
3970   $transform{'DIST-TARGETS'} = join (' ', @dist_targets);
3972   my $flm = option ('filename-length-max');
3973   my $filename_filter = $flm ? '.' x $flm->[1] : '';
3975   $output_rules .= &file_contents ('distdir',
3976                                    new Automake::Location,
3977                                    %transform,
3978                                    FILENAME_FILTER => $filename_filter);
3982 # check_directory ($NAME, $WHERE)
3983 # -------------------------------
3984 # Ensure $NAME is a directory, and that it uses a sane name.
3985 # Use $WHERE as a location in the diagnostic, if any.
3986 sub check_directory ($$)
3988   my ($dir, $where) = @_;
3990   error $where, "required directory $relative_dir/$dir does not exist"
3991     unless -d "$relative_dir/$dir";
3993   # If an `obj/' directory exists, BSD make will enter it before
3994   # reading `Makefile'.  Hence the `Makefile' in the current directory
3995   # will not be read.
3996   #
3997   #  % cat Makefile
3998   #  all:
3999   #          echo Hello
4000   #  % cat obj/Makefile
4001   #  all:
4002   #          echo World
4003   #  % make      # GNU make
4004   #  echo Hello
4005   #  Hello
4006   #  % pmake     # BSD make
4007   #  echo World
4008   #  World
4009   msg ('portability', $where,
4010        "naming a subdirectory `obj' causes troubles with BSD make")
4011     if $dir eq 'obj';
4013   # `aux' is probably the most important of the following forbidden name,
4014   # since it's tempting to use it as an AC_CONFIG_AUX_DIR.
4015   msg ('portability', $where,
4016        "name `$dir' is reserved on W32 and DOS platforms")
4017     if grep (/^\Q$dir\E$/i, qw/aux lpt1 lpt2 lpt3 com1 com2 com3 com4 con prn/);
4020 # check_directories_in_var ($VARIABLE)
4021 # ------------------------------------
4022 # Recursively check all items in variables $VARIABLE as directories
4023 sub check_directories_in_var ($)
4025   my ($var) = @_;
4026   $var->traverse_recursively
4027     (sub
4028      {
4029        my ($var, $val, $cond, $full_cond) = @_;
4030        check_directory ($val, $var->rdef ($cond)->location);
4031        return ();
4032      },
4033      undef,
4034      skip_ac_subst => 1);
4037 # &handle_subdirs ()
4038 # ------------------
4039 # Handle subdirectories.
4040 sub handle_subdirs ()
4042   my $subdirs = var ('SUBDIRS');
4043   return
4044     unless $subdirs;
4046   check_directories_in_var $subdirs;
4048   my $dsubdirs = var ('DIST_SUBDIRS');
4049   check_directories_in_var $dsubdirs
4050     if $dsubdirs;
4052   $output_rules .= &file_contents ('subdirs', new Automake::Location);
4053   rvar ('RECURSIVE_TARGETS')->rdef (TRUE)->{'pretty'} = VAR_SORTED; # Gross!
4057 # ($REGEN, @DEPENDENCIES)
4058 # &scan_aclocal_m4
4059 # ----------------
4060 # If aclocal.m4 creation is automated, return the list of its dependencies.
4061 sub scan_aclocal_m4 ()
4063   my $regen_aclocal = 0;
4065   set_seen 'CONFIG_STATUS_DEPENDENCIES';
4066   set_seen 'CONFIGURE_DEPENDENCIES';
4068   if (-f 'aclocal.m4')
4069     {
4070       &define_variable ("ACLOCAL_M4", '$(top_srcdir)/aclocal.m4', INTERNAL);
4072       my $aclocal = new Automake::XFile "< aclocal.m4";
4073       my $line = $aclocal->getline;
4074       $regen_aclocal = $line =~ 'generated automatically by aclocal';
4075     }
4077   my @ac_deps = ();
4079   if (set_seen ('ACLOCAL_M4_SOURCES'))
4080     {
4081       push (@ac_deps, '$(ACLOCAL_M4_SOURCES)');
4082       msg_var ('obsolete', 'ACLOCAL_M4_SOURCES',
4083                "`ACLOCAL_M4_SOURCES' is obsolete.\n"
4084                . "It should be safe to simply remove it.");
4085     }
4087   # Note that it might be possible that aclocal.m4 doesn't exist but
4088   # should be auto-generated.  This case probably isn't very
4089   # important.
4091   return ($regen_aclocal, @ac_deps);
4095 # Helper function for substitute_ac_subst_variables.
4096 sub substitute_ac_subst_variables_worker($)
4098   my ($token) = @_;
4099   return "\@$token\@" if var $token;
4100   return "\${$token\}";
4103 # substitute_ac_subst_variables ($TEXT)
4104 # -------------------------------------
4105 # Replace any occurrence of ${FOO} in $TEXT by @FOO@ if FOO is an AC_SUBST
4106 # variable.
4107 sub substitute_ac_subst_variables ($)
4109   my ($text) = @_;
4110   $text =~ s/\${([^ \t=:+{}]+)}/&substitute_ac_subst_variables_worker ($1)/ge;
4111   return $text;
4114 # @DEPENDENCIES
4115 # &prepend_srcdir (@INPUTS)
4116 # -------------------------
4117 # Prepend $(srcdir) or $(top_srcdir) to all @INPUTS.  The idea is that
4118 # if an input file has a directory part the same as the current
4119 # directory, then the directory part is simply replaced by $(srcdir).
4120 # But if the directory part is different, then $(top_srcdir) is
4121 # prepended.
4122 sub prepend_srcdir (@)
4124   my (@inputs) = @_;
4125   my @newinputs;
4127   foreach my $single (@inputs)
4128     {
4129       if (dirname ($single) eq $relative_dir)
4130         {
4131           push (@newinputs, '$(srcdir)/' . basename ($single));
4132         }
4133       else
4134         {
4135           push (@newinputs, '$(top_srcdir)/' . $single);
4136         }
4137     }
4138   return @newinputs;
4141 # @DEPENDENCIES
4142 # rewrite_inputs_into_dependencies ($OUTPUT, @INPUTS)
4143 # ---------------------------------------------------
4144 # Compute a list of dependencies appropriate for the rebuild
4145 # rule of
4146 #   AC_CONFIG_FILES($OUTPUT:$INPUT[0]:$INPUTS[1]:...)
4147 # Also distribute $INPUTs which are not built by another AC_CONFIG_FOOS.
4148 sub rewrite_inputs_into_dependencies ($@)
4150   my ($file, @inputs) = @_;
4151   my @res = ();
4153   for my $i (@inputs)
4154     {
4155       # We cannot create dependencies on shell variables.
4156       next if (substitute_ac_subst_variables $i) =~ /\$/;
4158       if (exists $ac_config_files_location{$i} && $i ne $file)
4159         {
4160           my $di = dirname $i;
4161           if ($di eq $relative_dir)
4162             {
4163               $i = basename $i;
4164             }
4165           # In the top-level Makefile we do not use $(top_builddir), because
4166           # we are already there, and since the targets are built without
4167           # a $(top_builddir), it helps BSD Make to match them with
4168           # dependencies.
4169           elsif ($relative_dir ne '.')
4170             {
4171               $i = '$(top_builddir)/' . $i;
4172             }
4173         }
4174       else
4175         {
4176           msg ('error', $ac_config_files_location{$file},
4177                "required file `$i' not found")
4178             unless $i =~ /\$/ || exists $output_files{$i} || -f $i;
4179           ($i) = prepend_srcdir ($i);
4180           push_dist_common ($i);
4181         }
4182       push @res, $i;
4183     }
4184   return @res;
4189 # &handle_configure ($MAKEFILE_AM, $MAKEFILE_IN, $MAKEFILE, @INPUTS)
4190 # ------------------------------------------------------------------
4191 # Handle remaking and configure stuff.
4192 # We need the name of the input file, to do proper remaking rules.
4193 sub handle_configure ($$$@)
4195   my ($makefile_am, $makefile_in, $makefile, @inputs) = @_;
4197   prog_error 'empty @inputs'
4198     unless @inputs;
4200   my ($rel_makefile_am, $rel_makefile_in) = prepend_srcdir ($makefile_am,
4201                                                             $makefile_in);
4202   my $rel_makefile = basename $makefile;
4204   my $colon_infile = ':' . join (':', @inputs);
4205   $colon_infile = '' if $colon_infile eq ":$makefile.in";
4206   my @rewritten = rewrite_inputs_into_dependencies ($makefile, @inputs);
4207   my ($regen_aclocal_m4, @aclocal_m4_deps) = scan_aclocal_m4;
4208   define_pretty_variable ('am__aclocal_m4_deps', TRUE, INTERNAL,
4209                           @configure_deps, @aclocal_m4_deps,
4210                           '$(top_srcdir)/' . $configure_ac);
4211   my @configuredeps = ('$(am__aclocal_m4_deps)', '$(CONFIGURE_DEPENDENCIES)');
4212   push @configuredeps, '$(ACLOCAL_M4)' if -f 'aclocal.m4';
4213   define_pretty_variable ('am__configure_deps', TRUE, INTERNAL,
4214                           @configuredeps);
4216   my $automake_options = '--' . (global_option 'cygnus' ? 'cygnus' : $strictness_name)
4217                          . (global_option 'no-dependencies' ? ' --ignore-deps' : '');
4219   $output_rules .= file_contents
4220     ('configure',
4221      new Automake::Location,
4222      MAKEFILE              => $rel_makefile,
4223      'MAKEFILE-DEPS'       => "@rewritten",
4224      'CONFIG-MAKEFILE'     => ($relative_dir eq '.') ? '$@' : '$(subdir)/$@',
4225      'MAKEFILE-IN'         => $rel_makefile_in,
4226      'MAKEFILE-IN-DEPS'    => "@include_stack",
4227      'MAKEFILE-AM'         => $rel_makefile_am,
4228      'AUTOMAKE-OPTIONS'    => $automake_options,
4229      'MAKEFILE-AM-SOURCES' => "$makefile$colon_infile",
4230      'REGEN-ACLOCAL-M4'    => $regen_aclocal_m4,
4231      VERBOSE               => verbose_flag ('GEN'));
4233   if ($relative_dir eq '.')
4234     {
4235       &push_dist_common ('acconfig.h')
4236         if -f 'acconfig.h';
4237     }
4239   # If we have a configure header, require it.
4240   my $hdr_index = 0;
4241   my @distclean_config;
4242   foreach my $spec (@config_headers)
4243     {
4244       $hdr_index += 1;
4245       # $CONFIG_H_PATH: config.h from top level.
4246       my ($config_h_path, @ins) = split_config_file_spec ($spec);
4247       my $config_h_dir = dirname ($config_h_path);
4249       # If the header is in the current directory we want to build
4250       # the header here.  Otherwise, if we're at the topmost
4251       # directory and the header's directory doesn't have a
4252       # Makefile, then we also want to build the header.
4253       if ($relative_dir eq $config_h_dir
4254           || ($relative_dir eq '.' && ! &is_make_dir ($config_h_dir)))
4255         {
4256           my ($cn_sans_dir, $stamp_dir);
4257           if ($relative_dir eq $config_h_dir)
4258             {
4259               $cn_sans_dir = basename ($config_h_path);
4260               $stamp_dir = '';
4261             }
4262           else
4263             {
4264               $cn_sans_dir = $config_h_path;
4265               if ($config_h_dir eq '.')
4266                 {
4267                   $stamp_dir = '';
4268                 }
4269               else
4270                 {
4271                   $stamp_dir = $config_h_dir . '/';
4272                 }
4273             }
4275           # This will also distribute all inputs.
4276           @ins = rewrite_inputs_into_dependencies ($config_h_path, @ins);
4278           # Cannot define rebuild rules for filenames with shell variables.
4279           next if (substitute_ac_subst_variables $config_h_path) =~ /\$/;
4281           # Header defined in this directory.
4282           my @files;
4283           if (-f $config_h_path . '.top')
4284             {
4285               push (@files, "$cn_sans_dir.top");
4286             }
4287           if (-f $config_h_path . '.bot')
4288             {
4289               push (@files, "$cn_sans_dir.bot");
4290             }
4292           push_dist_common (@files);
4294           # For now, acconfig.h can only appear in the top srcdir.
4295           if (-f 'acconfig.h')
4296             {
4297               push (@files, '$(top_srcdir)/acconfig.h');
4298             }
4300           my $stamp = "${stamp_dir}stamp-h${hdr_index}";
4301           $output_rules .=
4302             file_contents ('remake-hdr',
4303                            new Automake::Location,
4304                            FILES            => "@files",
4305                            CONFIG_H         => $cn_sans_dir,
4306                            CONFIG_HIN       => $ins[0],
4307                            CONFIG_H_DEPS    => "@ins",
4308                            CONFIG_H_PATH    => $config_h_path,
4309                            STAMP            => "$stamp");
4311           push @distclean_config, $cn_sans_dir, $stamp;
4312         }
4313     }
4315   $output_rules .= file_contents ('clean-hdr',
4316                                   new Automake::Location,
4317                                   FILES => "@distclean_config")
4318     if @distclean_config;
4320   # Distribute and define mkinstalldirs only if it is already present
4321   # in the package, for backward compatibility (some people may still
4322   # use $(mkinstalldirs)).
4323   my $mkidpath = "$config_aux_dir/mkinstalldirs";
4324   if (-f $mkidpath)
4325     {
4326       # Use require_file so that any existing script gets updated
4327       # by --force-missing.
4328       require_conf_file ($mkidpath, FOREIGN, 'mkinstalldirs');
4329       define_variable ('mkinstalldirs',
4330                        "\$(SHELL) $am_config_aux_dir/mkinstalldirs", INTERNAL);
4331     }
4332   else
4333     {
4334       # Use $(install_sh), not $(MKDIR_P) because the latter requires
4335       # at least one argument, and $(mkinstalldirs) used to work
4336       # even without arguments (e.g. $(mkinstalldirs) $(conditional_dir)).
4337       define_variable ('mkinstalldirs', '$(install_sh) -d', INTERNAL);
4338     }
4340   reject_var ('CONFIG_HEADER',
4341               "`CONFIG_HEADER' is an anachronism; now determined "
4342               . "automatically\nfrom `$configure_ac'");
4344   my @config_h;
4345   foreach my $spec (@config_headers)
4346     {
4347       my ($out, @ins) = split_config_file_spec ($spec);
4348       # Generate CONFIG_HEADER define.
4349       if ($relative_dir eq dirname ($out))
4350         {
4351           push @config_h, basename ($out);
4352         }
4353       else
4354         {
4355           push @config_h, "\$(top_builddir)/$out";
4356         }
4357     }
4358   define_variable ("CONFIG_HEADER", "@config_h", INTERNAL)
4359     if @config_h;
4361   # Now look for other files in this directory which must be remade
4362   # by config.status, and generate rules for them.
4363   my @actual_other_files = ();
4364   # These get cleaned only in a VPATH build.
4365   my @actual_other_vpath_files = ();
4366   foreach my $lfile (@other_input_files)
4367     {
4368       my $file;
4369       my @inputs;
4370       if ($lfile =~ /^([^:]*):(.*)$/)
4371         {
4372           # This is the ":" syntax of AC_OUTPUT.
4373           $file = $1;
4374           @inputs = split (':', $2);
4375         }
4376       else
4377         {
4378           # Normal usage.
4379           $file = $lfile;
4380           @inputs = $file . '.in';
4381         }
4383       # Automake files should not be stored in here, but in %MAKE_LIST.
4384       prog_error ("$lfile in \@other_input_files\n"
4385                   . "\@other_input_files = (@other_input_files)")
4386         if -f $file . '.am';
4388       my $local = basename ($file);
4390       # We skip files that aren't in this directory.  However, if
4391       # the file's directory does not have a Makefile, and we are
4392       # currently doing `.', then we create a rule to rebuild the
4393       # file in the subdir.
4394       my $fd = dirname ($file);
4395       if ($fd ne $relative_dir)
4396         {
4397           if ($relative_dir eq '.' && ! &is_make_dir ($fd))
4398             {
4399               $local = $file;
4400             }
4401           else
4402             {
4403               next;
4404             }
4405         }
4407       my @rewritten_inputs = rewrite_inputs_into_dependencies ($file, @inputs);
4409       # Cannot output rules for shell variables.
4410       next if (substitute_ac_subst_variables $local) =~ /\$/;
4412       my $condstr = '';
4413       my $cond = $ac_config_files_condition{$lfile};
4414       if (defined $cond)
4415         {
4416           $condstr = $cond->subst_string;
4417           Automake::Rule::define ($local, $configure_ac, RULE_AUTOMAKE, $cond,
4418                                   $ac_config_files_location{$file});
4419         }
4420       $output_rules .= ($condstr . $local . ': '
4421                         . '$(top_builddir)/config.status '
4422                         . "@rewritten_inputs\n"
4423                         . $condstr . "\t"
4424                         . 'cd $(top_builddir) && '
4425                         . '$(SHELL) ./config.status '
4426                         . ($relative_dir eq '.' ? '' : '$(subdir)/')
4427                         . '$@'
4428                         . "\n");
4429       push (@actual_other_files, $local);
4430     }
4432   # For links we should clean destinations and distribute sources.
4433   foreach my $spec (@config_links)
4434     {
4435       my ($link, $file) = split /:/, $spec;
4436       # Some people do AC_CONFIG_LINKS($computed).  We only handle
4437       # the DEST:SRC form.
4438       next unless $file;
4439       my $where = $ac_config_files_location{$link};
4441       # Skip destinations that contain shell variables.
4442       if ((substitute_ac_subst_variables $link) !~ /\$/)
4443         {
4444           # We skip links that aren't in this directory.  However, if
4445           # the link's directory does not have a Makefile, and we are
4446           # currently doing `.', then we add the link to CONFIG_CLEAN_FILES
4447           # in `.'s Makefile.in.
4448           my $local = basename ($link);
4449           my $fd = dirname ($link);
4450           if ($fd ne $relative_dir)
4451             {
4452               if ($relative_dir eq '.' && ! &is_make_dir ($fd))
4453                 {
4454                   $local = $link;
4455                 }
4456               else
4457                 {
4458                   $local = undef;
4459                 }
4460             }
4461           if ($file ne $link)
4462             {
4463               push @actual_other_files, $local if $local;
4464             }
4465           else
4466             {
4467               push @actual_other_vpath_files, $local if $local;
4468             }
4469         }
4471       # Do not process sources that contain shell variables.
4472       if ((substitute_ac_subst_variables $file) !~ /\$/)
4473         {
4474           my $fd = dirname ($file);
4476           # We distribute files that are in this directory.
4477           # At the top-level (`.') we also distribute files whose
4478           # directory does not have a Makefile.
4479           if (($fd eq $relative_dir)
4480               || ($relative_dir eq '.' && ! &is_make_dir ($fd)))
4481             {
4482               # The following will distribute $file as a side-effect when
4483               # it is appropriate (i.e., when $file is not already an output).
4484               # We do not need the result, just the side-effect.
4485               rewrite_inputs_into_dependencies ($link, $file);
4486             }
4487         }
4488     }
4490   # These files get removed by "make distclean".
4491   define_pretty_variable ('CONFIG_CLEAN_FILES', TRUE, INTERNAL,
4492                           @actual_other_files);
4493   define_pretty_variable ('CONFIG_CLEAN_VPATH_FILES', TRUE, INTERNAL,
4494                           @actual_other_vpath_files);
4497 # Handle C headers.
4498 sub handle_headers
4500     my @r = &am_install_var ('-defaultdist', 'header', 'HEADERS', 'include',
4501                              'oldinclude', 'pkginclude',
4502                              'noinst', 'check');
4503     foreach (@r)
4504     {
4505       next unless $_->[1] =~ /\..*$/;
4506       &saw_extension ($&);
4507     }
4510 sub handle_gettext
4512   return if ! $seen_gettext || $relative_dir ne '.';
4514   my $subdirs = var 'SUBDIRS';
4516   if (! $subdirs)
4517     {
4518       err_ac "AM_GNU_GETTEXT used but SUBDIRS not defined";
4519       return;
4520     }
4522   # Perform some sanity checks to help users get the right setup.
4523   # We disable these tests when po/ doesn't exist in order not to disallow
4524   # unusual gettext setups.
4525   #
4526   # Bruno Haible:
4527   # | The idea is:
4528   # |
4529   # |  1) If a package doesn't have a directory po/ at top level, it
4530   # |     will likely have multiple po/ directories in subpackages.
4531   # |
4532   # |  2) It is useful to warn for the absence of intl/ if AM_GNU_GETTEXT
4533   # |     is used without 'external'. It is also useful to warn for the
4534   # |     presence of intl/ if AM_GNU_GETTEXT([external]) is used. Both
4535   # |     warnings apply only to the usual layout of packages, therefore
4536   # |     they should both be disabled if no po/ directory is found at
4537   # |     top level.
4539   if (-d 'po')
4540     {
4541       my @subdirs = $subdirs->value_as_list_recursive;
4543       msg_var ('syntax', $subdirs,
4544                "AM_GNU_GETTEXT used but `po' not in SUBDIRS")
4545         if ! grep ($_ eq 'po', @subdirs);
4547       # intl/ is not required when AM_GNU_GETTEXT is called with the
4548       # `external' option and AM_GNU_GETTEXT_INTL_SUBDIR is not called.
4549       msg_var ('syntax', $subdirs,
4550                "AM_GNU_GETTEXT used but `intl' not in SUBDIRS")
4551         if (! ($seen_gettext_external && ! $seen_gettext_intl)
4552             && ! grep ($_ eq 'intl', @subdirs));
4554       # intl/ should not be used with AM_GNU_GETTEXT([external]), except
4555       # if AM_GNU_GETTEXT_INTL_SUBDIR is called.
4556       msg_var ('syntax', $subdirs,
4557                "`intl' should not be in SUBDIRS when "
4558                . "AM_GNU_GETTEXT([external]) is used")
4559         if ($seen_gettext_external && ! $seen_gettext_intl
4560             && grep ($_ eq 'intl', @subdirs));
4561     }
4563   require_file ($ac_gettext_location, GNU, 'ABOUT-NLS');
4566 # Handle footer elements.
4567 sub handle_footer
4569     reject_rule ('.SUFFIXES',
4570                  "use variable `SUFFIXES', not target `.SUFFIXES'");
4572     # Note: AIX 4.1 /bin/make will fail if any suffix rule appears
4573     # before .SUFFIXES.  So we make sure that .SUFFIXES appears before
4574     # anything else, by sticking it right after the default: target.
4575     $output_header .= ".SUFFIXES:\n";
4576     my $suffixes = var 'SUFFIXES';
4577     my @suffixes = Automake::Rule::suffixes;
4578     if (@suffixes || $suffixes)
4579     {
4580         # Make sure SUFFIXES has unique elements.  Sort them to ensure
4581         # the output remains consistent.  However, $(SUFFIXES) is
4582         # always at the start of the list, unsorted.  This is done
4583         # because make will choose rules depending on the ordering of
4584         # suffixes, and this lets the user have some control.  Push
4585         # actual suffixes, and not $(SUFFIXES).  Some versions of make
4586         # do not like variable substitutions on the .SUFFIXES line.
4587         my @user_suffixes = ($suffixes
4588                              ? $suffixes->value_as_list_recursive : ());
4590         my %suffixes = map { $_ => 1 } @suffixes;
4591         delete @suffixes{@user_suffixes};
4593         $output_header .= (".SUFFIXES: "
4594                            . join (' ', @user_suffixes, sort keys %suffixes)
4595                            . "\n");
4596     }
4598     $output_trailer .= file_contents ('footer', new Automake::Location);
4602 # Generate `make install' rules.
4603 sub handle_install ()
4605   $output_rules .= &file_contents
4606     ('install',
4607      new Automake::Location,
4608      maybe_BUILT_SOURCES => (set_seen ('BUILT_SOURCES')
4609                              ? (" \$(BUILT_SOURCES)\n"
4610                                 . "\t\$(MAKE) \$(AM_MAKEFLAGS)")
4611                              : ''),
4612      'installdirs-local' => (user_phony_rule 'installdirs-local'
4613                              ? ' installdirs-local' : ''),
4614      am__installdirs => variable_value ('am__installdirs') || '');
4618 # Deal with all and all-am.
4619 sub handle_all ($)
4621     my ($makefile) = @_;
4623     # Output `all-am'.
4625     # Put this at the beginning for the sake of non-GNU makes.  This
4626     # is still wrong if these makes can run parallel jobs.  But it is
4627     # right enough.
4628     unshift (@all, basename ($makefile));
4630     foreach my $spec (@config_headers)
4631       {
4632         my ($out, @ins) = split_config_file_spec ($spec);
4633         push (@all, basename ($out))
4634           if dirname ($out) eq $relative_dir;
4635       }
4637     # Install `all' hooks.
4638     push (@all, "all-local")
4639       if user_phony_rule "all-local";
4641     &pretty_print_rule ("all-am:", "\t\t", @all);
4642     &depend ('.PHONY', 'all-am', 'all');
4645     # Output `all'.
4647     my @local_headers = ();
4648     push @local_headers, '$(BUILT_SOURCES)'
4649       if var ('BUILT_SOURCES');
4650     foreach my $spec (@config_headers)
4651       {
4652         my ($out, @ins) = split_config_file_spec ($spec);
4653         push @local_headers, basename ($out)
4654           if dirname ($out) eq $relative_dir;
4655       }
4657     if (@local_headers)
4658       {
4659         # We need to make sure config.h is built before we recurse.
4660         # We also want to make sure that built sources are built
4661         # before any ordinary `all' targets are run.  We can't do this
4662         # by changing the order of dependencies to the "all" because
4663         # that breaks when using parallel makes.  Instead we handle
4664         # things explicitly.
4665         $output_all .= ("all: @local_headers"
4666                         . "\n\t"
4667                         . '$(MAKE) $(AM_MAKEFLAGS) '
4668                         . (var ('SUBDIRS') ? 'all-recursive' : 'all-am')
4669                         . "\n\n");
4670         depend ('.MAKE', 'all');
4671       }
4672     else
4673       {
4674         $output_all .= "all: " . (var ('SUBDIRS')
4675                                   ? 'all-recursive' : 'all-am') . "\n\n";
4676       }
4680 # &do_check_merge_target ()
4681 # -------------------------
4682 # Handle check merge target specially.
4683 sub do_check_merge_target ()
4685   # Include user-defined local form of target.
4686   push @check_tests, 'check-local'
4687     if user_phony_rule 'check-local';
4689   # In --cygnus mode, check doesn't depend on all.
4690   if (option 'cygnus')
4691     {
4692       # Just run the local check rules.
4693       pretty_print_rule ('check-am:', "\t\t", @check);
4694     }
4695   else
4696     {
4697       # The check target must depend on the local equivalent of
4698       # `all', to ensure all the primary targets are built.  Then it
4699       # must build the local check rules.
4700       $output_rules .= "check-am: all-am\n";
4701       if (@check)
4702         {
4703           pretty_print_rule ("\t\$(MAKE) \$(AM_MAKEFLAGS)", "\t  ",
4704                              @check);
4705           depend ('.MAKE', 'check-am');
4706         }
4707     }
4708   if (@check_tests)
4709     {
4710       pretty_print_rule ("\t\$(MAKE) \$(AM_MAKEFLAGS)", "\t  ",
4711                          @check_tests);
4712       depend ('.MAKE', 'check-am');
4713     }
4715   depend '.PHONY', 'check', 'check-am';
4716   # Handle recursion.  We have to honor BUILT_SOURCES like for `all:'.
4717   $output_rules .= ("check: "
4718                     . (var ('BUILT_SOURCES')
4719                        ? "\$(BUILT_SOURCES)\n\t\$(MAKE) \$(AM_MAKEFLAGS) "
4720                        : '')
4721                     . (var ('SUBDIRS') ? 'check-recursive' : 'check-am')
4722                     . "\n");
4723   depend ('.MAKE', 'check')
4724     if var ('BUILT_SOURCES');
4727 # handle_clean ($MAKEFILE)
4728 # ------------------------
4729 # Handle all 'clean' targets.
4730 sub handle_clean ($)
4732   my ($makefile) = @_;
4734   # Clean the files listed in user variables if they exist.
4735   $clean_files{'$(MOSTLYCLEANFILES)'} = MOSTLY_CLEAN
4736     if var ('MOSTLYCLEANFILES');
4737   $clean_files{'$(CLEANFILES)'} = CLEAN
4738     if var ('CLEANFILES');
4739   $clean_files{'$(DISTCLEANFILES)'} = DIST_CLEAN
4740     if var ('DISTCLEANFILES');
4741   $clean_files{'$(MAINTAINERCLEANFILES)'} = MAINTAINER_CLEAN
4742     if var ('MAINTAINERCLEANFILES');
4744   # Built sources are automatically removed by maintainer-clean.
4745   $clean_files{'$(BUILT_SOURCES)'} = MAINTAINER_CLEAN
4746     if var ('BUILT_SOURCES');
4748   # Compute a list of "rm"s to run for each target.
4749   my %rms = (MOSTLY_CLEAN, [],
4750              CLEAN, [],
4751              DIST_CLEAN, [],
4752              MAINTAINER_CLEAN, []);
4754   foreach my $file (keys %clean_files)
4755     {
4756       my $when = $clean_files{$file};
4757       prog_error 'invalid entry in %clean_files'
4758         unless exists $rms{$when};
4760       my $rm = "rm -f $file";
4761       # If file is a variable, make sure when don't call `rm -f' without args.
4762       $rm ="test -z \"$file\" || $rm"
4763         if ($file =~ /^\s*\$(\(.*\)|\{.*\})\s*$/);
4765       push @{$rms{$when}}, "\t-$rm\n";
4766     }
4768   $output_rules .= &file_contents
4769     ('clean',
4770      new Automake::Location,
4771      MOSTLYCLEAN_RMS      => join ('', sort @{$rms{&MOSTLY_CLEAN}}),
4772      CLEAN_RMS            => join ('', sort @{$rms{&CLEAN}}),
4773      DISTCLEAN_RMS        => join ('', sort @{$rms{&DIST_CLEAN}}),
4774      MAINTAINER_CLEAN_RMS => join ('', sort @{$rms{&MAINTAINER_CLEAN}}),
4775      MAKEFILE             => basename $makefile,
4776      );
4780 # &target_cmp ($A, $B)
4781 # --------------------
4782 # Subroutine for &handle_factored_dependencies to let `.PHONY' and
4783 # other `.TARGETS' be last.
4784 sub target_cmp
4786   return 0 if $a eq $b;
4788   my $a1 = substr ($a, 0, 1);
4789   my $b1 = substr ($b, 0, 1);
4790   if ($a1 ne $b1)
4791     {
4792       return -1 if $b1 eq '.';
4793       return 1 if $a1 eq '.';
4794     }
4795   return $a cmp $b;
4799 # &handle_factored_dependencies ()
4800 # --------------------------------
4801 # Handle everything related to gathered targets.
4802 sub handle_factored_dependencies
4804   # Reject bad hooks.
4805   foreach my $utarg ('uninstall-data-local', 'uninstall-data-hook',
4806                      'uninstall-exec-local', 'uninstall-exec-hook',
4807                      'uninstall-dvi-local',
4808                      'uninstall-html-local',
4809                      'uninstall-info-local',
4810                      'uninstall-pdf-local',
4811                      'uninstall-ps-local')
4812     {
4813       my $x = $utarg;
4814       $x =~ s/-.*-/-/;
4815       reject_rule ($utarg, "use `$x', not `$utarg'");
4816     }
4818   reject_rule ('install-local',
4819                "use `install-data-local' or `install-exec-local', "
4820                . "not `install-local'");
4822   reject_rule ('install-hook',
4823                "use `install-data-hook' or `install-exec-hook', "
4824                . "not `install-hook'");
4826   # Install the -local hooks.
4827   foreach (keys %dependencies)
4828     {
4829       # Hooks are installed on the -am targets.
4830       s/-am$// or next;
4831       depend ("$_-am", "$_-local")
4832         if user_phony_rule "$_-local";
4833     }
4835   # Install the -hook hooks.
4836   # FIXME: Why not be as liberal as we are with -local hooks?
4837   foreach ('install-exec', 'install-data', 'uninstall')
4838     {
4839       if (user_phony_rule "$_-hook")
4840         {
4841           depend ('.MAKE', "$_-am");
4842           register_action("$_-am",
4843                           ("\t\@\$(NORMAL_INSTALL)\n"
4844                            . "\t\$(MAKE) \$(AM_MAKEFLAGS) $_-hook"));
4845         }
4846     }
4848   # All the required targets are phony.
4849   depend ('.PHONY', keys %required_targets);
4851   # Actually output gathered targets.
4852   foreach (sort target_cmp keys %dependencies)
4853     {
4854       # If there is nothing about this guy, skip it.
4855       next
4856         unless (@{$dependencies{$_}}
4857                 || $actions{$_}
4858                 || $required_targets{$_});
4860       # Define gathered targets in undefined conditions.
4861       # FIXME: Right now we must handle .PHONY as an exception,
4862       # because people write things like
4863       #    .PHONY: myphonytarget
4864       # to append dependencies.  This would not work if Automake
4865       # refrained from defining its own .PHONY target as it does
4866       # with other overridden targets.
4867       # Likewise for `.MAKE'.
4868       my @undefined_conds = (TRUE,);
4869       if ($_ ne '.PHONY' && $_ ne '.MAKE')
4870         {
4871           @undefined_conds =
4872             Automake::Rule::define ($_, 'internal',
4873                                     RULE_AUTOMAKE, TRUE, INTERNAL);
4874         }
4875       my @uniq_deps = uniq (sort @{$dependencies{$_}});
4876       foreach my $cond (@undefined_conds)
4877         {
4878           my $condstr = $cond->subst_string;
4879           &pretty_print_rule ("$condstr$_:", "$condstr\t", @uniq_deps);
4880           $output_rules .= $actions{$_} if defined $actions{$_};
4881           $output_rules .= "\n";
4882         }
4883     }
4887 # &handle_tests_dejagnu ()
4888 # ------------------------
4889 sub handle_tests_dejagnu
4891     push (@check_tests, 'check-DEJAGNU');
4892     $output_rules .= file_contents ('dejagnu', new Automake::Location);
4896 # Handle TESTS variable and other checks.
4897 sub handle_tests
4899   if (option 'dejagnu')
4900     {
4901       &handle_tests_dejagnu;
4902     }
4903   else
4904     {
4905       foreach my $c ('DEJATOOL', 'RUNTEST', 'RUNTESTFLAGS')
4906         {
4907           reject_var ($c, "`$c' defined but `dejagnu' not in "
4908                       . "`AUTOMAKE_OPTIONS'");
4909         }
4910     }
4912   if (var ('TESTS'))
4913     {
4914       push (@check_tests, 'check-TESTS');
4915       $output_rules .= &file_contents ('check', new Automake::Location,
4916                                        COLOR => !! option 'color-tests',
4917                                        PARALLEL_TESTS => !! option 'parallel-tests');
4919       # Tests that are known programs should have $(EXEEXT) appended.
4920       # For matching purposes, we need to adjust XFAIL_TESTS as well.
4921       append_exeext { exists $known_programs{$_[0]} } 'TESTS';
4922       append_exeext { exists $known_programs{$_[0]} } 'XFAIL_TESTS'
4923         if (var ('XFAIL_TESTS'));
4925       if (option 'parallel-tests')
4926         {
4927           define_variable ('TEST_SUITE_LOG', 'test-suite.log', INTERNAL);
4928           define_variable ('TEST_SUITE_HTML', '$(TEST_SUITE_LOG:.log=.html)', INTERNAL);
4929           my $suff = '.test';
4930           my $at_exeext = '';
4931           my $handle_exeext = exists $configure_vars{'EXEEXT'};
4932           if ($handle_exeext)
4933             {
4934               $at_exeext = subst ('EXEEXT');
4935               $suff = $at_exeext  . ' ' . $suff;
4936             }
4937           define_variable ('TEST_EXTENSIONS', $suff, INTERNAL);
4938           # FIXME: this mishandles conditions.
4939           my @test_suffixes = (var 'TEST_EXTENSIONS')->value_as_list_recursive;
4940           if ($handle_exeext)
4941             {
4942               unshift (@test_suffixes, $at_exeext)
4943                 unless $test_suffixes[0] eq $at_exeext;
4944             }
4945           unshift (@test_suffixes, '');
4947           transform_variable_recursively
4948             ('TESTS', 'TEST_LOGS', 'am__testlogs', 1, INTERNAL,
4949               sub {
4950                 my ($subvar, $val, $cond, $full_cond) = @_;
4951                 my $obj = $val;
4952                 return $obj
4953                   if $val =~ /^\@.*\@$/;
4954                 $obj =~ s/\$\(EXEEXT\)$//o;
4956                 if ($val =~ /(\$\((top_)?srcdir\))\//o)
4957                   {
4958                     msg ('error', $subvar->rdef ($cond)->location,
4959                          "parallel-tests: using `$1' in TESTS is currently broken: `$val'");
4960                   }
4962                 foreach my $test_suffix (@test_suffixes)
4963                   {
4964                     next
4965                       if $test_suffix eq $at_exeext || $test_suffix eq '';
4966                     return substr ($obj, 0, length ($obj) - length ($test_suffix)) . '.log'
4967                       if substr ($obj, - length ($test_suffix)) eq $test_suffix;
4968                   }
4969                 $obj .= '.log';
4970                 my $compile = 'LOG_COMPILE';
4971                 define_variable ($compile,
4972                                  '$(LOG_COMPILER) $(AM_LOG_FLAGS) $(LOG_FLAGS)', INTERNAL);
4973                 $output_rules .= file_contents ('check2', new Automake::Location,
4974                                                 GENERIC => 0,
4975                                                 OBJ => $obj,
4976                                                 SOURCE => $val,
4977                                                 COMPILE =>'$(' . $compile . ')',
4978                                                 EXT => '',
4979                                                 am__EXEEXT => 'FALSE');
4980                 return $obj;
4981               });
4983           my $nhelper=1;
4984           my $prev = 'TESTS';
4985           my $post = '';
4986           my $last_suffix = $test_suffixes[$#test_suffixes];
4987           my $cur = '';
4988           foreach my $test_suffix (@test_suffixes)
4989             {
4990               if ($test_suffix eq $last_suffix)
4991                 {
4992                   $cur = 'TEST_LOGS';
4993                 }
4994               else
4995                 {
4996                   $cur = 'am__test_logs' . $nhelper;
4997                 }
4998               define_variable ($cur,
4999                 '$(' . $prev . ':' . $test_suffix . $post . '=.log)', INTERNAL);
5000               $post = '.log';
5001               $prev = $cur;
5002               $nhelper++;
5003               if ($test_suffix ne $at_exeext && $test_suffix ne '')
5004                 {
5005                   (my $ext = $test_suffix) =~ s/^\.//;
5006                   $ext = uc $ext;
5007                   my $compile = $ext . '_LOG_COMPILE';
5008                   define_variable ($compile,
5009                                    '$(' . $ext . '_LOG_COMPILER) $(AM_' .  $ext . '_LOG_FLAGS)'
5010                                    . ' $(' . $ext . '_LOG_FLAGS)', INTERNAL);
5011                   my $am_exeext = $handle_exeext ? 'am__EXEEXT' : 'FALSE';
5012                   $output_rules .= file_contents ('check2', new Automake::Location,
5013                                                   GENERIC => 1,
5014                                                   OBJ => '',
5015                                                   SOURCE => '$<',
5016                                                   COMPILE => '$(' . $compile . ')',
5017                                                   EXT => $test_suffix,
5018                                                   am__EXEEXT => $am_exeext);
5019                 }
5020             }
5022           define_variable ('TEST_LOGS_TMP', '$(TEST_LOGS:.log=.log-t)', INTERNAL);
5024           $clean_files{'$(TEST_LOGS_TMP)'} = MOSTLY_CLEAN;
5025           $clean_files{'$(TEST_LOGS)'} = MOSTLY_CLEAN;
5026           $clean_files{'$(TEST_SUITE_LOG)'} = MOSTLY_CLEAN;
5027           $clean_files{'$(TEST_SUITE_HTML)'} = MOSTLY_CLEAN;
5028         }
5029     }
5032 # Handle Emacs Lisp.
5033 sub handle_emacs_lisp
5035   my @elfiles = &am_install_var ('-candist', 'lisp', 'LISP',
5036                                  'lisp', 'noinst');
5038   return if ! @elfiles;
5040   define_pretty_variable ('am__ELFILES', TRUE, INTERNAL,
5041                           map { $_->[1] } @elfiles);
5042   define_pretty_variable ('am__ELCFILES', TRUE, INTERNAL,
5043                           '$(am__ELFILES:.el=.elc)');
5044   # This one can be overridden by users.
5045   define_pretty_variable ('ELCFILES', TRUE, INTERNAL, '$(LISP:.el=.elc)');
5047   push @all, '$(ELCFILES)';
5049   require_variables ($elfiles[0][0], "Emacs Lisp sources seen", TRUE,
5050                      'EMACS', 'lispdir');
5051   require_conf_file ($elfiles[0][0], FOREIGN, 'elisp-comp');
5052   &define_variable ('elisp_comp', "$am_config_aux_dir/elisp-comp", INTERNAL);
5055 # Handle Python
5056 sub handle_python
5058   my @pyfiles = &am_install_var ('-defaultdist', 'python', 'PYTHON',
5059                                  'noinst');
5060   return if ! @pyfiles;
5062   require_variables ($pyfiles[0][0], "Python sources seen", TRUE, 'PYTHON');
5063   require_conf_file ($pyfiles[0][0], FOREIGN, 'py-compile');
5064   &define_variable ('py_compile', "$am_config_aux_dir/py-compile", INTERNAL);
5067 # Handle Java.
5068 sub handle_java
5070     my @sourcelist = &am_install_var ('-candist',
5071                                       'java', 'JAVA',
5072                                       'java', 'noinst', 'check');
5073     return if ! @sourcelist;
5075     my @prefix = am_primary_prefixes ('JAVA', 1,
5076                                       'java', 'noinst', 'check');
5078     my $dir;
5079     foreach my $curs (@prefix)
5080       {
5081         next
5082           if $curs eq 'EXTRA';
5084         err_var "${curs}_JAVA", "multiple _JAVA primaries in use"
5085           if defined $dir;
5086         $dir = $curs;
5087       }
5090     push (@all, 'class' . $dir . '.stamp');
5094 # Handle some of the minor options.
5095 sub handle_minor_options
5097   if (option 'readme-alpha')
5098     {
5099       if ($relative_dir eq '.')
5100         {
5101           if ($package_version !~ /^$GNITS_VERSION_PATTERN$/)
5102             {
5103               msg ('error-gnits', $package_version_location,
5104                    "version `$package_version' doesn't follow " .
5105                    "Gnits standards");
5106             }
5107           if (defined $1 && -f 'README-alpha')
5108             {
5109               # This means we have an alpha release.  See
5110               # GNITS_VERSION_PATTERN for details.
5111               push_dist_common ('README-alpha');
5112             }
5113         }
5114     }
5117 ################################################################
5119 # ($OUTPUT, @INPUTS)
5120 # &split_config_file_spec ($SPEC)
5121 # -------------------------------
5122 # Decode the Autoconf syntax for config files (files, headers, links
5123 # etc.).
5124 sub split_config_file_spec ($)
5126   my ($spec) = @_;
5127   my ($output, @inputs) = split (/:/, $spec);
5129   push @inputs, "$output.in"
5130     unless @inputs;
5132   return ($output, @inputs);
5135 # $input
5136 # locate_am (@POSSIBLE_SOURCES)
5137 # -----------------------------
5138 # AC_CONFIG_FILES allow specifications such as Makefile:top.in:mid.in:bot.in
5139 # This functions returns the first *.in file for which a *.am exists.
5140 # It returns undef otherwise.
5141 sub locate_am (@)
5143   my (@rest) = @_;
5144   my $input;
5145   foreach my $file (@rest)
5146     {
5147       if (($file =~ /^(.*)\.in$/) && -f "$1.am")
5148         {
5149           $input = $file;
5150           last;
5151         }
5152     }
5153   return $input;
5156 my %make_list;
5158 # &scan_autoconf_config_files ($WHERE, $CONFIG-FILES)
5159 # ---------------------------------------------------
5160 # Study $CONFIG-FILES which is the first argument to AC_CONFIG_FILES
5161 # (or AC_OUTPUT).
5162 sub scan_autoconf_config_files ($$)
5164   my ($where, $config_files) = @_;
5166   # Look at potential Makefile.am's.
5167   foreach (split ' ', $config_files)
5168     {
5169       # Must skip empty string for Perl 4.
5170       next if $_ eq "\\" || $_ eq '';
5172       # Handle $local:$input syntax.
5173       my ($local, @rest) = split (/:/);
5174       @rest = ("$local.in",) unless @rest;
5175       msg ('portability', $where,
5176           "Omit leading `./' from config file names such as `$local',"
5177           . "\nas not all make implementations treat `file' and `./file' equally.")
5178         if ($local =~ /^\.\//);
5179       my $input = locate_am @rest;
5180       if ($input)
5181         {
5182           # We have a file that automake should generate.
5183           $make_list{$input} = join (':', ($local, @rest));
5184         }
5185       else
5186         {
5187           # We have a file that automake should cause to be
5188           # rebuilt, but shouldn't generate itself.
5189           push (@other_input_files, $_);
5190         }
5191       $ac_config_files_location{$local} = $where;
5192       $ac_config_files_condition{$local} =
5193         new Automake::Condition (@cond_stack)
5194           if (@cond_stack);
5195     }
5199 # &scan_autoconf_traces ($FILENAME)
5200 # ---------------------------------
5201 sub scan_autoconf_traces ($)
5203   my ($filename) = @_;
5205   # Macros to trace, with their minimal number of arguments.
5206   #
5207   # IMPORTANT: If you add a macro here, you should also add this macro
5208   # =========  to Automake-preselection in autoconf/lib/autom4te.in.
5209   my %traced = (
5210                 AC_CANONICAL_BUILD => 0,
5211                 AC_CANONICAL_HOST => 0,
5212                 AC_CANONICAL_TARGET => 0,
5213                 AC_CONFIG_AUX_DIR => 1,
5214                 AC_CONFIG_FILES => 1,
5215                 AC_CONFIG_HEADERS => 1,
5216                 AC_CONFIG_LIBOBJ_DIR => 1,
5217                 AC_CONFIG_LINKS => 1,
5218                 AC_FC_SRCEXT => 1,
5219                 AC_INIT => 0,
5220                 AC_LIBSOURCE => 1,
5221                 AC_REQUIRE_AUX_FILE => 1,
5222                 AC_SUBST_TRACE => 1,
5223                 AM_AUTOMAKE_VERSION => 1,
5224                 AM_CONDITIONAL => 2,
5225                 AM_ENABLE_MULTILIB => 0,
5226                 AM_GNU_GETTEXT => 0,
5227                 AM_GNU_GETTEXT_INTL_SUBDIR => 0,
5228                 AM_INIT_AUTOMAKE => 0,
5229                 AM_MAINTAINER_MODE => 0,
5230                 AM_PROG_CC_C_O => 0,
5231                 AM_SILENT_RULES => 0,
5232                 _AM_SUBST_NOTMAKE => 1,
5233                 _AM_COND_IF => 1,
5234                 _AM_COND_ELSE => 1,
5235                 _AM_COND_ENDIF => 1,
5236                 LT_SUPPORTED_TAG => 1,
5237                 _LT_AC_TAGCONFIG => 0,
5238                 m4_include => 1,
5239                 m4_sinclude => 1,
5240                 sinclude => 1,
5241               );
5243   my $traces = ($ENV{AUTOCONF} || 'autoconf') . " ";
5245   # Use a separator unlikely to be used, not `:', the default, which
5246   # has a precise meaning for AC_CONFIG_FILES and so on.
5247   $traces .= join (' ',
5248                    map { "--trace=$_" . ':\$f:\$l::\$d::\$n::\${::}%' }
5249                    (keys %traced));
5251   my $tracefh = new Automake::XFile ("$traces $filename |");
5252   verb "reading $traces";
5254   @cond_stack = ();
5255   my $where;
5257   while ($_ = $tracefh->getline)
5258     {
5259       chomp;
5260       my ($here, $depth, @args) = split (/::/);
5261       $where = new Automake::Location $here;
5262       my $macro = $args[0];
5264       prog_error ("unrequested trace `$macro'")
5265         unless exists $traced{$macro};
5267       # Skip and diagnose malformed calls.
5268       if ($#args < $traced{$macro})
5269         {
5270           msg ('syntax', $where, "not enough arguments for $macro");
5271           next;
5272         }
5274       # Alphabetical ordering please.
5275       if ($macro eq 'AC_CANONICAL_BUILD')
5276         {
5277           if ($seen_canonical <= AC_CANONICAL_BUILD)
5278             {
5279               $seen_canonical = AC_CANONICAL_BUILD;
5280               $canonical_location = $where;
5281             }
5282         }
5283       elsif ($macro eq 'AC_CANONICAL_HOST')
5284         {
5285           if ($seen_canonical <= AC_CANONICAL_HOST)
5286             {
5287               $seen_canonical = AC_CANONICAL_HOST;
5288               $canonical_location = $where;
5289             }
5290         }
5291       elsif ($macro eq 'AC_CANONICAL_TARGET')
5292         {
5293           $seen_canonical = AC_CANONICAL_TARGET;
5294           $canonical_location = $where;
5295         }
5296       elsif ($macro eq 'AC_CONFIG_AUX_DIR')
5297         {
5298           if ($seen_init_automake)
5299             {
5300               error ($where, "AC_CONFIG_AUX_DIR must be called before "
5301                      . "AM_INIT_AUTOMAKE...", partial => 1);
5302               error ($seen_init_automake, "... AM_INIT_AUTOMAKE called here");
5303             }
5304           $config_aux_dir = $args[1];
5305           $config_aux_dir_set_in_configure_ac = 1;
5306           $relative_dir = '.';
5307           check_directory ($config_aux_dir, $where);
5308         }
5309       elsif ($macro eq 'AC_CONFIG_FILES')
5310         {
5311           # Look at potential Makefile.am's.
5312           scan_autoconf_config_files ($where, $args[1]);
5313         }
5314       elsif ($macro eq 'AC_CONFIG_HEADERS')
5315         {
5316           foreach my $spec (split (' ', $args[1]))
5317             {
5318               my ($dest, @src) = split (':', $spec);
5319               $ac_config_files_location{$dest} = $where;
5320               push @config_headers, $spec;
5321             }
5322         }
5323       elsif ($macro eq 'AC_CONFIG_LIBOBJ_DIR')
5324         {
5325           $config_libobj_dir = $args[1];
5326           $relative_dir = '.';
5327           check_directory ($config_libobj_dir, $where);
5328         }
5329       elsif ($macro eq 'AC_CONFIG_LINKS')
5330         {
5331           foreach my $spec (split (' ', $args[1]))
5332             {
5333               my ($dest, $src) = split (':', $spec);
5334               $ac_config_files_location{$dest} = $where;
5335               push @config_links, $spec;
5336             }
5337         }
5338       elsif ($macro eq 'AC_FC_SRCEXT')
5339         {
5340           my $suffix = $args[1];
5341           # These flags are used as %SOURCEFLAG% in depend2.am,
5342           # where the trailing space is important.
5343           $sourceflags{'.' . $suffix} = '$(FCFLAGS_' . $suffix . ') '
5344             if ($suffix eq 'f90' || $suffix eq 'f95' || $suffix eq 'f03' || $suffix eq 'f08');
5345         }
5346       elsif ($macro eq 'AC_INIT')
5347         {
5348           if (defined $args[2])
5349             {
5350               $package_version = $args[2];
5351               $package_version_location = $where;
5352             }
5353         }
5354       elsif ($macro eq 'AC_LIBSOURCE')
5355         {
5356           $libsources{$args[1]} = $here;
5357         }
5358       elsif ($macro eq 'AC_REQUIRE_AUX_FILE')
5359         {
5360           # Only remember the first time a file is required.
5361           $required_aux_file{$args[1]} = $where
5362             unless exists $required_aux_file{$args[1]};
5363         }
5364       elsif ($macro eq 'AC_SUBST_TRACE')
5365         {
5366           # Just check for alphanumeric in AC_SUBST_TRACE.  If you do
5367           # AC_SUBST(5), then too bad.
5368           $configure_vars{$args[1]} = $where
5369             if $args[1] =~ /^\w+$/;
5370         }
5371       elsif ($macro eq 'AM_AUTOMAKE_VERSION')
5372         {
5373           error ($where,
5374                  "version mismatch.  This is Automake $VERSION,\n" .
5375                  "but the definition used by this AM_INIT_AUTOMAKE\n" .
5376                  "comes from Automake $args[1].  You should recreate\n" .
5377                  "aclocal.m4 with aclocal and run automake again.\n",
5378                  # $? = 63 is used to indicate version mismatch to missing.
5379                  exit_code => 63)
5380             if $VERSION ne $args[1];
5382           $seen_automake_version = 1;
5383         }
5384       elsif ($macro eq 'AM_CONDITIONAL')
5385         {
5386           $configure_cond{$args[1]} = $where;
5387         }
5388       elsif ($macro eq 'AM_ENABLE_MULTILIB')
5389         {
5390           $seen_multilib = $where;
5391         }
5392       elsif ($macro eq 'AM_GNU_GETTEXT')
5393         {
5394           $seen_gettext = $where;
5395           $ac_gettext_location = $where;
5396           $seen_gettext_external = grep ($_ eq 'external', @args);
5397         }
5398       elsif ($macro eq 'AM_GNU_GETTEXT_INTL_SUBDIR')
5399         {
5400           $seen_gettext_intl = $where;
5401         }
5402       elsif ($macro eq 'AM_INIT_AUTOMAKE')
5403         {
5404           $seen_init_automake = $where;
5405           if (defined $args[2])
5406             {
5407               $package_version = $args[2];
5408               $package_version_location = $where;
5409             }
5410           elsif (defined $args[1])
5411             {
5412               exit $exit_code
5413                 if (process_global_option_list ($where,
5414                                                 split (' ', $args[1])));
5415             }
5416         }
5417       elsif ($macro eq 'AM_MAINTAINER_MODE')
5418         {
5419           $seen_maint_mode = $where;
5420         }
5421       elsif ($macro eq 'AM_PROG_CC_C_O')
5422         {
5423           $seen_cc_c_o = $where;
5424         }
5425       elsif ($macro eq 'AM_SILENT_RULES')
5426         {
5427           set_global_option ('silent-rules', $where);
5428         }
5429       elsif ($macro eq '_AM_COND_IF')
5430         {
5431           cond_stack_if ('', $args[1], $where);
5432           error ($where, "missing m4 quoting, macro depth $depth")
5433             if ($depth != 1);
5434         }
5435       elsif ($macro eq '_AM_COND_ELSE')
5436         {
5437           cond_stack_else ('!', $args[1], $where);
5438           error ($where, "missing m4 quoting, macro depth $depth")
5439             if ($depth != 1);
5440         }
5441       elsif ($macro eq '_AM_COND_ENDIF')
5442         {
5443           cond_stack_endif (undef, undef, $where);
5444           error ($where, "missing m4 quoting, macro depth $depth")
5445             if ($depth != 1);
5446         }
5447       elsif ($macro eq '_AM_SUBST_NOTMAKE')
5448         {
5449           $ignored_configure_vars{$args[1]} = $where;
5450         }
5451       elsif ($macro eq 'm4_include'
5452              || $macro eq 'm4_sinclude'
5453              || $macro eq 'sinclude')
5454         {
5455           # Skip missing `sinclude'd files.
5456           next if $macro ne 'm4_include' && ! -f $args[1];
5458           # Some modified versions of Autoconf don't use
5459           # frozen files.  Consequently it's possible that we see all
5460           # m4_include's performed during Autoconf's startup.
5461           # Obviously we don't want to distribute Autoconf's files
5462           # so we skip absolute filenames here.
5463           push @configure_deps, '$(top_srcdir)/' . $args[1]
5464             unless $here =~ m,^(?:\w:)?[\\/],;
5465           # Keep track of the greatest timestamp.
5466           if (-e $args[1])
5467             {
5468               my $mtime = mtime $args[1];
5469               $configure_deps_greatest_timestamp = $mtime
5470                 if $mtime > $configure_deps_greatest_timestamp;
5471             }
5472         }
5473       elsif ($macro eq 'LT_SUPPORTED_TAG')
5474         {
5475           $libtool_tags{$args[1]} = 1;
5476           $libtool_new_api = 1;
5477         }
5478       elsif ($macro eq '_LT_AC_TAGCONFIG')
5479         {
5480           # _LT_AC_TAGCONFIG is an old macro present in Libtool 1.5.
5481           # We use it to detect whether tags are supported.  Our
5482           # preferred interface is LT_SUPPORTED_TAG, but it was
5483           # introduced in Libtool 1.6.
5484           if (0 == keys %libtool_tags)
5485             {
5486               # Hardcode the tags supported by Libtool 1.5.
5487               %libtool_tags = (CC => 1, CXX => 1, GCJ => 1, F77 => 1);
5488             }
5489         }
5490     }
5492   error ($where, "condition stack not properly closed")
5493     if (@cond_stack);
5495   $tracefh->close;
5499 # &scan_autoconf_files ()
5500 # -----------------------
5501 # Check whether we use `configure.ac' or `configure.in'.
5502 # Scan it (and possibly `aclocal.m4') for interesting things.
5503 # We must scan aclocal.m4 because there might be AC_SUBSTs and such there.
5504 sub scan_autoconf_files ()
5506   # Reinitialize libsources here.  This isn't really necessary,
5507   # since we currently assume there is only one configure.ac.  But
5508   # that won't always be the case.
5509   %libsources = ();
5511   # Keep track of the youngest configure dependency.
5512   $configure_deps_greatest_timestamp = mtime $configure_ac;
5513   if (-e 'aclocal.m4')
5514     {
5515       my $mtime = mtime 'aclocal.m4';
5516       $configure_deps_greatest_timestamp = $mtime
5517         if $mtime > $configure_deps_greatest_timestamp;
5518     }
5520   scan_autoconf_traces ($configure_ac);
5522   @configure_input_files = sort keys %make_list;
5523   # Set input and output files if not specified by user.
5524   if (! @input_files)
5525     {
5526       @input_files = @configure_input_files;
5527       %output_files = %make_list;
5528     }
5531   if (! $seen_init_automake)
5532     {
5533       err_ac ("no proper invocation of AM_INIT_AUTOMAKE was found.\nYou "
5534               . "should verify that $configure_ac invokes AM_INIT_AUTOMAKE,"
5535               . "\nthat aclocal.m4 is present in the top-level directory,\n"
5536               . "and that aclocal.m4 was recently regenerated "
5537               . "(using aclocal).");
5538     }
5539   else
5540     {
5541       if (! $seen_automake_version)
5542         {
5543           if (-f 'aclocal.m4')
5544             {
5545               error ($seen_init_automake,
5546                      "your implementation of AM_INIT_AUTOMAKE comes from " .
5547                      "an\nold Automake version.  You should recreate " .
5548                      "aclocal.m4\nwith aclocal and run automake again.\n",
5549                      # $? = 63 is used to indicate version mismatch to missing.
5550                      exit_code => 63);
5551             }
5552           else
5553             {
5554               error ($seen_init_automake,
5555                      "no proper implementation of AM_INIT_AUTOMAKE was " .
5556                      "found,\nprobably because aclocal.m4 is missing...\n" .
5557                      "You should run aclocal to create this file, then\n" .
5558                      "run automake again.\n");
5559             }
5560         }
5561     }
5563   locate_aux_dir ();
5565   # Reorder @input_files so that the Makefile that distributes aux
5566   # files is processed last.  This is important because each directory
5567   # can require auxiliary scripts and we should wait until they have
5568   # been installed before distributing them.
5570   # The Makefile.in that distribute the aux files is the one in
5571   # $config_aux_dir or the top-level Makefile.
5572   my $auxdirdist = is_make_dir ($config_aux_dir) ? $config_aux_dir : '.';
5573   my @new_input_files = ();
5574   while (@input_files)
5575     {
5576       my $in = pop @input_files;
5577       my @ins = split (/:/, $output_files{$in});
5578       if (dirname ($ins[0]) eq $auxdirdist)
5579         {
5580           push @new_input_files, $in;
5581           $automake_will_process_aux_dir = 1;
5582         }
5583       else
5584         {
5585           unshift @new_input_files, $in;
5586         }
5587     }
5588   @input_files = @new_input_files;
5590   # If neither the auxdir/Makefile nor the ./Makefile are generated
5591   # by Automake, we won't distribute the aux files anyway.  Assume
5592   # the user know what (s)he does, and pretend we will distribute
5593   # them to disable the error in require_file_internal.
5594   $automake_will_process_aux_dir = 1 if ! is_make_dir ($auxdirdist);
5596   # Look for some files we need.  Always check for these.  This
5597   # check must be done for every run, even those where we are only
5598   # looking at a subdir Makefile.  We must set relative_dir for
5599   # maybe_push_required_file to work.
5600   # Sort the files for stable verbose output.
5601   $relative_dir = '.';
5602   foreach my $file (sort keys %required_aux_file)
5603     {
5604       require_conf_file ($required_aux_file{$file}->get, FOREIGN, $file)
5605     }
5606   err_am "`install.sh' is an anachronism; use `install-sh' instead"
5607     if -f $config_aux_dir . '/install.sh';
5609   # Preserve dist_common for later.
5610   $configure_dist_common = variable_value ('DIST_COMMON') || '';
5614 ################################################################
5616 # Set up for Cygnus mode.
5617 sub check_cygnus
5619   my $cygnus = option 'cygnus';
5620   return unless $cygnus;
5622   set_strictness ('foreign');
5623   set_option ('no-installinfo', $cygnus);
5624   set_option ('no-dependencies', $cygnus);
5625   set_option ('no-dist', $cygnus);
5627   err_ac "`AM_MAINTAINER_MODE' required when --cygnus specified"
5628     if !$seen_maint_mode;
5631 # Do any extra checking for GNU standards.
5632 sub check_gnu_standards
5634   if ($relative_dir eq '.')
5635     {
5636       # In top level (or only) directory.
5637       require_file ("$am_file.am", GNU,
5638                     qw/INSTALL NEWS README AUTHORS ChangeLog/);
5640       # Accept one of these three licenses; default to COPYING.
5641       # Make sure we do not overwrite an existing license.
5642       my $license;
5643       foreach (qw /COPYING COPYING.LIB COPYING.LESSER/)
5644         {
5645           if (-f $_)
5646             {
5647               $license = $_;
5648               last;
5649             }
5650         }
5651       require_file ("$am_file.am", GNU, 'COPYING')
5652         unless $license;
5653     }
5655   for my $opt ('no-installman', 'no-installinfo')
5656     {
5657       msg ('error-gnu', option $opt,
5658            "option `$opt' disallowed by GNU standards")
5659         if option $opt;
5660     }
5663 # Do any extra checking for GNITS standards.
5664 sub check_gnits_standards
5666   if ($relative_dir eq '.')
5667     {
5668       # In top level (or only) directory.
5669       require_file ("$am_file.am", GNITS, 'THANKS');
5670     }
5673 ################################################################
5675 # Functions to handle files of each language.
5677 # Each `lang_X_rewrite($DIRECTORY, $BASE, $EXT)' function follows a
5678 # simple formula: Return value is LANG_SUBDIR if the resulting object
5679 # file should be in a subdir if the source file is, LANG_PROCESS if
5680 # file is to be dealt with, LANG_IGNORE otherwise.
5682 # Much of the actual processing is handled in
5683 # handle_single_transform.  These functions exist so that
5684 # auxiliary information can be recorded for a later cleanup pass.
5685 # Note that the calls to these functions are computed, so don't bother
5686 # searching for their precise names in the source.
5688 # This is just a convenience function that can be used to determine
5689 # when a subdir object should be used.
5690 sub lang_sub_obj
5692     return option 'subdir-objects' ? LANG_SUBDIR : LANG_PROCESS;
5695 # Rewrite a single C source file.
5696 sub lang_c_rewrite
5698   my ($directory, $base, $ext, $nonansi_obj, $have_per_exec_flags, $var) = @_;
5700   if (option 'ansi2knr' && $base =~ /_$/)
5701     {
5702       # FIXME: include line number in error.
5703       err_am "C source file `$base.c' would be deleted by ansi2knr rules";
5704     }
5706   my $r = LANG_PROCESS;
5707   if (option 'subdir-objects')
5708     {
5709       $r = LANG_SUBDIR;
5710       if ($directory && $directory ne '.')
5711         {
5712           $base = $directory . '/' . $base;
5714           # libtool is always able to put the object at the proper place,
5715           # so we do not have to require AM_PROG_CC_C_O when building .lo files.
5716           msg_var ('portability', $var,
5717                    "compiling `$base.c' in subdir requires "
5718                    . "`AM_PROG_CC_C_O' in `$configure_ac'",
5719                    uniq_scope => US_GLOBAL,
5720                    uniq_part => 'AM_PROG_CC_C_O subdir')
5721             unless $seen_cc_c_o || $nonansi_obj eq '.lo';
5722         }
5724       # In this case we already have the directory information, so
5725       # don't add it again.
5726       $de_ansi_files{$base} = '';
5727     }
5728   else
5729     {
5730       $de_ansi_files{$base} = (($directory eq '.' || $directory eq '')
5731                                ? ''
5732                                : "$directory/");
5733     }
5735   if (! $seen_cc_c_o
5736       && $have_per_exec_flags
5737       && ! option 'subdir-objects'
5738       && $nonansi_obj ne '.lo')
5739     {
5740       msg_var ('portability',
5741                $var, "compiling `$base.c' with per-target flags requires "
5742                . "`AM_PROG_CC_C_O' in `$configure_ac'",
5743                uniq_scope => US_GLOBAL,
5744                uniq_part => 'AM_PROG_CC_C_O per-target')
5745     }
5747     return $r;
5750 # Rewrite a single C++ source file.
5751 sub lang_cxx_rewrite
5753     return &lang_sub_obj;
5756 # Rewrite a single header file.
5757 sub lang_header_rewrite
5759     # Header files are simply ignored.
5760     return LANG_IGNORE;
5763 # Rewrite a single Vala source file.
5764 sub lang_vala_rewrite
5766     my ($directory, $base, $ext) = @_;
5768     (my $newext = $ext) =~ s/vala$/c/;
5769     return (LANG_SUBDIR, $newext);
5772 # Rewrite a single yacc file.
5773 sub lang_yacc_rewrite
5775     my ($directory, $base, $ext) = @_;
5777     my $r = &lang_sub_obj;
5778     (my $newext = $ext) =~ tr/y/c/;
5779     return ($r, $newext);
5782 # Rewrite a single yacc++ file.
5783 sub lang_yaccxx_rewrite
5785     my ($directory, $base, $ext) = @_;
5787     my $r = &lang_sub_obj;
5788     (my $newext = $ext) =~ tr/y/c/;
5789     return ($r, $newext);
5792 # Rewrite a single lex file.
5793 sub lang_lex_rewrite
5795     my ($directory, $base, $ext) = @_;
5797     my $r = &lang_sub_obj;
5798     (my $newext = $ext) =~ tr/l/c/;
5799     return ($r, $newext);
5802 # Rewrite a single lex++ file.
5803 sub lang_lexxx_rewrite
5805     my ($directory, $base, $ext) = @_;
5807     my $r = &lang_sub_obj;
5808     (my $newext = $ext) =~ tr/l/c/;
5809     return ($r, $newext);
5812 # Rewrite a single assembly file.
5813 sub lang_asm_rewrite
5815     return &lang_sub_obj;
5818 # Rewrite a single preprocessed assembly file.
5819 sub lang_cppasm_rewrite
5821     return &lang_sub_obj;
5824 # Rewrite a single Fortran 77 file.
5825 sub lang_f77_rewrite
5827     return &lang_sub_obj;
5830 # Rewrite a single Fortran file.
5831 sub lang_fc_rewrite
5833     return &lang_sub_obj;
5836 # Rewrite a single preprocessed Fortran file.
5837 sub lang_ppfc_rewrite
5839     return &lang_sub_obj;
5842 # Rewrite a single preprocessed Fortran 77 file.
5843 sub lang_ppf77_rewrite
5845     return &lang_sub_obj;
5848 # Rewrite a single ratfor file.
5849 sub lang_ratfor_rewrite
5851     return &lang_sub_obj;
5854 # Rewrite a single Objective C file.
5855 sub lang_objc_rewrite
5857     return &lang_sub_obj;
5860 # Rewrite a single Unified Parallel C file.
5861 sub lang_upc_rewrite
5863     return &lang_sub_obj;
5866 # Rewrite a single Java file.
5867 sub lang_java_rewrite
5869     return LANG_SUBDIR;
5872 # The lang_X_finish functions are called after all source file
5873 # processing is done.  Each should handle defining rules for the
5874 # language, etc.  A finish function is only called if a source file of
5875 # the appropriate type has been seen.
5877 sub lang_c_finish
5879     # Push all libobjs files onto de_ansi_files.  We actually only
5880     # push files which exist in the current directory, and which are
5881     # genuine source files.
5882     foreach my $file (keys %libsources)
5883     {
5884         if ($file =~ /^(.*)\.[cly]$/ && -f "$relative_dir/$file")
5885         {
5886             $de_ansi_files{$1} = ''
5887         }
5888     }
5890     if (option 'ansi2knr' && keys %de_ansi_files)
5891     {
5892         # Make all _.c files depend on their corresponding .c files.
5893         my @objects;
5894         foreach my $base (sort keys %de_ansi_files)
5895         {
5896             # Each _.c file must depend on ansi2knr; otherwise it
5897             # might be used in a parallel build before it is built.
5898             # We need to support files in the srcdir and in the build
5899             # dir (because these files might be auto-generated.  But
5900             # we can't use $< -- some makes only define $< during a
5901             # suffix rule.
5902             my $ansfile = $de_ansi_files{$base} . $base . '.c';
5903             $output_rules .= ($base . "_.c: $ansfile \$(ANSI2KNR)\n\t"
5904                               . '$(CPP) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) '
5905                               . '`if test -f $(srcdir)/' . $ansfile
5906                               . '; then echo $(srcdir)/' . $ansfile
5907                               . '; else echo ' . $ansfile . '; fi` '
5908                               . "| sed 's/^# \\([0-9]\\)/#line \\1/' "
5909                               . '| $(ANSI2KNR) > $@'
5910                               # If ansi2knr fails then we shouldn't
5911                               # create the _.c file
5912                               . " || rm -f \$\@\n");
5913             push (@objects, $base . '_.$(OBJEXT)');
5914             push (@objects, $base . '_.lo')
5915               if var ('LIBTOOL');
5917             # Explicitly clean the _.c files if they are in a
5918             # subdirectory. (In the current directory they get erased
5919             # by a `rm -f *_.c' rule.)
5920             $clean_files{$base . '_.c'} = MOSTLY_CLEAN
5921               if dirname ($base) ne '.';
5922         }
5924         # Make all _.o (and _.lo) files depend on ansi2knr.
5925         # Use a sneaky little hack to make it print nicely.
5926         &pretty_print_rule ('', '', @objects, ':', '$(ANSI2KNR)');
5927     }
5930 sub lang_vala_finish_target ($$)
5932   my ($self, $name) = @_;
5934   my $derived = canonicalize ($name);
5935   my $varname = $derived . '_SOURCES';
5936   my $var = var ($varname);
5938   if ($var)
5939     {
5940       foreach my $file ($var->value_as_list_recursive)
5941         {
5942           $output_rules .= "$file: ${derived}_vala.stamp\n".
5943             "\t\@if test -f \$@; then :; else \\\n".
5944             "\t  rm -f ${derived}_vala.stamp; \\\n".
5945             "\t  \$(MAKE) \$(AM_MAKEFLAGS) ${derived}_vala.stamp; \\\n".
5946             "\tfi\n"
5947             if $file =~ s/(.*)\.vala$/$1.c/;
5948         }
5949     }
5951   my $compile = $self->compile;
5953   # Rewrite each occurrence of `AM_$flag' in the compile
5954   # rule into `${derived}_$flag' if it exists.
5955   for my $flag (@{$self->flags})
5956     {
5957       my $val = "${derived}_$flag";
5958       $compile =~ s/\(AM_$flag\)/\($val\)/
5959         if set_seen ($val);
5960     }
5962   my $dirname = dirname ($name);
5964   # Only generate C code, do not run C compiler
5965   $compile .= " -C";
5967   my $verbose = verbose_flag ('VALAC');
5968   my $silent = silent_flag ();
5970   $output_rules .=
5971     "${derived}_vala.stamp: \$(${derived}_SOURCES)\n".
5972     "\t${verbose}${compile} \$(${derived}_SOURCES)\n".
5973     "\t${silent}touch \$@\n";
5975   push_dist_common ("${derived}_vala.stamp");
5977   $clean_files{"${derived}_vala.stamp"} = MAINTAINER_CLEAN;
5980 # Add output rules to invoke valac and create stamp file as a witness
5981 # to handle multiple outputs. This function is called after all source
5982 # file processing is done.
5983 sub lang_vala_finish
5985   my ($self) = @_;
5987   foreach my $prog (keys %known_programs)
5988     {
5989       lang_vala_finish_target ($self, $prog);
5990     }
5992   while (my ($name) = each %known_libraries)
5993     {
5994       lang_vala_finish_target ($self, $name);
5995     }
5998 # The built .c files should be cleaned only on maintainer-clean
5999 # as the .c files are distributed. This function is called for each
6000 # .vala source file.
6001 sub lang_vala_target_hook
6003   my ($self, $aggregate, $output, $input, %transform) = @_;
6005   $clean_files{$output} = MAINTAINER_CLEAN;
6008 # This is a yacc helper which is called whenever we have decided to
6009 # compile a yacc file.
6010 sub lang_yacc_target_hook
6012     my ($self, $aggregate, $output, $input, %transform) = @_;
6014     my $flag = $aggregate . "_YFLAGS";
6015     my $flagvar = var $flag;
6016     my $YFLAGSvar = var 'YFLAGS';
6017     if (($flagvar && $flagvar->variable_value =~ /$DASH_D_PATTERN/o)
6018         || ($YFLAGSvar && $YFLAGSvar->variable_value =~ /$DASH_D_PATTERN/o))
6019     {
6020         (my $output_base = $output) =~ s/$KNOWN_EXTENSIONS_PATTERN$//;
6021         my $header = $output_base . '.h';
6023         # Found a `-d' that applies to the compilation of this file.
6024         # Add a dependency for the generated header file, and arrange
6025         # for that file to be included in the distribution.
6026         foreach my $cond (Automake::Rule::define (${header}, 'internal',
6027                                                   RULE_AUTOMAKE, TRUE,
6028                                                   INTERNAL))
6029           {
6030             my $condstr = $cond->subst_string;
6031             $output_rules .=
6032               "$condstr${header}: $output\n"
6033               # Recover from removal of $header
6034               . "$condstr\t\@if test ! -f \$@; then \\\n"
6035               . "$condstr\t  rm -f $output; \\\n"
6036               . "$condstr\t  \$(MAKE) \$(AM_MAKEFLAGS) $output; \\\n"
6037               . "$condstr\telse :; fi\n";
6038           }
6039         # Distribute the generated file, unless its .y source was
6040         # listed in a nodist_ variable.  (&handle_source_transform
6041         # will set DIST_SOURCE.)
6042         &push_dist_common ($header)
6043           if $transform{'DIST_SOURCE'};
6045         # If the files are built in the build directory, then we want
6046         # to remove them with `make clean'.  If they are in srcdir
6047         # they shouldn't be touched.  However, we can't determine this
6048         # statically, and the GNU rules say that yacc/lex output files
6049         # should be removed by maintainer-clean.  So that's what we
6050         # do.
6051         $clean_files{$header} = MAINTAINER_CLEAN;
6052     }
6053     # Erase $OUTPUT on `make maintainer-clean' (by GNU standards).
6054     # See the comment above for $HEADER.
6055     $clean_files{$output} = MAINTAINER_CLEAN;
6058 # This is a lex helper which is called whenever we have decided to
6059 # compile a lex file.
6060 sub lang_lex_target_hook
6062     my ($self, $aggregate, $output, $input) = @_;
6063     # If the files are built in the build directory, then we want to
6064     # remove them with `make clean'.  If they are in srcdir they
6065     # shouldn't be touched.  However, we can't determine this
6066     # statically, and the GNU rules say that yacc/lex output files
6067     # should be removed by maintainer-clean.  So that's what we do.
6068     $clean_files{$output} = MAINTAINER_CLEAN;
6071 # This is a helper for both lex and yacc.
6072 sub yacc_lex_finish_helper
6074   return if defined $language_scratch{'lex-yacc-done'};
6075   $language_scratch{'lex-yacc-done'} = 1;
6077   # FIXME: for now, no line number.
6078   require_conf_file ($configure_ac, FOREIGN, 'ylwrap');
6079   &define_variable ('YLWRAP', "$am_config_aux_dir/ylwrap", INTERNAL);
6082 sub lang_yacc_finish
6084   return if defined $language_scratch{'yacc-done'};
6085   $language_scratch{'yacc-done'} = 1;
6087   reject_var 'YACCFLAGS', "`YACCFLAGS' obsolete; use `YFLAGS' instead";
6089   yacc_lex_finish_helper;
6093 sub lang_lex_finish
6095   return if defined $language_scratch{'lex-done'};
6096   $language_scratch{'lex-done'} = 1;
6098   yacc_lex_finish_helper;
6102 # Given a hash table of linker names, pick the name that has the most
6103 # precedence.  This is lame, but something has to have global
6104 # knowledge in order to eliminate the conflict.  Add more linkers as
6105 # required.
6106 sub resolve_linker
6108     my (%linkers) = @_;
6110     foreach my $l (qw(GCJLINK CXXLINK F77LINK FCLINK OBJCLINK UPCLINK))
6111     {
6112         return $l if defined $linkers{$l};
6113     }
6114     return 'LINK';
6117 # Called to indicate that an extension was used.
6118 sub saw_extension
6120     my ($ext) = @_;
6121     if (! defined $extension_seen{$ext})
6122     {
6123         $extension_seen{$ext} = 1;
6124     }
6125     else
6126     {
6127         ++$extension_seen{$ext};
6128     }
6131 # Return the number of files seen for a given language.  Knows about
6132 # special cases we care about.  FIXME: this is hideous.  We need
6133 # something that involves real language objects.  For instance yacc
6134 # and yaccxx could both derive from a common yacc class which would
6135 # know about the strange ylwrap requirement.  (Or better yet we could
6136 # just not support legacy yacc!)
6137 sub count_files_for_language
6139     my ($name) = @_;
6141     my @names;
6142     if ($name eq 'yacc' || $name eq 'yaccxx')
6143     {
6144         @names = ('yacc', 'yaccxx');
6145     }
6146     elsif ($name eq 'lex' || $name eq 'lexxx')
6147     {
6148         @names = ('lex', 'lexxx');
6149     }
6150     else
6151     {
6152         @names = ($name);
6153     }
6155     my $r = 0;
6156     foreach $name (@names)
6157     {
6158         my $lang = $languages{$name};
6159         foreach my $ext (@{$lang->extensions})
6160         {
6161             $r += $extension_seen{$ext}
6162                 if defined $extension_seen{$ext};
6163         }
6164     }
6166     return $r
6169 # Called to ask whether source files have been seen . If HEADERS is 1,
6170 # headers can be included.
6171 sub saw_sources_p
6173     my ($headers) = @_;
6175     # count all the sources
6176     my $count = 0;
6177     foreach my $val (values %extension_seen)
6178     {
6179         $count += $val;
6180     }
6182     if (!$headers)
6183     {
6184         $count -= count_files_for_language ('header');
6185     }
6187     return $count > 0;
6191 # register_language (%ATTRIBUTE)
6192 # ------------------------------
6193 # Register a single language.
6194 # Each %ATTRIBUTE is of the form ATTRIBUTE => VALUE.
6195 sub register_language (%)
6197   my (%option) = @_;
6199   # Set the defaults.
6200   $option{'ansi'} = 0
6201     unless defined $option{'ansi'};
6202   $option{'autodep'} = 'no'
6203     unless defined $option{'autodep'};
6204   $option{'linker'} = ''
6205     unless defined $option{'linker'};
6206   $option{'flags'} = []
6207     unless defined $option{'flags'};
6208   $option{'output_extensions'} = sub { return ( '.$(OBJEXT)', '.lo' ) }
6209     unless defined $option{'output_extensions'};
6210   $option{'nodist_specific'} = 0
6211     unless defined $option{'nodist_specific'};
6213   my $lang = new Language (%option);
6215   # Fill indexes.
6216   $extension_map{$_} = $lang->name foreach @{$lang->extensions};
6217   $languages{$lang->name} = $lang;
6218   my $link = $lang->linker;
6219   if ($link)
6220     {
6221       if (exists $link_languages{$link})
6222         {
6223           prog_error ("`$link' has different definitions in "
6224                       . $lang->name . " and " . $link_languages{$link}->name)
6225             if $lang->link ne $link_languages{$link}->link;
6226         }
6227       else
6228         {
6229           $link_languages{$link} = $lang;
6230         }
6231     }
6233   # Update the pattern of known extensions.
6234   accept_extensions (@{$lang->extensions});
6236   # Upate the $suffix_rule map.
6237   foreach my $suffix (@{$lang->extensions})
6238     {
6239       foreach my $dest (&{$lang->output_extensions} ($suffix))
6240         {
6241           register_suffix_rule (INTERNAL, $suffix, $dest);
6242         }
6243     }
6246 # derive_suffix ($EXT, $OBJ)
6247 # --------------------------
6248 # This function is used to find a path from a user-specified suffix $EXT
6249 # to $OBJ or to some other suffix we recognize internally, e.g. `cc'.
6250 sub derive_suffix ($$)
6252   my ($source_ext, $obj) = @_;
6254   while (! $extension_map{$source_ext}
6255          && $source_ext ne $obj
6256          && exists $suffix_rules->{$source_ext}
6257          && exists $suffix_rules->{$source_ext}{$obj})
6258     {
6259       $source_ext = $suffix_rules->{$source_ext}{$obj}[0];
6260     }
6262   return $source_ext;
6266 ################################################################
6268 # Pretty-print something and append to output_rules.
6269 sub pretty_print_rule
6271     $output_rules .= &makefile_wrap (@_);
6275 ################################################################
6278 ## -------------------------------- ##
6279 ## Handling the conditional stack.  ##
6280 ## -------------------------------- ##
6283 # $STRING
6284 # make_conditional_string ($NEGATE, $COND)
6285 # ----------------------------------------
6286 sub make_conditional_string ($$)
6288   my ($negate, $cond) = @_;
6289   $cond = "${cond}_TRUE"
6290     unless $cond =~ /^TRUE|FALSE$/;
6291   $cond = Automake::Condition::conditional_negate ($cond)
6292     if $negate;
6293   return $cond;
6297 my %_am_macro_for_cond =
6298   (
6299   AMDEP => "one of the compiler tests\n"
6300            . "    AC_PROG_CC, AC_PROG_CXX, AC_PROG_CXX, AC_PROG_OBJC,\n"
6301            . "    AM_PROG_AS, AM_PROG_GCJ, AM_PROG_UPC",
6302   am__fastdepCC => 'AC_PROG_CC',
6303   am__fastdepCCAS => 'AM_PROG_AS',
6304   am__fastdepCXX => 'AC_PROG_CXX',
6305   am__fastdepGCJ => 'AM_PROG_GCJ',
6306   am__fastdepOBJC => 'AC_PROG_OBJC',
6307   am__fastdepUPC => 'AM_PROG_UPC'
6308   );
6310 # $COND
6311 # cond_stack_if ($NEGATE, $COND, $WHERE)
6312 # --------------------------------------
6313 sub cond_stack_if ($$$)
6315   my ($negate, $cond, $where) = @_;
6317   if (! $configure_cond{$cond} && $cond !~ /^TRUE|FALSE$/)
6318     {
6319       my $text = "$cond does not appear in AM_CONDITIONAL";
6320       my $scope = US_LOCAL;
6321       if (exists $_am_macro_for_cond{$cond})
6322         {
6323           my $mac = $_am_macro_for_cond{$cond};
6324           $text .= "\n  The usual way to define `$cond' is to add ";
6325           $text .= ($mac =~ / /) ? $mac : "`$mac'";
6326           $text .= "\n  to `$configure_ac' and run `aclocal' and `autoconf' again.";
6327           # These warnings appear in Automake files (depend2.am),
6328           # so there is no need to display them more than once:
6329           $scope = US_GLOBAL;
6330         }
6331       error $where, $text, uniq_scope => $scope;
6332     }
6334   push (@cond_stack, make_conditional_string ($negate, $cond));
6336   return new Automake::Condition (@cond_stack);
6340 # $COND
6341 # cond_stack_else ($NEGATE, $COND, $WHERE)
6342 # ----------------------------------------
6343 sub cond_stack_else ($$$)
6345   my ($negate, $cond, $where) = @_;
6347   if (! @cond_stack)
6348     {
6349       error $where, "else without if";
6350       return FALSE;
6351     }
6353   $cond_stack[$#cond_stack] =
6354     Automake::Condition::conditional_negate ($cond_stack[$#cond_stack]);
6356   # If $COND is given, check against it.
6357   if (defined $cond)
6358     {
6359       $cond = make_conditional_string ($negate, $cond);
6361       error ($where, "else reminder ($negate$cond) incompatible with "
6362              . "current conditional: $cond_stack[$#cond_stack]")
6363         if $cond_stack[$#cond_stack] ne $cond;
6364     }
6366   return new Automake::Condition (@cond_stack);
6370 # $COND
6371 # cond_stack_endif ($NEGATE, $COND, $WHERE)
6372 # -----------------------------------------
6373 sub cond_stack_endif ($$$)
6375   my ($negate, $cond, $where) = @_;
6376   my $old_cond;
6378   if (! @cond_stack)
6379     {
6380       error $where, "endif without if";
6381       return TRUE;
6382     }
6384   # If $COND is given, check against it.
6385   if (defined $cond)
6386     {
6387       $cond = make_conditional_string ($negate, $cond);
6389       error ($where, "endif reminder ($negate$cond) incompatible with "
6390              . "current conditional: $cond_stack[$#cond_stack]")
6391         if $cond_stack[$#cond_stack] ne $cond;
6392     }
6394   pop @cond_stack;
6396   return new Automake::Condition (@cond_stack);
6403 ## ------------------------ ##
6404 ## Handling the variables.  ##
6405 ## ------------------------ ##
6408 # &define_pretty_variable ($VAR, $COND, $WHERE, @VALUE)
6409 # -----------------------------------------------------
6410 # Like define_variable, but the value is a list, and the variable may
6411 # be defined conditionally.  The second argument is the condition
6412 # under which the value should be defined; this should be the empty
6413 # string to define the variable unconditionally.  The third argument
6414 # is a list holding the values to use for the variable.  The value is
6415 # pretty printed in the output file.
6416 sub define_pretty_variable ($$$@)
6418     my ($var, $cond, $where, @value) = @_;
6420     if (! vardef ($var, $cond))
6421     {
6422         Automake::Variable::define ($var, VAR_AUTOMAKE, '', $cond, "@value",
6423                                     '', $where, VAR_PRETTY);
6424         rvar ($var)->rdef ($cond)->set_seen;
6425     }
6429 # define_variable ($VAR, $VALUE, $WHERE)
6430 # --------------------------------------
6431 # Define a new Automake Makefile variable VAR to VALUE, but only if
6432 # not already defined.
6433 sub define_variable ($$$)
6435     my ($var, $value, $where) = @_;
6436     define_pretty_variable ($var, TRUE, $where, $value);
6440 # define_files_variable ($VAR, \@BASENAME, $EXTENSION, $WHERE)
6441 # -----------------------------------------------------------
6442 # Define the $VAR which content is the list of file names composed of
6443 # a @BASENAME and the $EXTENSION.
6444 sub define_files_variable ($\@$$)
6446   my ($var, $basename, $extension, $where) = @_;
6447   define_variable ($var,
6448                    join (' ', map { "$_.$extension" } @$basename),
6449                    $where);
6453 # Like define_variable, but define a variable to be the configure
6454 # substitution by the same name.
6455 sub define_configure_variable ($)
6457   my ($var) = @_;
6459   my $pretty = VAR_ASIS;
6460   my $owner = VAR_CONFIGURE;
6462   # Some variables we do not want to output.  For instance it
6463   # would be a bad idea to output `U = @U@` when `@U@` can be
6464   # substituted as `\`.
6465   $pretty = VAR_SILENT if exists $ignored_configure_vars{$var};
6467   # ANSI2KNR is a variable that Automake wants to redefine, so
6468   # it must be owned by Automake.  (It is also used as a proof
6469   # that AM_C_PROTOTYPES has been run, that's why we do not simply
6470   # omit the AC_SUBST.)
6471   $owner = VAR_AUTOMAKE if $var eq 'ANSI2KNR';
6473   Automake::Variable::define ($var, $owner, '', TRUE, subst $var,
6474                               '', $configure_vars{$var}, $pretty);
6478 # define_compiler_variable ($LANG)
6479 # --------------------------------
6480 # Define a compiler variable.  We also handle defining the `LT'
6481 # version of the command when using libtool.
6482 sub define_compiler_variable ($)
6484     my ($lang) = @_;
6486     my ($var, $value) = ($lang->compiler, $lang->compile);
6487     my $libtool_tag = '';
6488     $libtool_tag = '--tag=' . $lang->libtool_tag . ' '
6489       if $lang->libtool_tag && exists $libtool_tags{$lang->libtool_tag};
6490     &define_variable ($var, $value, INTERNAL);
6491     if (var ('LIBTOOL'))
6492       {
6493         my $verbose = define_verbose_libtool ();
6494         &define_variable ("LT$var",
6495                           "\$(LIBTOOL) $verbose $libtool_tag\$(AM_LIBTOOLFLAGS) "
6496                           . "\$(LIBTOOLFLAGS) --mode=compile $value",
6497                           INTERNAL);
6498       }
6499     define_verbose_tagvar ($lang->ccer || 'GEN');
6503 # define_linker_variable ($LANG)
6504 # ------------------------------
6505 # Define linker variables.
6506 sub define_linker_variable ($)
6508     my ($lang) = @_;
6510     my $libtool_tag = '';
6511     $libtool_tag = '--tag=' . $lang->libtool_tag . ' '
6512       if $lang->libtool_tag && exists $libtool_tags{$lang->libtool_tag};
6513     # CCLD = $(CC).
6514     &define_variable ($lang->lder, $lang->ld, INTERNAL);
6515     # CCLINK = $(CCLD) blah blah...
6516     my $link = '';
6517     if (var ('LIBTOOL'))
6518       {
6519         my $verbose = define_verbose_libtool ();
6520         $link = "\$(LIBTOOL) $verbose $libtool_tag\$(AM_LIBTOOLFLAGS) "
6521                 . "\$(LIBTOOLFLAGS) --mode=link ";
6522       }
6523     &define_variable ($lang->linker, $link . $lang->link, INTERNAL);
6524     &define_variable ($lang->compiler,  $lang);
6525     &define_verbose_tagvar ($lang->lder || 'GEN');
6528 sub define_per_target_linker_variable ($$)
6530   my ($linker, $target) = @_;
6532   # If the user wrote a custom link command, we don't define ours.
6533   return "${target}_LINK"
6534     if set_seen "${target}_LINK";
6536   my $xlink = $linker ? $linker : 'LINK';
6538   my $lang = $link_languages{$xlink};
6539   prog_error "Unknown language for linker variable `$xlink'"
6540     unless $lang;
6542   my $link_command = $lang->link;
6543   if (var 'LIBTOOL')
6544     {
6545       my $libtool_tag = '';
6546       $libtool_tag = '--tag=' . $lang->libtool_tag . ' '
6547         if $lang->libtool_tag && exists $libtool_tags{$lang->libtool_tag};
6549       my $verbose = define_verbose_libtool ();
6550       $link_command =
6551         "\$(LIBTOOL) $verbose $libtool_tag\$(AM_LIBTOOLFLAGS) \$(LIBTOOLFLAGS) "
6552         . "--mode=link " . $link_command;
6553     }
6555   # Rewrite each occurrence of `AM_$flag' in the link
6556   # command into `${derived}_$flag' if it exists.
6557   my $orig_command = $link_command;
6558   my @flags = (@{$lang->flags}, 'LDFLAGS');
6559   push @flags, 'LIBTOOLFLAGS' if var 'LIBTOOL';
6560   for my $flag (@flags)
6561     {
6562       my $val = "${target}_$flag";
6563       $link_command =~ s/\(AM_$flag\)/\($val\)/
6564         if set_seen ($val);
6565     }
6567   # If the computed command is the same as the generic command, use
6568   # the command linker variable.
6569   return ($lang->linker, $lang->lder)
6570     if $link_command eq $orig_command;
6572   &define_variable ("${target}_LINK", $link_command, INTERNAL);
6573   return ("${target}_LINK", $lang->lder);
6576 ################################################################
6578 # &check_trailing_slash ($WHERE, $LINE)
6579 # --------------------------------------
6580 # Return 1 iff $LINE ends with a slash.
6581 # Might modify $LINE.
6582 sub check_trailing_slash ($\$)
6584   my ($where, $line) = @_;
6586   # Ignore `##' lines.
6587   return 0 if $$line =~ /$IGNORE_PATTERN/o;
6589   # Catch and fix a common error.
6590   msg "syntax", $where, "whitespace following trailing backslash"
6591     if $$line =~ s/\\\s+\n$/\\\n/;
6593   return $$line =~ /\\$/;
6597 # &read_am_file ($AMFILE, $WHERE)
6598 # -------------------------------
6599 # Read Makefile.am and set up %contents.  Simultaneously copy lines
6600 # from Makefile.am into $output_trailer, or define variables as
6601 # appropriate.  NOTE we put rules in the trailer section.  We want
6602 # user rules to come after our generated stuff.
6603 sub read_am_file ($$)
6605     my ($amfile, $where) = @_;
6607     my $am_file = new Automake::XFile ("< $amfile");
6608     verb "reading $amfile";
6610     # Keep track of the youngest output dependency.
6611     my $mtime = mtime $amfile;
6612     $output_deps_greatest_timestamp = $mtime
6613       if $mtime > $output_deps_greatest_timestamp;
6615     my $spacing = '';
6616     my $comment = '';
6617     my $blank = 0;
6618     my $saw_bk = 0;
6619     my $var_look = VAR_ASIS;
6621     use constant IN_VAR_DEF => 0;
6622     use constant IN_RULE_DEF => 1;
6623     use constant IN_COMMENT => 2;
6624     my $prev_state = IN_RULE_DEF;
6626     while ($_ = $am_file->getline)
6627     {
6628         $where->set ("$amfile:$.");
6629         if (/$IGNORE_PATTERN/o)
6630         {
6631             # Merely delete comments beginning with two hashes.
6632         }
6633         elsif (/$WHITE_PATTERN/o)
6634         {
6635             error $where, "blank line following trailing backslash"
6636               if $saw_bk;
6637             # Stick a single white line before the incoming macro or rule.
6638             $spacing = "\n";
6639             $blank = 1;
6640             # Flush all comments seen so far.
6641             if ($comment ne '')
6642             {
6643                 $output_vars .= $comment;
6644                 $comment = '';
6645             }
6646         }
6647         elsif (/$COMMENT_PATTERN/o)
6648         {
6649             # Stick comments before the incoming macro or rule.  Make
6650             # sure a blank line precedes the first block of comments.
6651             $spacing = "\n" unless $blank;
6652             $blank = 1;
6653             $comment .= $spacing . $_;
6654             $spacing = '';
6655             $prev_state = IN_COMMENT;
6656         }
6657         else
6658         {
6659             last;
6660         }
6661         $saw_bk = check_trailing_slash ($where, $_);
6662     }
6664     # We save the conditional stack on entry, and then check to make
6665     # sure it is the same on exit.  This lets us conditionally include
6666     # other files.
6667     my @saved_cond_stack = @cond_stack;
6668     my $cond = new Automake::Condition (@cond_stack);
6670     my $last_var_name = '';
6671     my $last_var_type = '';
6672     my $last_var_value = '';
6673     my $last_where;
6674     # FIXME: shouldn't use $_ in this loop; it is too big.
6675     while ($_)
6676     {
6677         $where->set ("$amfile:$.");
6679         # Make sure the line is \n-terminated.
6680         chomp;
6681         $_ .= "\n";
6683         # Don't look at MAINTAINER_MODE_TRUE here.  That shouldn't be
6684         # used by users.  @MAINT@ is an anachronism now.
6685         $_ =~ s/\@MAINT\@//g
6686             unless $seen_maint_mode;
6688         my $new_saw_bk = check_trailing_slash ($where, $_);
6690         if (/$IGNORE_PATTERN/o)
6691         {
6692             # Merely delete comments beginning with two hashes.
6694             # Keep any backslash from the previous line.
6695             $new_saw_bk = $saw_bk;
6696         }
6697         elsif (/$WHITE_PATTERN/o)
6698         {
6699             # Stick a single white line before the incoming macro or rule.
6700             $spacing = "\n";
6701             error $where, "blank line following trailing backslash"
6702               if $saw_bk;
6703         }
6704         elsif (/$COMMENT_PATTERN/o)
6705         {
6706             error $where, "comment following trailing backslash"
6707               if $saw_bk && $prev_state != IN_COMMENT;
6709             # Stick comments before the incoming macro or rule.
6710             $comment .= $spacing . $_;
6711             $spacing = '';
6712             $prev_state = IN_COMMENT;
6713         }
6714         elsif ($saw_bk)
6715         {
6716             if ($prev_state == IN_RULE_DEF)
6717             {
6718               my $cond = new Automake::Condition @cond_stack;
6719               $output_trailer .= $cond->subst_string;
6720               $output_trailer .= $_;
6721             }
6722             elsif ($prev_state == IN_COMMENT)
6723             {
6724                 # If the line doesn't start with a `#', add it.
6725                 # We do this because a continued comment like
6726                 #   # A = foo \
6727                 #         bar \
6728                 #         baz
6729                 # is not portable.  BSD make doesn't honor
6730                 # escaped newlines in comments.
6731                 s/^#?/#/;
6732                 $comment .= $spacing . $_;
6733             }
6734             else # $prev_state == IN_VAR_DEF
6735             {
6736               $last_var_value .= ' '
6737                 unless $last_var_value =~ /\s$/;
6738               $last_var_value .= $_;
6740               if (!/\\$/)
6741                 {
6742                   Automake::Variable::define ($last_var_name, VAR_MAKEFILE,
6743                                               $last_var_type, $cond,
6744                                               $last_var_value, $comment,
6745                                               $last_where, VAR_ASIS)
6746                     if $cond != FALSE;
6747                   $comment = $spacing = '';
6748                 }
6749             }
6750         }
6752         elsif (/$IF_PATTERN/o)
6753           {
6754             $cond = cond_stack_if ($1, $2, $where);
6755           }
6756         elsif (/$ELSE_PATTERN/o)
6757           {
6758             $cond = cond_stack_else ($1, $2, $where);
6759           }
6760         elsif (/$ENDIF_PATTERN/o)
6761           {
6762             $cond = cond_stack_endif ($1, $2, $where);
6763           }
6765         elsif (/$RULE_PATTERN/o)
6766         {
6767             # Found a rule.
6768             $prev_state = IN_RULE_DEF;
6770             # For now we have to output all definitions of user rules
6771             # and can't diagnose duplicates (see the comment in
6772             # Automake::Rule::define). So we go on and ignore the return value.
6773             Automake::Rule::define ($1, $amfile, RULE_USER, $cond, $where);
6775             check_variable_expansions ($_, $where);
6777             $output_trailer .= $comment . $spacing;
6778             my $cond = new Automake::Condition @cond_stack;
6779             $output_trailer .= $cond->subst_string;
6780             $output_trailer .= $_;
6781             $comment = $spacing = '';
6782         }
6783         elsif (/$ASSIGNMENT_PATTERN/o)
6784         {
6785             # Found a macro definition.
6786             $prev_state = IN_VAR_DEF;
6787             $last_var_name = $1;
6788             $last_var_type = $2;
6789             $last_var_value = $3;
6790             $last_where = $where->clone;
6791             if ($3 ne '' && substr ($3, -1) eq "\\")
6792               {
6793                 # We preserve the `\' because otherwise the long lines
6794                 # that are generated will be truncated by broken
6795                 # `sed's.
6796                 $last_var_value = $3 . "\n";
6797               }
6798             # Normally we try to output variable definitions in the
6799             # same format they were input.  However, POSIX compliant
6800             # systems are not required to support lines longer than
6801             # 2048 bytes (most notably, some sed implementation are
6802             # limited to 4000 bytes, and sed is used by config.status
6803             # to rewrite Makefile.in into Makefile).  Moreover nobody
6804             # would really write such long lines by hand since it is
6805             # hardly maintainable.  So if a line is longer that 1000
6806             # bytes (an arbitrary limit), assume it has been
6807             # automatically generated by some tools, and flatten the
6808             # variable definition.  Otherwise, keep the variable as it
6809             # as been input.
6810             $var_look = VAR_PRETTY if length ($last_var_value) >= 1000;
6812             if (!/\\$/)
6813               {
6814                 Automake::Variable::define ($last_var_name, VAR_MAKEFILE,
6815                                             $last_var_type, $cond,
6816                                             $last_var_value, $comment,
6817                                             $last_where, $var_look)
6818                   if $cond != FALSE;
6819                 $comment = $spacing = '';
6820                 $var_look = VAR_ASIS;
6821               }
6822         }
6823         elsif (/$INCLUDE_PATTERN/o)
6824         {
6825             my $path = $1;
6827             if ($path =~ s/^\$\(top_srcdir\)\///)
6828               {
6829                 push (@include_stack, "\$\(top_srcdir\)/$path");
6830                 # Distribute any included file.
6832                 # Always use the $(top_srcdir) prefix in DIST_COMMON,
6833                 # otherwise OSF make will implicitly copy the included
6834                 # file in the build tree during `make distdir' to satisfy
6835                 # the dependency.
6836                 # (subdircond2.test and subdircond3.test will fail.)
6837                 push_dist_common ("\$\(top_srcdir\)/$path");
6838               }
6839             else
6840               {
6841                 $path =~ s/\$\(srcdir\)\///;
6842                 push (@include_stack, "\$\(srcdir\)/$path");
6843                 # Always use the $(srcdir) prefix in DIST_COMMON,
6844                 # otherwise OSF make will implicitly copy the included
6845                 # file in the build tree during `make distdir' to satisfy
6846                 # the dependency.
6847                 # (subdircond2.test and subdircond3.test will fail.)
6848                 push_dist_common ("\$\(srcdir\)/$path");
6849                 $path = $relative_dir . "/" . $path if $relative_dir ne '.';
6850               }
6851             $where->push_context ("`$path' included from here");
6852             &read_am_file ($path, $where);
6853             $where->pop_context;
6854         }
6855         else
6856         {
6857             # This isn't an error; it is probably a continued rule.
6858             # In fact, this is what we assume.
6859             $prev_state = IN_RULE_DEF;
6860             check_variable_expansions ($_, $where);
6861             $output_trailer .= $comment . $spacing;
6862             my $cond = new Automake::Condition @cond_stack;
6863             $output_trailer .= $cond->subst_string;
6864             $output_trailer .= $_;
6865             $comment = $spacing = '';
6866             error $where, "`#' comment at start of rule is unportable"
6867               if $_ =~ /^\t\s*\#/;
6868         }
6870         $saw_bk = $new_saw_bk;
6871         $_ = $am_file->getline;
6872     }
6874     $output_trailer .= $comment;
6876     error ($where, "trailing backslash on last line")
6877       if $saw_bk;
6879     error ($where, (@cond_stack ? "unterminated conditionals: @cond_stack"
6880                     : "too many conditionals closed in include file"))
6881       if "@saved_cond_stack" ne "@cond_stack";
6885 # define_standard_variables ()
6886 # ----------------------------
6887 # A helper for read_main_am_file which initializes configure variables
6888 # and variables from header-vars.am.
6889 sub define_standard_variables
6891   my $saved_output_vars = $output_vars;
6892   my ($comments, undef, $rules) =
6893     file_contents_internal (1, "$libdir/am/header-vars.am",
6894                             new Automake::Location);
6896   foreach my $var (sort keys %configure_vars)
6897     {
6898       &define_configure_variable ($var);
6899     }
6901   $output_vars .= $comments . $rules;
6904 # Read main am file.
6905 sub read_main_am_file
6907     my ($amfile) = @_;
6909     # This supports the strange variable tricks we are about to play.
6910     prog_error (macros_dump () . "variable defined before read_main_am_file")
6911       if (scalar (variables) > 0);
6913     # Generate copyright header for generated Makefile.in.
6914     # We do discard the output of predefined variables, handled below.
6915     $output_vars = ("# $in_file_name generated by automake "
6916                    . $VERSION . " from $am_file_name.\n");
6917     $output_vars .= '# ' . subst ('configure_input') . "\n";
6918     $output_vars .= $gen_copyright;
6920     # We want to predefine as many variables as possible.  This lets
6921     # the user set them with `+=' in Makefile.am.
6922     &define_standard_variables;
6924     # Read user file, which might override some of our values.
6925     &read_am_file ($amfile, new Automake::Location);
6930 ################################################################
6932 # $FLATTENED
6933 # &flatten ($STRING)
6934 # ------------------
6935 # Flatten the $STRING and return the result.
6936 sub flatten
6938   $_ = shift;
6940   s/\\\n//somg;
6941   s/\s+/ /g;
6942   s/^ //;
6943   s/ $//;
6945   return $_;
6949 # transform_token ($TOKEN, \%PAIRS, $KEY)
6950 # =======================================
6951 # Return the value associated to $KEY in %PAIRS, as used on $TOKEN
6952 # (which should be ?KEY? or any of the special %% requests)..
6953 sub transform_token ($$$)
6955   my ($token, $transform, $key) = @_;
6956   my $res = $transform->{$key};
6957   prog_error "Unknown key `$key' in `$token'" unless defined $res;
6958   return $res;
6962 # transform ($TOKEN, \%PAIRS)
6963 # ===========================
6964 # If ($TOKEN, $VAL) is in %PAIRS:
6965 #   - replaces %KEY% with $VAL,
6966 #   - enables/disables ?KEY? and ?!KEY?,
6967 #   - replaces %?KEY% with TRUE or FALSE.
6968 #   - replaces %KEY?IFTRUE%, %KEY:IFFALSE%, and %KEY?IFTRUE:IFFALSE% with
6969 #     IFTRUE / IFFALSE, as appropriate.
6970 sub transform ($$)
6972   my ($token, $transform) = @_;
6974   # %KEY%.
6975   # Must be before the following pattern to exclude the case
6976   # when there is neither IFTRUE nor IFFALSE.
6977   if ($token =~ /^%([\w\-]+)%$/)
6978     {
6979       return transform_token ($token, $transform, $1);
6980     }
6981   # %KEY?IFTRUE%, %KEY:IFFALSE%, and %KEY?IFTRUE:IFFALSE%.
6982   elsif ($token =~ /^%([\w\-]+)(?:\?([^?:%]+))?(?::([^?:%]+))?%$/)
6983     {
6984       return transform_token ($token, $transform, $1) ? ($2 || '') : ($3 || '');
6985     }
6986   # %?KEY%.
6987   elsif ($token =~ /^%\?([\w\-]+)%$/)
6988     {
6989       return transform_token ($token, $transform, $1) ? 'TRUE' : 'FALSE';
6990     }
6991   # ?KEY? and ?!KEY?.
6992   elsif ($token =~ /^ \? (!?) ([\w\-]+) \? $/x)
6993     {
6994       my $neg = ($1 eq '!') ? 1 : 0;
6995       my $val = transform_token ($token, $transform, $2);
6996       return (!!$val == $neg) ? '##%' : '';
6997     }
6998   else
6999     {
7000       prog_error "Unknown request format: $token";
7001     }
7005 # @PARAGRAPHS
7006 # &make_paragraphs ($MAKEFILE, [%TRANSFORM])
7007 # ------------------------------------------
7008 # Load a $MAKEFILE, apply the %TRANSFORM, and return it as a list of
7009 # paragraphs.
7010 sub make_paragraphs ($%)
7012   my ($file, %transform) = @_;
7014   # Complete %transform with global options.
7015   # Note that %transform goes last, so it overrides global options.
7016   %transform = ('CYGNUS'      => !! option 'cygnus',
7017                  'MAINTAINER-MODE'
7018                  => $seen_maint_mode ? subst ('MAINTAINER_MODE_TRUE') : '',
7020                  'XZ'          => !! option 'dist-xz',
7021                  'LZMA'        => !! option 'dist-lzma',
7022                  'BZIP2'       => !! option 'dist-bzip2',
7023                  'COMPRESS'    => !! option 'dist-tarZ',
7024                  'GZIP'        =>  ! option 'no-dist-gzip',
7025                  'SHAR'        => !! option 'dist-shar',
7026                  'ZIP'         => !! option 'dist-zip',
7028                  'INSTALL-INFO' =>  ! option 'no-installinfo',
7029                  'INSTALL-MAN'  =>  ! option 'no-installman',
7030                  'HAVE-MANS'    => !! var ('MANS'),
7031                  'CK-NEWS'      => !! option 'check-news',
7033                  'SUBDIRS'      => !! var ('SUBDIRS'),
7034                  'TOPDIR_P'     => $relative_dir eq '.',
7036                  'BUILD'    => ($seen_canonical >= AC_CANONICAL_BUILD),
7037                  'HOST'     => ($seen_canonical >= AC_CANONICAL_HOST),
7038                  'TARGET'   => ($seen_canonical >= AC_CANONICAL_TARGET),
7040                  'LIBTOOL'      => !! var ('LIBTOOL'),
7041                  'NONLIBTOOL'   => 1,
7042                  'FIRST'        => ! $transformed_files{$file},
7043                 %transform);
7045   $transformed_files{$file} = 1;
7046   $_ = $am_file_cache{$file};
7048   if (! defined $_)
7049     {
7050       verb "reading $file";
7051       # Swallow the whole file.
7052       my $fc_file = new Automake::XFile "< $file";
7053       my $saved_dollar_slash = $/;
7054       undef $/;
7055       $_ = $fc_file->getline;
7056       $/ = $saved_dollar_slash;
7057       $fc_file->close;
7059       # Remove ##-comments.
7060       # Besides we don't need more than two consecutive new-lines.
7061       s/(?:$IGNORE_PATTERN|(?<=\n\n)\n+)//gom;
7063       $am_file_cache{$file} = $_;
7064     }
7066   # Substitute Automake template tokens.
7067   s/(?: % \?? [\w\-]+ %
7068       | % [\w\-]+ (?:\?[^?:%]+)? (?::[^?:%]+)? %
7069       | \? !? [\w\-]+ \?
7070     )/transform($&, \%transform)/gex;
7071   # transform() may have added some ##%-comments to strip.
7072   # (we use `##%' instead of `##' so we can distinguish ##%##%##% from
7073   # ####### and do not remove the latter.)
7074   s/^[ \t]*(?:##%)+.*\n//gm;
7076   # Split at unescaped new lines.
7077   my @lines = split (/(?<!\\)\n/, $_);
7078   my @res;
7080   while (defined ($_ = shift @lines))
7081     {
7082       my $paragraph = $_;
7083       # If we are a rule, eat as long as we start with a tab.
7084       if (/$RULE_PATTERN/smo)
7085         {
7086           while (defined ($_ = shift @lines) && $_ =~ /^\t/)
7087             {
7088               $paragraph .= "\n$_";
7089             }
7090           unshift (@lines, $_);
7091         }
7093       # If we are a comments, eat as much comments as you can.
7094       elsif (/$COMMENT_PATTERN/smo)
7095         {
7096           while (defined ($_ = shift @lines)
7097                  && $_ =~ /$COMMENT_PATTERN/smo)
7098             {
7099               $paragraph .= "\n$_";
7100             }
7101           unshift (@lines, $_);
7102         }
7104       push @res, $paragraph;
7105     }
7107   return @res;
7112 # ($COMMENT, $VARIABLES, $RULES)
7113 # &file_contents_internal ($IS_AM, $FILE, $WHERE, [%TRANSFORM])
7114 # -------------------------------------------------------------
7115 # Return contents of a file from $libdir/am, automatically skipping
7116 # macros or rules which are already known. $IS_AM iff the caller is
7117 # reading an Automake file (as opposed to the user's Makefile.am).
7118 sub file_contents_internal ($$$%)
7120     my ($is_am, $file, $where, %transform) = @_;
7122     $where->set ($file);
7124     my $result_vars = '';
7125     my $result_rules = '';
7126     my $comment = '';
7127     my $spacing = '';
7129     # The following flags are used to track rules spanning across
7130     # multiple paragraphs.
7131     my $is_rule = 0;            # 1 if we are processing a rule.
7132     my $discard_rule = 0;       # 1 if the current rule should not be output.
7134     # We save the conditional stack on entry, and then check to make
7135     # sure it is the same on exit.  This lets us conditionally include
7136     # other files.
7137     my @saved_cond_stack = @cond_stack;
7138     my $cond = new Automake::Condition (@cond_stack);
7140     foreach (make_paragraphs ($file, %transform))
7141     {
7142         # FIXME: no line number available.
7143         $where->set ($file);
7145         # Sanity checks.
7146         error $where, "blank line following trailing backslash:\n$_"
7147           if /\\$/;
7148         error $where, "comment following trailing backslash:\n$_"
7149           if /\\#/;
7151         if (/^$/)
7152         {
7153             $is_rule = 0;
7154             # Stick empty line before the incoming macro or rule.
7155             $spacing = "\n";
7156         }
7157         elsif (/$COMMENT_PATTERN/mso)
7158         {
7159             $is_rule = 0;
7160             # Stick comments before the incoming macro or rule.
7161             $comment = "$_\n";
7162         }
7164         # Handle inclusion of other files.
7165         elsif (/$INCLUDE_PATTERN/o)
7166         {
7167             if ($cond != FALSE)
7168               {
7169                 my $file = ($is_am ? "$libdir/am/" : '') . $1;
7170                 $where->push_context ("`$file' included from here");
7171                 # N-ary `.=' fails.
7172                 my ($com, $vars, $rules)
7173                   = file_contents_internal ($is_am, $file, $where, %transform);
7174                 $where->pop_context;
7175                 $comment .= $com;
7176                 $result_vars .= $vars;
7177                 $result_rules .= $rules;
7178               }
7179         }
7181         # Handling the conditionals.
7182         elsif (/$IF_PATTERN/o)
7183           {
7184             $cond = cond_stack_if ($1, $2, $file);
7185           }
7186         elsif (/$ELSE_PATTERN/o)
7187           {
7188             $cond = cond_stack_else ($1, $2, $file);
7189           }
7190         elsif (/$ENDIF_PATTERN/o)
7191           {
7192             $cond = cond_stack_endif ($1, $2, $file);
7193           }
7195         # Handling rules.
7196         elsif (/$RULE_PATTERN/mso)
7197         {
7198           $is_rule = 1;
7199           $discard_rule = 0;
7200           # Separate relationship from optional actions: the first
7201           # `new-line tab" not preceded by backslash (continuation
7202           # line).
7203           my $paragraph = $_;
7204           /^(.*?)(?:(?<!\\)\n(\t.*))?$/s;
7205           my ($relationship, $actions) = ($1, $2 || '');
7207           # Separate targets from dependencies: the first colon.
7208           $relationship =~ /^([^:]+\S+) *: *(.*)$/som;
7209           my ($targets, $dependencies) = ($1, $2);
7210           # Remove the escaped new lines.
7211           # I don't know why, but I have to use a tmp $flat_deps.
7212           my $flat_deps = &flatten ($dependencies);
7213           my @deps = split (' ', $flat_deps);
7215           foreach (split (' ', $targets))
7216             {
7217               # FIXME: 1. We are not robust to people defining several targets
7218               # at once, only some of them being in %dependencies.  The
7219               # actions from the targets in %dependencies are usually generated
7220               # from the content of %actions, but if some targets in $targets
7221               # are not in %dependencies the ELSE branch will output
7222               # a rule for all $targets (i.e. the targets which are both
7223               # in %dependencies and $targets will have two rules).
7225               # FIXME: 2. The logic here is not able to output a
7226               # multi-paragraph rule several time (e.g. for each condition
7227               # it is defined for) because it only knows the first paragraph.
7229               # FIXME: 3. We are not robust to people defining a subset
7230               # of a previously defined "multiple-target" rule.  E.g.
7231               # `foo:' after `foo bar:'.
7233               # Output only if not in FALSE.
7234               if (defined $dependencies{$_} && $cond != FALSE)
7235                 {
7236                   &depend ($_, @deps);
7237                   register_action ($_, $actions);
7238                 }
7239               else
7240                 {
7241                   # Free-lance dependency.  Output the rule for all the
7242                   # targets instead of one by one.
7243                   my @undefined_conds =
7244                     Automake::Rule::define ($targets, $file,
7245                                             $is_am ? RULE_AUTOMAKE : RULE_USER,
7246                                             $cond, $where);
7247                   for my $undefined_cond (@undefined_conds)
7248                     {
7249                       my $condparagraph = $paragraph;
7250                       $condparagraph =~ s/^/$undefined_cond->subst_string/gme;
7251                       $result_rules .= "$spacing$comment$condparagraph\n";
7252                     }
7253                   if (scalar @undefined_conds == 0)
7254                     {
7255                       # Remember to discard next paragraphs
7256                       # if they belong to this rule.
7257                       # (but see also FIXME: #2 above.)
7258                       $discard_rule = 1;
7259                     }
7260                   $comment = $spacing = '';
7261                   last;
7262                 }
7263             }
7264         }
7266         elsif (/$ASSIGNMENT_PATTERN/mso)
7267         {
7268             my ($var, $type, $val) = ($1, $2, $3);
7269             error $where, "variable `$var' with trailing backslash"
7270               if /\\$/;
7272             $is_rule = 0;
7274             Automake::Variable::define ($var,
7275                                         $is_am ? VAR_AUTOMAKE : VAR_MAKEFILE,
7276                                         $type, $cond, $val, $comment, $where,
7277                                         VAR_ASIS)
7278               if $cond != FALSE;
7280             $comment = $spacing = '';
7281         }
7282         else
7283         {
7284             # This isn't an error; it is probably some tokens which
7285             # configure is supposed to replace, such as `@SET-MAKE@',
7286             # or some part of a rule cut by an if/endif.
7287             if (! $cond->false && ! ($is_rule && $discard_rule))
7288               {
7289                 s/^/$cond->subst_string/gme;
7290                 $result_rules .= "$spacing$comment$_\n";
7291               }
7292             $comment = $spacing = '';
7293         }
7294     }
7296     error ($where, @cond_stack ?
7297            "unterminated conditionals: @cond_stack" :
7298            "too many conditionals closed in include file")
7299       if "@saved_cond_stack" ne "@cond_stack";
7301     return ($comment, $result_vars, $result_rules);
7305 # $CONTENTS
7306 # &file_contents ($BASENAME, $WHERE, [%TRANSFORM])
7307 # ------------------------------------------------
7308 # Return contents of a file from $libdir/am, automatically skipping
7309 # macros or rules which are already known.
7310 sub file_contents ($$%)
7312     my ($basename, $where, %transform) = @_;
7313     my ($comments, $variables, $rules) =
7314       file_contents_internal (1, "$libdir/am/$basename.am", $where,
7315                               %transform);
7316     return "$comments$variables$rules";
7320 # @PREFIX
7321 # &am_primary_prefixes ($PRIMARY, $CAN_DIST, @PREFIXES)
7322 # -----------------------------------------------------
7323 # Find all variable prefixes that are used for install directories.  A
7324 # prefix `zar' qualifies iff:
7326 # * `zardir' is a variable.
7327 # * `zar_PRIMARY' is a variable.
7329 # As a side effect, it looks for misspellings.  It is an error to have
7330 # a variable ending in a "reserved" suffix whose prefix is unknown, e.g.
7331 # "bni_PROGRAMS".  However, unusual prefixes are allowed if a variable
7332 # of the same name (with "dir" appended) exists.  For instance, if the
7333 # variable "zardir" is defined, then "zar_PROGRAMS" becomes valid.
7334 # This is to provide a little extra flexibility in those cases which
7335 # need it.
7336 sub am_primary_prefixes ($$@)
7338   my ($primary, $can_dist, @prefixes) = @_;
7340   local $_;
7341   my %valid = map { $_ => 0 } @prefixes;
7342   $valid{'EXTRA'} = 0;
7343   foreach my $var (variables $primary)
7344     {
7345       # Automake is allowed to define variables that look like primaries
7346       # but which aren't.  E.g. INSTALL_sh_DATA.
7347       # Autoconf can also define variables like INSTALL_DATA, so
7348       # ignore all configure variables (at least those which are not
7349       # redefined in Makefile.am).
7350       # FIXME: We should make sure that these variables are not
7351       # conditionally defined (or else adjust the condition below).
7352       my $def = $var->def (TRUE);
7353       next if $def && $def->owner != VAR_MAKEFILE;
7355       my $varname = $var->name;
7357       if ($varname =~ /^(nobase_)?(dist_|nodist_)?(.*)_[[:alnum:]]+$/)
7358         {
7359           my ($base, $dist, $X) = ($1 || '', $2 || '', $3 || '');
7360           if ($dist ne '' && ! $can_dist)
7361             {
7362               err_var ($var,
7363                        "invalid variable `$varname': `dist' is forbidden");
7364             }
7365           # Standard directories must be explicitly allowed.
7366           elsif (! defined $valid{$X} && exists $standard_prefix{$X})
7367             {
7368               err_var ($var,
7369                        "`${X}dir' is not a legitimate directory " .
7370                        "for `$primary'");
7371             }
7372           # A not explicitly valid directory is allowed if Xdir is defined.
7373           elsif (! defined $valid{$X} &&
7374                  $var->requires_variables ("`$varname' is used", "${X}dir"))
7375             {
7376               # Nothing to do.  Any error message has been output
7377               # by $var->requires_variables.
7378             }
7379           else
7380             {
7381               # Ensure all extended prefixes are actually used.
7382               $valid{"$base$dist$X"} = 1;
7383             }
7384         }
7385       else
7386         {
7387           prog_error "unexpected variable name: $varname";
7388         }
7389     }
7391   # Return only those which are actually defined.
7392   return sort grep { var ($_ . '_' . $primary) } keys %valid;
7396 # Handle `where_HOW' variable magic.  Does all lookups, generates
7397 # install code, and possibly generates code to define the primary
7398 # variable.  The first argument is the name of the .am file to munge,
7399 # the second argument is the primary variable (e.g. HEADERS), and all
7400 # subsequent arguments are possible installation locations.
7402 # Returns list of [$location, $value] pairs, where
7403 # $value's are the values in all where_HOW variable, and $location
7404 # there associated location (the place here their parent variables were
7405 # defined).
7407 # FIXME: this should be rewritten to be cleaner.  It should be broken
7408 # up into multiple functions.
7410 # Usage is: am_install_var (OPTION..., file, HOW, where...)
7411 sub am_install_var
7413   my (@args) = @_;
7415   my $do_require = 1;
7416   my $can_dist = 0;
7417   my $default_dist = 0;
7418   while (@args)
7419     {
7420       if ($args[0] eq '-noextra')
7421         {
7422           $do_require = 0;
7423         }
7424       elsif ($args[0] eq '-candist')
7425         {
7426           $can_dist = 1;
7427         }
7428       elsif ($args[0] eq '-defaultdist')
7429         {
7430           $default_dist = 1;
7431           $can_dist = 1;
7432         }
7433       elsif ($args[0] !~ /^-/)
7434         {
7435           last;
7436         }
7437       shift (@args);
7438     }
7440   my ($file, $primary, @prefix) = @args;
7442   # Now that configure substitutions are allowed in where_HOW
7443   # variables, it is an error to actually define the primary.  We
7444   # allow `JAVA', as it is customarily used to mean the Java
7445   # interpreter.  This is but one of several Java hacks.  Similarly,
7446   # `PYTHON' is customarily used to mean the Python interpreter.
7447   reject_var $primary, "`$primary' is an anachronism"
7448     unless $primary eq 'JAVA' || $primary eq 'PYTHON';
7450   # Get the prefixes which are valid and actually used.
7451   @prefix = am_primary_prefixes ($primary, $can_dist, @prefix);
7453   # If a primary includes a configure substitution, then the EXTRA_
7454   # form is required.  Otherwise we can't properly do our job.
7455   my $require_extra;
7457   my @used = ();
7458   my @result = ();
7460   foreach my $X (@prefix)
7461     {
7462       my $nodir_name = $X;
7463       my $one_name = $X . '_' . $primary;
7464       my $one_var = var $one_name;
7466       my $strip_subdir = 1;
7467       # If subdir prefix should be preserved, do so.
7468       if ($nodir_name =~ /^nobase_/)
7469         {
7470           $strip_subdir = 0;
7471           $nodir_name =~ s/^nobase_//;
7472         }
7474       # If files should be distributed, do so.
7475       my $dist_p = 0;
7476       if ($can_dist)
7477         {
7478           $dist_p = (($default_dist && $nodir_name !~ /^nodist_/)
7479                      || (! $default_dist && $nodir_name =~ /^dist_/));
7480           $nodir_name =~ s/^(dist|nodist)_//;
7481         }
7484       # Use the location of the currently processed variable.
7485       # We are not processing a particular condition, so pick the first
7486       # available.
7487       my $tmpcond = $one_var->conditions->one_cond;
7488       my $where = $one_var->rdef ($tmpcond)->location->clone;
7490       # Append actual contents of where_PRIMARY variable to
7491       # @result, skipping @substitutions@.
7492       foreach my $locvals ($one_var->value_as_list_recursive (location => 1))
7493         {
7494           my ($loc, $value) = @$locvals;
7495           # Skip configure substitutions.
7496           if ($value =~ /^\@.*\@$/)
7497             {
7498               if ($nodir_name eq 'EXTRA')
7499                 {
7500                   error ($where,
7501                          "`$one_name' contains configure substitution, "
7502                          . "but shouldn't");
7503                 }
7504               # Check here to make sure variables defined in
7505               # configure.ac do not imply that EXTRA_PRIMARY
7506               # must be defined.
7507               elsif (! defined $configure_vars{$one_name})
7508                 {
7509                   $require_extra = $one_name
7510                     if $do_require;
7511                 }
7512             }
7513           else
7514             {
7515               # Strip any $(EXEEXT) suffix the user might have added, or this
7516               # will confuse &handle_source_transform and &check_canonical_spelling.
7517               # We'll add $(EXEEXT) back later anyway.
7518               # Do it here rather than in handle_programs so the uniquifying at the
7519               # end of this function works.
7520               ${$locvals}[1] =~ s/\$\(EXEEXT\)$//
7521                 if $primary eq 'PROGRAMS';
7523               push (@result, $locvals);
7524             }
7525         }
7526       # A blatant hack: we rewrite each _PROGRAMS primary to include
7527       # EXEEXT.
7528       append_exeext { 1 } $one_name
7529         if $primary eq 'PROGRAMS';
7530       # "EXTRA" shouldn't be used when generating clean targets,
7531       # all, or install targets.  We used to warn if EXTRA_FOO was
7532       # defined uselessly, but this was annoying.
7533       next
7534         if $nodir_name eq 'EXTRA';
7536       if ($nodir_name eq 'check')
7537         {
7538           push (@check, '$(' . $one_name . ')');
7539         }
7540       else
7541         {
7542           push (@used, '$(' . $one_name . ')');
7543         }
7545       # Is this to be installed?
7546       my $install_p = $nodir_name ne 'noinst' && $nodir_name ne 'check';
7548       # If so, with install-exec? (or install-data?).
7549       my $exec_p = ($nodir_name =~ /$EXEC_DIR_PATTERN/o);
7551       my $check_options_p = $install_p && !! option 'std-options';
7553       # Use the location of the currently processed variable as context.
7554       $where->push_context ("while processing `$one_name'");
7556       # The variable containing all files to distribute.
7557       my $distvar = "\$($one_name)";
7558       $distvar = shadow_unconditionally ($one_name, $where)
7559         if ($dist_p && $one_var->has_conditional_contents);
7561       # Singular form of $PRIMARY.
7562       (my $one_primary = $primary) =~ s/S$//;
7563       $output_rules .= &file_contents ($file, $where,
7564                                        PRIMARY     => $primary,
7565                                        ONE_PRIMARY => $one_primary,
7566                                        DIR         => $X,
7567                                        NDIR        => $nodir_name,
7568                                        BASE        => $strip_subdir,
7570                                        EXEC      => $exec_p,
7571                                        INSTALL   => $install_p,
7572                                        DIST      => $dist_p,
7573                                        DISTVAR   => $distvar,
7574                                        'CK-OPTS' => $check_options_p);
7575     }
7577   # The JAVA variable is used as the name of the Java interpreter.
7578   # The PYTHON variable is used as the name of the Python interpreter.
7579   if (@used && $primary ne 'JAVA' && $primary ne 'PYTHON')
7580     {
7581       # Define it.
7582       define_pretty_variable ($primary, TRUE, INTERNAL, @used);
7583       $output_vars .= "\n";
7584     }
7586   err_var ($require_extra,
7587            "`$require_extra' contains configure substitution,\n"
7588            . "but `EXTRA_$primary' not defined")
7589     if ($require_extra && ! var ('EXTRA_' . $primary));
7591   # Push here because PRIMARY might be configure time determined.
7592   push (@all, '$(' . $primary . ')')
7593     if @used && $primary ne 'JAVA' && $primary ne 'PYTHON';
7595   # Make the result unique.  This lets the user use conditionals in
7596   # a natural way, but still lets us program lazily -- we don't have
7597   # to worry about handling a particular object more than once.
7598   # We will keep only one location per object.
7599   my %result = ();
7600   for my $pair (@result)
7601     {
7602       my ($loc, $val) = @$pair;
7603       $result{$val} = $loc;
7604     }
7605   my @l = sort keys %result;
7606   return map { [$result{$_}->clone, $_] } @l;
7610 ################################################################
7612 # Each key in this hash is the name of a directory holding a
7613 # Makefile.in.  These variables are local to `is_make_dir'.
7614 my %make_dirs = ();
7615 my $make_dirs_set = 0;
7617 sub is_make_dir
7619     my ($dir) = @_;
7620     if (! $make_dirs_set)
7621     {
7622         foreach my $iter (@configure_input_files)
7623         {
7624             $make_dirs{dirname ($iter)} = 1;
7625         }
7626         # We also want to notice Makefile.in's.
7627         foreach my $iter (@other_input_files)
7628         {
7629             if ($iter =~ /Makefile\.in$/)
7630             {
7631                 $make_dirs{dirname ($iter)} = 1;
7632             }
7633         }
7634         $make_dirs_set = 1;
7635     }
7636     return defined $make_dirs{$dir};
7639 ################################################################
7641 # Find the aux dir.  This should match the algorithm used by
7642 # ./configure. (See the Autoconf documentation for for
7643 # AC_CONFIG_AUX_DIR.)
7644 sub locate_aux_dir ()
7646   if (! $config_aux_dir_set_in_configure_ac)
7647     {
7648       # The default auxiliary directory is the first
7649       # of ., .., or ../.. that contains install-sh.
7650       # Assume . if install-sh doesn't exist yet.
7651       for my $dir (qw (. .. ../..))
7652         {
7653           if (-f "$dir/install-sh")
7654             {
7655               $config_aux_dir = $dir;
7656               last;
7657             }
7658         }
7659       $config_aux_dir = '.' unless $config_aux_dir;
7660     }
7661   # Avoid unsightly '/.'s.
7662   $am_config_aux_dir =
7663     '$(top_srcdir)' . ($config_aux_dir eq '.' ? "" : "/$config_aux_dir");
7664   $am_config_aux_dir =~ s,/*$,,;
7668 # &maybe_push_required_file ($DIR, $FILE, $FULLFILE)
7669 # --------------------------------------------------
7670 # See if we want to push this file onto dist_common.  This function
7671 # encodes the rules for deciding when to do so.
7672 sub maybe_push_required_file
7674   my ($dir, $file, $fullfile) = @_;
7676   if ($dir eq $relative_dir)
7677     {
7678       push_dist_common ($file);
7679       return 1;
7680     }
7681   elsif ($relative_dir eq '.' && ! &is_make_dir ($dir))
7682     {
7683       # If we are doing the topmost directory, and the file is in a
7684       # subdir which does not have a Makefile, then we distribute it
7685       # here.
7687       # If a required file is above the source tree, it is important
7688       # to prefix it with `$(srcdir)' so that no VPATH search is
7689       # performed.  Otherwise problems occur with Make implementations
7690       # that rewrite and simplify rules whose dependencies are found in a
7691       # VPATH location.  Here is an example with OSF1/Tru64 Make.
7692       #
7693       #   % cat Makefile
7694       #   VPATH = sub
7695       #   distdir: ../a
7696       #           echo ../a
7697       #   % ls
7698       #   Makefile a
7699       #   % make
7700       #   echo a
7701       #   a
7702       #
7703       # Dependency `../a' was found in `sub/../a', but this make
7704       # implementation simplified it as `a'.  (Note that the sub/
7705       # directory does not even exist.)
7706       #
7707       # This kind of VPATH rewriting seems hard to cancel.  The
7708       # distdir.am hack against VPATH rewriting works only when no
7709       # simplification is done, i.e., for dependencies which are in
7710       # subdirectories, not in enclosing directories.  Hence, in
7711       # the latter case we use a full path to make sure no VPATH
7712       # search occurs.
7713       $fullfile = '$(srcdir)/' . $fullfile
7714         if $dir =~ m,^\.\.(?:$|/),;
7716       push_dist_common ($fullfile);
7717       return 1;
7718     }
7719   return 0;
7723 # If a file name appears as a key in this hash, then it has already
7724 # been checked for.  This allows us not to report the same error more
7725 # than once.
7726 my %required_file_not_found = ();
7728 # &require_file_internal ($WHERE, $MYSTRICT, $DIRECTORY, @FILES)
7729 # --------------------------------------------------------------
7730 # Verify that the file must exist in $DIRECTORY, or install it.
7731 # $MYSTRICT is the strictness level at which this file becomes required.
7732 sub require_file_internal ($$$@)
7734   my ($where, $mystrict, $dir, @files) = @_;
7736   foreach my $file (@files)
7737     {
7738       my $fullfile = "$dir/$file";
7739       my $found_it = 0;
7740       my $dangling_sym = 0;
7742       if (-l $fullfile && ! -f $fullfile)
7743         {
7744           $dangling_sym = 1;
7745         }
7746       elsif (dir_has_case_matching_file ($dir, $file))
7747         {
7748           $found_it = 1;
7749           maybe_push_required_file ($dir, $file, $fullfile);
7750         }
7752       # `--force-missing' only has an effect if `--add-missing' is
7753       # specified.
7754       if ($found_it && (! $add_missing || ! $force_missing))
7755         {
7756           next;
7757         }
7758       else
7759         {
7760           # If we've already looked for it, we're done.  You might
7761           # wonder why we don't do this before searching for the
7762           # file.  If we do that, then something like
7763           # AC_OUTPUT(subdir/foo foo) will fail to put foo.in into
7764           # DIST_COMMON.
7765           if (! $found_it)
7766             {
7767               next if defined $required_file_not_found{$fullfile};
7768               $required_file_not_found{$fullfile} = 1;
7769             }
7771           if ($strictness >= $mystrict)
7772             {
7773               if ($dangling_sym && $add_missing)
7774                 {
7775                   unlink ($fullfile);
7776                 }
7778               my $trailer = '';
7779               my $trailer2 = '';
7780               my $suppress = 0;
7782               # Only install missing files according to our desired
7783               # strictness level.
7784               my $message = "required file `$fullfile' not found";
7785               if ($add_missing)
7786                 {
7787                   if (-f "$libdir/$file")
7788                     {
7789                       $suppress = 1;
7791                       # Install the missing file.  Symlink if we
7792                       # can, copy if we must.  Note: delete the file
7793                       # first, in case it is a dangling symlink.
7794                       $message = "installing `$fullfile'";
7796                       # The license file should not be volatile.
7797                       if ($file eq "COPYING")
7798                         {
7799                           $message .= " using GNU General Public License v3 file";
7800                           $trailer2 = "\n    Consider adding the COPYING file"
7801                                     . " to the version control system"
7802                                     . "\n    for your code, to avoid questions"
7803                                     . " about which license your project uses.";
7804                         }
7806                       # Windows Perl will hang if we try to delete a
7807                       # file that doesn't exist.
7808                       unlink ($fullfile) if -f $fullfile;
7809                       if ($symlink_exists && ! $copy_missing)
7810                         {
7811                           if (! symlink ("$libdir/$file", $fullfile))
7812                             {
7813                               $suppress = 0;
7814                               $trailer = "; error while making link: $!";
7815                             }
7816                         }
7817                       elsif (system ('cp', "$libdir/$file", $fullfile))
7818                         {
7819                           $suppress = 0;
7820                           $trailer = "\n    error while copying";
7821                         }
7822                       set_dir_cache_file ($dir, $file);
7823                     }
7825                   if (! maybe_push_required_file (dirname ($fullfile),
7826                                                   $file, $fullfile))
7827                     {
7828                       if (! $found_it && ! $automake_will_process_aux_dir)
7829                         {
7830                           # We have added the file but could not push it
7831                           # into DIST_COMMON, probably because this is
7832                           # an auxiliary file and we are not processing
7833                           # the top level Makefile.  Furthermore Automake
7834                           # hasn't been asked to create the Makefile.in
7835                           # that distributes the aux dir files.
7836                           error ($where, 'Please make a full run of automake'
7837                                  . " so $fullfile gets distributed.");
7838                         }
7839                     }
7840                 }
7841               else
7842                 {
7843                   $trailer = "\n  `automake --add-missing' can install `$file'"
7844                     if -f "$libdir/$file";
7845                 }
7847               # If --force-missing was specified, and we have
7848               # actually found the file, then do nothing.
7849               next
7850                 if $found_it && $force_missing;
7852               # If we couldn't install the file, but it is a target in
7853               # the Makefile, don't print anything.  This allows files
7854               # like README, AUTHORS, or THANKS to be generated.
7855               next
7856                 if !$suppress && rule $file;
7858               msg ($suppress ? 'note' : 'error', $where, "$message$trailer$trailer2");
7859             }
7860         }
7861     }
7864 # &require_file ($WHERE, $MYSTRICT, @FILES)
7865 # -----------------------------------------
7866 sub require_file ($$@)
7868     my ($where, $mystrict, @files) = @_;
7869     require_file_internal ($where, $mystrict, $relative_dir, @files);
7872 # &require_file_with_macro ($COND, $MACRO, $MYSTRICT, @FILES)
7873 # -----------------------------------------------------------
7874 sub require_file_with_macro ($$$@)
7876     my ($cond, $macro, $mystrict, @files) = @_;
7877     $macro = rvar ($macro) unless ref $macro;
7878     require_file ($macro->rdef ($cond)->location, $mystrict, @files);
7881 # &require_libsource_with_macro ($COND, $MACRO, $MYSTRICT, @FILES)
7882 # ----------------------------------------------------------------
7883 # Require an AC_LIBSOURCEd file.  If AC_CONFIG_LIBOBJ_DIR was called, it
7884 # must be in that directory.  Otherwise expect it in the current directory.
7885 sub require_libsource_with_macro ($$$@)
7887     my ($cond, $macro, $mystrict, @files) = @_;
7888     $macro = rvar ($macro) unless ref $macro;
7889     if ($config_libobj_dir)
7890       {
7891         require_file_internal ($macro->rdef ($cond)->location, $mystrict,
7892                                $config_libobj_dir, @files);
7893       }
7894     else
7895       {
7896         require_file ($macro->rdef ($cond)->location, $mystrict, @files);
7897       }
7900 # Queue to push require_conf_file requirements to.
7901 my $required_conf_file_queue;
7903 # &queue_required_conf_file ($QUEUE, $KEY, $DIR, $WHERE, $MYSTRICT, @FILES)
7904 # -------------------------------------------------------------------------
7905 sub queue_required_conf_file ($$$$@)
7907     my ($queue, $key, $dir, $where, $mystrict, @files) = @_;
7908     my @serial_loc;
7909     if (ref $where)
7910       {
7911         @serial_loc = (QUEUE_LOCATION, $where->serialize ());
7912       }
7913     else
7914       {
7915         @serial_loc = (QUEUE_STRING, $where);
7916       }
7917     $queue->enqueue ($key, $dir, @serial_loc, $mystrict, 0 + @files, @files);
7920 # &require_queued_conf_file ($QUEUE)
7921 # ----------------------------------
7922 sub require_queued_conf_file ($)
7924     my ($queue) = @_;
7925     my $where;
7926     my $dir = $queue->dequeue ();
7927     my $loc_key = $queue->dequeue ();
7928     if ($loc_key eq QUEUE_LOCATION)
7929       {
7930         $where = Automake::Location::deserialize ($queue);
7931       }
7932     elsif ($loc_key eq QUEUE_STRING)
7933       {
7934         $where = $queue->dequeue ();
7935       }
7936     else
7937       {
7938         prog_error "unexpected key $loc_key";
7939       }
7940     my $mystrict = $queue->dequeue ();
7941     my $nfiles = $queue->dequeue ();
7942     my @files;
7943     push @files, $queue->dequeue ()
7944       foreach (1 .. $nfiles);
7946     # Dequeuing happens outside of per-makefile context, so we have to
7947     # set the variables used by require_file_internal and the functions
7948     # it calls.  Gross!
7949     $relative_dir = $dir;
7950     require_file_internal ($where, $mystrict, $config_aux_dir, @files);
7953 # &require_conf_file ($WHERE, $MYSTRICT, @FILES)
7954 # ----------------------------------------------
7955 # Looks in configuration path, as specified by AC_CONFIG_AUX_DIR;
7956 # worker threads may queue up the action to be serialized by the master.
7958 # FIXME: this seriously relies on the semantics of require_file_internal
7959 # and maybe_push_required_file, in that we exploit the fact that only the
7960 # contents of the last handled output file may be impacted (which in turn
7961 # is dealt with by the master thread).
7962 sub require_conf_file ($$@)
7964     my ($where, $mystrict, @files) = @_;
7965     if (defined $required_conf_file_queue)
7966       {
7967         queue_required_conf_file ($required_conf_file_queue, QUEUE_CONF_FILE,
7968                                   $relative_dir, $where, $mystrict, @files);
7969       }
7970     else
7971       {
7972         require_file_internal ($where, $mystrict, $config_aux_dir, @files);
7973       }
7977 # &require_conf_file_with_macro ($COND, $MACRO, $MYSTRICT, @FILES)
7978 # ----------------------------------------------------------------
7979 sub require_conf_file_with_macro ($$$@)
7981     my ($cond, $macro, $mystrict, @files) = @_;
7982     require_conf_file (rvar ($macro)->rdef ($cond)->location,
7983                        $mystrict, @files);
7986 ################################################################
7988 # &require_build_directory ($DIRECTORY)
7989 # ------------------------------------
7990 # Emit rules to create $DIRECTORY if needed, and return
7991 # the file that any target requiring this directory should be made
7992 # dependent upon.
7993 # We don't want to emit the rule twice, and want to reuse it
7994 # for directories with equivalent names (e.g., `foo/bar' and `./foo//bar').
7995 sub require_build_directory ($)
7997   my $directory = shift;
7999   return $directory_map{$directory} if exists $directory_map{$directory};
8001   my $cdir = File::Spec->canonpath ($directory);
8003   if (exists $directory_map{$cdir})
8004     {
8005       my $stamp = $directory_map{$cdir};
8006       $directory_map{$directory} = $stamp;
8007       return $stamp;
8008     }
8010   my $dirstamp = "$cdir/\$(am__dirstamp)";
8012   $directory_map{$directory} = $dirstamp;
8013   $directory_map{$cdir} = $dirstamp;
8015   # Set a variable for the dirstamp basename.
8016   define_pretty_variable ('am__dirstamp', TRUE, INTERNAL,
8017                           '$(am__leading_dot)dirstamp');
8019   # Directory must be removed by `make distclean'.
8020   $clean_files{$dirstamp} = DIST_CLEAN;
8022   $output_rules .= ("$dirstamp:\n"
8023                     . "\t\@\$(MKDIR_P) $directory\n"
8024                     . "\t\@: > $dirstamp\n");
8026   return $dirstamp;
8029 # &require_build_directory_maybe ($FILE)
8030 # --------------------------------------
8031 # If $FILE lies in a subdirectory, emit a rule to create this
8032 # directory and return the file that $FILE should be made
8033 # dependent upon.  Otherwise, just return the empty string.
8034 sub require_build_directory_maybe ($)
8036     my $file = shift;
8037     my $directory = dirname ($file);
8039     if ($directory ne '.')
8040     {
8041         return require_build_directory ($directory);
8042     }
8043     else
8044     {
8045         return '';
8046     }
8049 ################################################################
8051 # Push a list of files onto dist_common.
8052 sub push_dist_common
8054   prog_error "push_dist_common run after handle_dist"
8055     if $handle_dist_run;
8056   Automake::Variable::define ('DIST_COMMON', VAR_AUTOMAKE, '+', TRUE, "@_",
8057                               '', INTERNAL, VAR_PRETTY);
8061 ################################################################
8063 # generate_makefile ($MAKEFILE_AM, $MAKEFILE_IN)
8064 # ----------------------------------------------
8065 # Generate a Makefile.in given the name of the corresponding Makefile and
8066 # the name of the file output by config.status.
8067 sub generate_makefile ($$)
8069   my ($makefile_am, $makefile_in) = @_;
8071   # Reset all the Makefile.am related variables.
8072   initialize_per_input;
8074   # AUTOMAKE_OPTIONS can contains -W flags to disable or enable
8075   # warnings for this file.  So hold any warning issued before
8076   # we have processed AUTOMAKE_OPTIONS.
8077   buffer_messages ('warning');
8079   # Name of input file ("Makefile.am") and output file
8080   # ("Makefile.in").  These have no directory components.
8081   $am_file_name = basename ($makefile_am);
8082   $in_file_name = basename ($makefile_in);
8084   # $OUTPUT is encoded.  If it contains a ":" then the first element
8085   # is the real output file, and all remaining elements are input
8086   # files.  We don't scan or otherwise deal with these input files,
8087   # other than to mark them as dependencies.  See
8088   # &scan_autoconf_files for details.
8089   my ($makefile, @inputs) = split (/:/, $output_files{$makefile_in});
8091   $relative_dir = dirname ($makefile);
8092   $am_relative_dir = dirname ($makefile_am);
8093   $topsrcdir = backname ($relative_dir);
8095   read_main_am_file ($makefile_am);
8096   if (handle_options)
8097     {
8098       # Process buffered warnings.
8099       flush_messages;
8100       # Fatal error.  Just return, so we can continue with next file.
8101       return;
8102     }
8103   # Process buffered warnings.
8104   flush_messages;
8106   # There are a few install-related variables that you should not define.
8107   foreach my $var ('PRE_INSTALL', 'POST_INSTALL', 'NORMAL_INSTALL')
8108     {
8109       my $v = var $var;
8110       if ($v)
8111         {
8112           my $def = $v->def (TRUE);
8113           prog_error "$var not defined in condition TRUE"
8114             unless $def;
8115           reject_var $var, "`$var' should not be defined"
8116             if $def->owner != VAR_AUTOMAKE;
8117         }
8118     }
8120   # Catch some obsolete variables.
8121   msg_var ('obsolete', 'INCLUDES',
8122            "`INCLUDES' is the old name for `AM_CPPFLAGS' (or `*_CPPFLAGS')")
8123     if var ('INCLUDES');
8125   # Must do this after reading .am file.
8126   define_variable ('subdir', $relative_dir, INTERNAL);
8128   # If DIST_SUBDIRS is defined, make sure SUBDIRS is, so that
8129   # recursive rules are enabled.
8130   define_pretty_variable ('SUBDIRS', TRUE, INTERNAL, '')
8131     if var 'DIST_SUBDIRS' && ! var 'SUBDIRS';
8133   # Check first, because we might modify some state.
8134   check_cygnus;
8135   check_gnu_standards;
8136   check_gnits_standards;
8138   handle_configure ($makefile_am, $makefile_in, $makefile, @inputs);
8139   handle_gettext;
8140   handle_libraries;
8141   handle_ltlibraries;
8142   handle_programs;
8143   handle_scripts;
8145   # These must be run after all the sources are scanned.  They
8146   # use variables defined by &handle_libraries, &handle_ltlibraries,
8147   # or &handle_programs.
8148   handle_compile;
8149   handle_languages;
8150   handle_libtool;
8152   # Variables used by distdir.am and tags.am.
8153   define_pretty_variable ('SOURCES', TRUE, INTERNAL, @sources);
8154   if (! option 'no-dist')
8155     {
8156       define_pretty_variable ('DIST_SOURCES', TRUE, INTERNAL, @dist_sources);
8157     }
8159   handle_multilib;
8160   handle_texinfo;
8161   handle_emacs_lisp;
8162   handle_python;
8163   handle_java;
8164   handle_man_pages;
8165   handle_data;
8166   handle_headers;
8167   handle_subdirs;
8168   handle_tags;
8169   handle_minor_options;
8170   # Must come after handle_programs so that %known_programs is up-to-date.
8171   handle_tests;
8173   # This must come after most other rules.
8174   handle_dist;
8176   handle_footer;
8177   do_check_merge_target;
8178   handle_all ($makefile);
8180   # FIXME: Gross!
8181   if (var ('lib_LTLIBRARIES') && var ('bin_PROGRAMS'))
8182     {
8183       $output_rules .= "install-binPROGRAMS: install-libLTLIBRARIES\n\n";
8184     }
8185   if (var ('nobase_lib_LTLIBRARIES') && var ('bin_PROGRAMS'))
8186     {
8187       $output_rules .= "install-binPROGRAMS: install-nobase_libLTLIBRARIES\n\n";
8188     }
8190   handle_install;
8191   handle_clean ($makefile);
8192   handle_factored_dependencies;
8194   # Comes last, because all the above procedures may have
8195   # defined or overridden variables.
8196   $output_vars .= output_variables;
8198   check_typos;
8200   my ($out_file) = $output_directory . '/' . $makefile_in;
8202   if ($exit_code != 0)
8203     {
8204       verb "not writing $out_file because of earlier errors";
8205       return;
8206     }
8208   if (! -d ($output_directory . '/' . $am_relative_dir))
8209     {
8210       mkdir ($output_directory . '/' . $am_relative_dir, 0755);
8211     }
8213   # We make sure that `all:' is the first target.
8214   my $output =
8215     "$output_vars$output_all$output_header$output_rules$output_trailer";
8217   # Decide whether we must update the output file or not.
8218   # We have to update in the following situations.
8219   #  * $force_generation is set.
8220   #  * any of the output dependencies is younger than the output
8221   #  * the contents of the output is different (this can happen
8222   #    if the project has been populated with a file listed in
8223   #    @common_files since the last run).
8224   # Output's dependencies are split in two sets:
8225   #  * dependencies which are also configure dependencies
8226   #    These do not change between each Makefile.am
8227   #  * other dependencies, specific to the Makefile.am being processed
8228   #    (such as the Makefile.am itself, or any Makefile fragment
8229   #    it includes).
8230   my $timestamp = mtime $out_file;
8231   if (! $force_generation
8232       && $configure_deps_greatest_timestamp < $timestamp
8233       && $output_deps_greatest_timestamp < $timestamp
8234       && $output eq contents ($out_file))
8235     {
8236       verb "$out_file unchanged";
8237       # No need to update.
8238       return;
8239     }
8241   if (-e $out_file)
8242     {
8243       unlink ($out_file)
8244         or fatal "cannot remove $out_file: $!\n";
8245     }
8247   my $gm_file = new Automake::XFile "> $out_file";
8248   verb "creating $out_file";
8249   print $gm_file $output;
8252 ################################################################
8257 ################################################################
8259 # Print usage information.
8260 sub usage ()
8262     print "Usage: $0 [OPTION] ... [Makefile]...
8264 Generate Makefile.in for configure from Makefile.am.
8266 Operation modes:
8267       --help               print this help, then exit
8268       --version            print version number, then exit
8269   -v, --verbose            verbosely list files processed
8270       --no-force           only update Makefile.in's that are out of date
8271   -W, --warnings=CATEGORY  report the warnings falling in CATEGORY
8273 Dependency tracking:
8274   -i, --ignore-deps      disable dependency tracking code
8275       --include-deps     enable dependency tracking code
8277 Flavors:
8278       --cygnus           assume program is part of Cygnus-style tree
8279       --foreign          set strictness to foreign
8280       --gnits            set strictness to gnits
8281       --gnu              set strictness to gnu
8283 Library files:
8284   -a, --add-missing      add missing standard files to package
8285       --libdir=DIR       directory storing library files
8286   -c, --copy             with -a, copy missing files (default is symlink)
8287   -f, --force-missing    force update of standard files
8290     Automake::ChannelDefs::usage;
8292     my ($last, @lcomm);
8293     $last = '';
8294     foreach my $iter (sort ((@common_files, @common_sometimes)))
8295     {
8296         push (@lcomm, $iter) unless $iter eq $last;
8297         $last = $iter;
8298     }
8300     my @four;
8301     print "\nFiles which are automatically distributed, if found:\n";
8302     format USAGE_FORMAT =
8303   @<<<<<<<<<<<<<<<<   @<<<<<<<<<<<<<<<<   @<<<<<<<<<<<<<<<<   @<<<<<<<<<<<<<<<<
8304   $four[0],           $four[1],           $four[2],           $four[3]
8306     $~ = "USAGE_FORMAT";
8308     my $cols = 4;
8309     my $rows = int(@lcomm / $cols);
8310     my $rest = @lcomm % $cols;
8312     if ($rest)
8313     {
8314         $rows++;
8315     }
8316     else
8317     {
8318         $rest = $cols;
8319     }
8321     for (my $y = 0; $y < $rows; $y++)
8322     {
8323         @four = ("", "", "", "");
8324         for (my $x = 0; $x < $cols; $x++)
8325         {
8326             last if $y + 1 == $rows && $x == $rest;
8328             my $idx = (($x > $rest)
8329                        ?  ($rows * $rest + ($rows - 1) * ($x - $rest))
8330                        : ($rows * $x));
8332             $idx += $y;
8333             $four[$x] = $lcomm[$idx];
8334         }
8335         write;
8336     }
8338     print "\nReport bugs to <bug-automake\@gnu.org>.\n";
8340     # --help always returns 0 per GNU standards.
8341     exit 0;
8345 # &version ()
8346 # -----------
8347 # Print version information
8348 sub version ()
8350   print <<EOF;
8351 automake (GNU $PACKAGE) $VERSION
8352 Copyright (C) 2009 Free Software Foundation, Inc.
8353 License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
8354 This is free software: you are free to change and redistribute it.
8355 There is NO WARRANTY, to the extent permitted by law.
8357 Written by Tom Tromey <tromey\@redhat.com>
8358        and Alexandre Duret-Lutz <adl\@gnu.org>.
8360   # --version always returns 0 per GNU standards.
8361   exit 0;
8364 ################################################################
8366 # Parse command line.
8367 sub parse_arguments ()
8369   # Start off as gnu.
8370   set_strictness ('gnu');
8372   my $cli_where = new Automake::Location;
8373   my %cli_options =
8374     (
8375      'libdir=s' => \$libdir,
8376      'gnu'              => sub { set_strictness ('gnu'); },
8377      'gnits'            => sub { set_strictness ('gnits'); },
8378      'cygnus'           => sub { set_global_option ('cygnus', $cli_where); },
8379      'foreign'          => sub { set_strictness ('foreign'); },
8380      'include-deps'     => sub { unset_global_option ('no-dependencies'); },
8381      'i|ignore-deps'    => sub { set_global_option ('no-dependencies',
8382                                                     $cli_where); },
8383      'no-force' => sub { $force_generation = 0; },
8384      'f|force-missing'  => \$force_missing,
8385      'o|output-dir=s'   => \$output_directory,
8386      'a|add-missing'    => \$add_missing,
8387      'c|copy'           => \$copy_missing,
8388      'v|verbose'        => sub { setup_channel 'verb', silent => 0; },
8389      'W|warnings=s'     => \&parse_warnings,
8390      # These long options (--Werror and --Wno-error) for backward
8391      # compatibility.  Use -Werror and -Wno-error today.
8392      'Werror'           => sub { parse_warnings 'W', 'error'; },
8393      'Wno-error'        => sub { parse_warnings 'W', 'no-error'; },
8394      );
8395   use Getopt::Long;
8396   Getopt::Long::config ("bundling", "pass_through");
8398   # See if --version or --help is used.  We want to process these before
8399   # anything else because the GNU Coding Standards require us to
8400   # `exit 0' after processing these options, and we can't guarantee this
8401   # if we treat other options first.  (Handling other options first
8402   # could produce error diagnostics, and in this condition it is
8403   # confusing if Automake does `exit 0'.)
8404   my %cli_options_1st_pass =
8405     (
8406      'version' => \&version,
8407      'help'    => \&usage,
8408      # Recognize all other options (and their arguments) but do nothing.
8409      map { $_ => sub {} } (keys %cli_options)
8410      );
8411   my @ARGV_backup = @ARGV;
8412   Getopt::Long::GetOptions %cli_options_1st_pass
8413     or exit 1;
8414   @ARGV = @ARGV_backup;
8416   # Now *really* process the options.  This time we know that --help
8417   # and --version are not present, but we specify them nonetheless so
8418   # that ambiguous abbreviation are diagnosed.
8419   Getopt::Long::GetOptions %cli_options, 'version' => sub {}, 'help' => sub {}
8420     or exit 1;
8422   if (defined $output_directory)
8423     {
8424       msg 'obsolete', "`--output-dir' is deprecated\n";
8425     }
8426   else
8427     {
8428       # In the next release we'll remove this entirely.
8429       $output_directory = '.';
8430     }
8432   return unless @ARGV;
8434   if ($ARGV[0] =~ /^-./)
8435     {
8436       my %argopts;
8437       for my $k (keys %cli_options)
8438         {
8439           if ($k =~ /(.*)=s$/)
8440             {
8441               map { $argopts{(length ($_) == 1)
8442                              ? "-$_" : "--$_" } = 1; } (split (/\|/, $1));
8443             }
8444         }
8445       if ($ARGV[0] eq '--')
8446         {
8447           shift @ARGV;
8448         }
8449       elsif (exists $argopts{$ARGV[0]})
8450         {
8451           fatal ("option `$ARGV[0]' requires an argument\n"
8452                  . "Try `$0 --help' for more information.");
8453         }
8454       else
8455         {
8456           fatal ("unrecognized option `$ARGV[0]'.\n"
8457                  . "Try `$0 --help' for more information.");
8458         }
8459     }
8461   my $errspec = 0;
8462   foreach my $arg (@ARGV)
8463     {
8464       fatal ("empty argument\nTry `$0 --help' for more information.")
8465         if ($arg eq '');
8467       # Handle $local:$input syntax.
8468       my ($local, @rest) = split (/:/, $arg);
8469       @rest = ("$local.in",) unless @rest;
8470       my $input = locate_am @rest;
8471       if ($input)
8472         {
8473           push @input_files, $input;
8474           $output_files{$input} = join (':', ($local, @rest));
8475         }
8476       else
8477         {
8478           error "no Automake input file found for `$arg'";
8479           $errspec = 1;
8480         }
8481     }
8482   fatal "no input file found among supplied arguments"
8483     if $errspec && ! @input_files;
8487 # handle_makefile ($MAKEFILE_IN)
8488 # ------------------------------
8489 # Deal with $MAKEFILE_IN.
8490 sub handle_makefile ($)
8492   my ($file) =  @_;
8493   ($am_file = $file) =~ s/\.in$//;
8494   if (! -f ($am_file . '.am'))
8495     {
8496       error "`$am_file.am' does not exist";
8497     }
8498   else
8499     {
8500       # Any warning setting now local to this Makefile.am.
8501       dup_channel_setup;
8503       generate_makefile ($am_file . '.am', $file);
8505       # Back out any warning setting.
8506       drop_channel_setup;
8507     }
8510 # handle_makefiles_serial ()
8511 # --------------------------
8512 # Deal with all makefiles, without threads.
8513 sub handle_makefiles_serial ()
8515   foreach my $file (@input_files)
8516     {
8517       handle_makefile ($file);
8518     }
8521 # get_number_of_threads ()
8522 # ------------------------
8523 # Logic for deciding how many worker threads to use.
8524 sub get_number_of_threads
8526   my $nthreads = $ENV{'AUTOMAKE_JOBS'} || 0;
8528   $nthreads = 0
8529     unless $nthreads =~ /^[0-9]+$/;
8531   # It doesn't make sense to use more threads than makefiles,
8532   my $max_threads = @input_files;
8534   # but a single worker thread is helpful for exposing bugs.
8535   if ($automake_will_process_aux_dir && $max_threads > 1)
8536     {
8537       $max_threads--;
8538     }
8539   if ($nthreads > $max_threads)
8540     {
8541       $nthreads = $max_threads;
8542     }
8543   return $nthreads;
8546 # handle_makefiles_threaded ($NTHREADS)
8547 # -------------------------------------
8548 # Deal with all makefiles, using threads.  The general strategy is to
8549 # spawn NTHREADS worker threads, dispatch makefiles to them, and let the
8550 # worker threads push back everything that needs serialization:
8551 # * warning and (normal) error messages, for stable stderr output
8552 #   order and content (avoiding duplicates, for example),
8553 # * races when installing aux files (and respective messages),
8554 # * races when collecting aux files for distribution.
8556 # The latter requires that the makefile that deals with the aux dir
8557 # files be handled last, done by the master thread.
8558 sub handle_makefiles_threaded ($)
8560   my ($nthreads) = @_;
8562   my @queued_input_files = @input_files;
8563   my $last_input_file = undef;
8564   if ($automake_will_process_aux_dir)
8565     {
8566       $last_input_file = pop @queued_input_files;
8567     }
8569   # The file queue distributes all makefiles, the message queues
8570   # collect all serializations needed for respective files.
8571   my $file_queue = Thread::Queue->new;
8572   my %msg_queues;
8573   foreach my $file (@queued_input_files)
8574     {
8575       $msg_queues{$file} = Thread::Queue->new;
8576     }
8578   verb "spawning $nthreads worker threads";
8579   my @threads = (1 .. $nthreads);
8580   foreach my $t (@threads)
8581     {
8582       $t = threads->new (sub
8583         {
8584           while (my $file = $file_queue->dequeue)
8585             {
8586               verb "handling $file";
8587               my $queue = $msg_queues{$file};
8588               setup_channel_queue ($queue, QUEUE_MESSAGE);
8589               $required_conf_file_queue = $queue;
8590               handle_makefile ($file);
8591               $queue->enqueue (undef);
8592               setup_channel_queue (undef, undef);
8593               $required_conf_file_queue = undef;
8594             }
8595           return $exit_code;
8596         });
8597     }
8599   # Queue all normal makefiles.
8600   verb "queuing " . @queued_input_files . " input files";
8601   $file_queue->enqueue (@queued_input_files, (undef) x @threads);
8603   # Collect and process serializations.
8604   foreach my $file (@queued_input_files)
8605     {
8606       verb "dequeuing messages for " . $file;
8607       reset_local_duplicates ();
8608       my $queue = $msg_queues{$file};
8609       while (my $key = $queue->dequeue)
8610         {
8611           if ($key eq QUEUE_MESSAGE)
8612             {
8613               pop_channel_queue ($queue);
8614             }
8615           elsif ($key eq QUEUE_CONF_FILE)
8616             {
8617               require_queued_conf_file ($queue);
8618             }
8619           else
8620             {
8621               prog_error "unexpected key $key";
8622             }
8623         }
8624     }
8626   foreach my $t (@threads)
8627     {
8628       my @exit_thread = $t->join;
8629       $exit_code = $exit_thread[0]
8630         if ($exit_thread[0] > $exit_code);
8631     }
8633   # The master processes the last file.
8634   if ($automake_will_process_aux_dir)
8635     {
8636       verb "processing last input file";
8637       handle_makefile ($last_input_file);
8638     }
8641 ################################################################
8643 # Parse the WARNINGS environment variable.
8644 parse_WARNINGS;
8646 # Parse command line.
8647 parse_arguments;
8649 $configure_ac = require_configure_ac;
8651 # Do configure.ac scan only once.
8652 scan_autoconf_files;
8654 if (! @input_files)
8655   {
8656     my $msg = '';
8657     $msg = "\nDid you forget AC_CONFIG_FILES([Makefile]) in $configure_ac?"
8658       if -f 'Makefile.am';
8659     fatal ("no `Makefile.am' found for any configure output$msg");
8660   }
8662 my $nthreads = get_number_of_threads ();
8664 if ($perl_threads && $nthreads >= 1)
8665   {
8666     handle_makefiles_threaded ($nthreads);
8667   }
8668 else
8669   {
8670     handle_makefiles_serial ();
8671   }
8673 exit $exit_code;
8676 ### Setup "GNU" style for perl-mode and cperl-mode.
8677 ## Local Variables:
8678 ## perl-indent-level: 2
8679 ## perl-continued-statement-offset: 2
8680 ## perl-continued-brace-offset: 0
8681 ## perl-brace-offset: 0
8682 ## perl-brace-imaginary-offset: 0
8683 ## perl-label-offset: -2
8684 ## cperl-indent-level: 2
8685 ## cperl-brace-offset: 0
8686 ## cperl-continued-brace-offset: 0
8687 ## cperl-label-offset: -2
8688 ## cperl-extra-newline-before-brace: t
8689 ## cperl-merge-trailing-else: nil
8690 ## cperl-continued-statement-offset: 2
8691 ## End: