Merge branch 'mh-vala-support' into next
[automake.git] / automake.in
blob4656032b58f7862d1a1cdb4bce1e52fac77a3e57
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 a 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       # Strip any $(EXEEXT) suffix the user might have added, or this
2619       # will confuse &handle_source_transform and &check_canonical_spelling.
2620       # We'll add $(EXEEXT) back later anyway.
2621       $one_file =~ s/\$\(EXEEXT\)$//;
2623       $known_programs{$one_file} = $where;
2625       # Canonicalize names and check for misspellings.
2626       my $xname = &check_canonical_spelling ($one_file, '_LDADD', '_LDFLAGS',
2627                                              '_SOURCES', '_OBJECTS',
2628                                              '_DEPENDENCIES');
2630       $where->push_context ("while processing program `$one_file'");
2631       $where->set (INTERNAL->get);
2633       my $linker = &handle_source_transform ($xname, $one_file, $obj, $where,
2634                                              NONLIBTOOL => 1, LIBTOOL => 0);
2636       if (var ($xname . "_LDADD"))
2637         {
2638           $seen_libobjs = &handle_lib_objects ($xname, $xname . '_LDADD');
2639         }
2640       else
2641         {
2642           # User didn't define prog_LDADD override.  So do it.
2643           &define_variable ($xname . '_LDADD', '$(LDADD)', $where);
2645           # This does a bit too much work.  But we need it to
2646           # generate _DEPENDENCIES when appropriate.
2647           if (var ('LDADD'))
2648             {
2649               $seen_libobjs = &handle_lib_objects ($xname, 'LDADD');
2650             }
2651         }
2653       reject_var ($xname . '_LIBADD',
2654                   "use `${xname}_LDADD', not `${xname}_LIBADD'");
2656       set_seen ($xname . '_DEPENDENCIES');
2657       set_seen ($xname . '_LDFLAGS');
2659       # Determine program to use for link.
2660       my($xlink, $vlink) = &define_per_target_linker_variable ($linker, $xname);
2661       $vlink = verbose_flag ($vlink || 'GEN');
2663       # If the resulting program lies into a subdirectory,
2664       # make sure this directory will exist.
2665       my $dirstamp = require_build_directory_maybe ($one_file);
2667       $libtool_clean_directories{dirname ($one_file)} = 1;
2669       $output_rules .= &file_contents ('program',
2670                                        $where,
2671                                        PROGRAM  => $one_file,
2672                                        XPROGRAM => $xname,
2673                                        XLINK    => $xlink,
2674                                        VERBOSE  => $vlink,
2675                                        DIRSTAMP => $dirstamp,
2676                                        EXEEXT   => '$(EXEEXT)');
2678       if ($seen_libobjs || $seen_global_libobjs)
2679         {
2680           if (var ($xname . '_LDADD'))
2681             {
2682               &check_libobjs_sources ($xname, $xname . '_LDADD');
2683             }
2684           elsif (var ('LDADD'))
2685             {
2686               &check_libobjs_sources ($xname, 'LDADD');
2687             }
2688         }
2689     }
2693 # handle_libraries ()
2694 # -------------------
2695 # Handle libraries.
2696 sub handle_libraries
2698   my @liblist = &am_install_var ('libs', 'LIBRARIES',
2699                                  'lib', 'pkglib', 'noinst', 'check');
2700   return if ! @liblist;
2702   my @prefix = am_primary_prefixes ('LIBRARIES', 0, 'lib', 'pkglib',
2703                                     'noinst', 'check');
2705   if (@prefix)
2706     {
2707       my $var = rvar ($prefix[0] . '_LIBRARIES');
2708       $var->requires_variables ('library used', 'RANLIB');
2709     }
2711   &define_variable ('AR', 'ar', INTERNAL);
2712   &define_variable ('ARFLAGS', 'cru', INTERNAL);
2713   &define_verbose_tagvar ('AR');
2715   foreach my $pair (@liblist)
2716     {
2717       my ($where, $onelib) = @$pair;
2719       my $seen_libobjs = 0;
2720       # Check that the library fits the standard naming convention.
2721       my $bn = basename ($onelib);
2722       if ($bn !~ /^lib.*\.a$/)
2723         {
2724           $bn =~ s/^(?:lib)?(.*?)(?:\.[^.]*)?$/lib$1.a/;
2725           my $suggestion = dirname ($onelib) . "/$bn";
2726           $suggestion =~ s|^\./||g;
2727           msg ('error-gnu/warn', $where,
2728                "`$onelib' is not a standard library name\n"
2729                . "did you mean `$suggestion'?")
2730         }
2732       ($known_libraries{$onelib} = $bn) =~ s/\.a$//;
2734       $where->push_context ("while processing library `$onelib'");
2735       $where->set (INTERNAL->get);
2737       my $obj = get_object_extension '.$(OBJEXT)';
2739       # Canonicalize names and check for misspellings.
2740       my $xlib = &check_canonical_spelling ($onelib, '_LIBADD', '_SOURCES',
2741                                             '_OBJECTS', '_DEPENDENCIES',
2742                                             '_AR');
2744       if (! var ($xlib . '_AR'))
2745         {
2746           &define_variable ($xlib . '_AR', '$(AR) $(ARFLAGS)', $where);
2747         }
2749       # Generate support for conditional object inclusion in
2750       # libraries.
2751       if (var ($xlib . '_LIBADD'))
2752         {
2753           if (&handle_lib_objects ($xlib, $xlib . '_LIBADD'))
2754             {
2755               $seen_libobjs = 1;
2756             }
2757         }
2758       else
2759         {
2760           &define_variable ($xlib . "_LIBADD", '', $where);
2761         }
2763       reject_var ($xlib . '_LDADD',
2764                   "use `${xlib}_LIBADD', not `${xlib}_LDADD'");
2766       # Make sure we at look at this.
2767       set_seen ($xlib . '_DEPENDENCIES');
2769       &handle_source_transform ($xlib, $onelib, $obj, $where,
2770                                 NONLIBTOOL => 1, LIBTOOL => 0);
2772       # If the resulting library lies into a subdirectory,
2773       # make sure this directory will exist.
2774       my $dirstamp = require_build_directory_maybe ($onelib);
2775       my $verbose = verbose_flag ('AR');
2776       my $silent = silent_flag ();
2778       $output_rules .= &file_contents ('library',
2779                                        $where,
2780                                        VERBOSE  => $verbose,
2781                                        SILENT   => $silent,
2782                                        LIBRARY  => $onelib,
2783                                        XLIBRARY => $xlib,
2784                                        DIRSTAMP => $dirstamp);
2786       if ($seen_libobjs)
2787         {
2788           if (var ($xlib . '_LIBADD'))
2789             {
2790               &check_libobjs_sources ($xlib, $xlib . '_LIBADD');
2791             }
2792         }
2793     }
2797 # handle_ltlibraries ()
2798 # ---------------------
2799 # Handle shared libraries.
2800 sub handle_ltlibraries
2802   my @liblist = &am_install_var ('ltlib', 'LTLIBRARIES',
2803                                  'noinst', 'lib', 'pkglib', 'check');
2804   return if ! @liblist;
2806   my @prefix = am_primary_prefixes ('LTLIBRARIES', 0, 'lib', 'pkglib',
2807                                     'noinst', 'check');
2809   if (@prefix)
2810     {
2811       my $var = rvar ($prefix[0] . '_LTLIBRARIES');
2812       $var->requires_variables ('Libtool library used', 'LIBTOOL');
2813     }
2815   my %instdirs = ();
2816   my %instsubdirs = ();
2817   my %instconds = ();
2818   my %liblocations = ();        # Location (in Makefile.am) of each library.
2820   foreach my $key (@prefix)
2821     {
2822       # Get the installation directory of each library.
2823       my $dir = $key;
2824       my $strip_subdir = 1;
2825       if ($dir =~ /^nobase_/)
2826         {
2827           $dir =~ s/^nobase_//;
2828           $strip_subdir = 0;
2829         }
2830       my $var = rvar ($key . '_LTLIBRARIES');
2832       # We reject libraries which are installed in several places
2833       # in the same condition, because we can only specify one
2834       # `-rpath' option.
2835       $var->traverse_recursively
2836         (sub
2837          {
2838            my ($var, $val, $cond, $full_cond) = @_;
2839            my $hcond = $full_cond->human;
2840            my $where = $var->rdef ($cond)->location;
2841            my $ldir = '';
2842            $ldir = '/' . dirname ($val)
2843              if (!$strip_subdir);
2844            # A library cannot be installed in different directory
2845            # in overlapping conditions.
2846            if (exists $instconds{$val})
2847              {
2848                my ($msg, $acond) =
2849                  $instconds{$val}->ambiguous_p ($val, $full_cond);
2851                if ($msg)
2852                  {
2853                    error ($where, $msg, partial => 1);
2854                    my $dirtxt = "installed " . ($strip_subdir ? "in" : "below") . " `$dir'";
2855                    $dirtxt = "built for `$dir'"
2856                      if $dir eq 'EXTRA' || $dir eq 'noinst' || $dir eq 'check';
2857                    my $dircond =
2858                      $full_cond->true ? "" : " in condition $hcond";
2860                    error ($where, "`$val' should be $dirtxt$dircond ...",
2861                           partial => 1);
2863                    my $hacond = $acond->human;
2864                    my $adir = $instdirs{$val}{$acond};
2865                    my $adirtxt = "installed in `$adir'";
2866                    $adirtxt = "built for `$adir'"
2867                      if ($adir eq 'EXTRA' || $adir eq 'noinst'
2868                          || $adir eq 'check');
2869                    my $adircond = $acond->true ? "" : " in condition $hacond";
2871                    my $onlyone = ($dir ne $adir) ?
2872                      ("\nLibtool libraries can be built for only one "
2873                       . "destination.") : "";
2875                    error ($liblocations{$val}{$acond},
2876                           "... and should also be $adirtxt$adircond.$onlyone");
2877                    return;
2878                  }
2879              }
2880            else
2881              {
2882                $instconds{$val} = new Automake::DisjConditions;
2883              }
2884            $instdirs{$val}{$full_cond} = $dir;
2885            $instsubdirs{$val}{$full_cond} = $ldir;
2886            $liblocations{$val}{$full_cond} = $where;
2887            $instconds{$val} = $instconds{$val}->merge ($full_cond);
2888          },
2889          sub
2890          {
2891            return ();
2892          },
2893          skip_ac_subst => 1);
2894     }
2896   foreach my $pair (@liblist)
2897     {
2898       my ($where, $onelib) = @$pair;
2900       my $seen_libobjs = 0;
2901       my $obj = get_object_extension '.lo';
2903       # Canonicalize names and check for misspellings.
2904       my $xlib = &check_canonical_spelling ($onelib, '_LIBADD', '_LDFLAGS',
2905                                             '_SOURCES', '_OBJECTS',
2906                                             '_DEPENDENCIES');
2908       # Check that the library fits the standard naming convention.
2909       my $libname_rx = '^lib.*\.la';
2910       my $ldvar = var ("${xlib}_LDFLAGS") || var ('AM_LDFLAGS');
2911       my $ldvar2 = var ('LDFLAGS');
2912       if (($ldvar && grep (/-module/, $ldvar->value_as_list_recursive))
2913           || ($ldvar2 && grep (/-module/, $ldvar2->value_as_list_recursive)))
2914         {
2915           # Relax name checking for libtool modules.
2916           $libname_rx = '\.la';
2917         }
2919       my $bn = basename ($onelib);
2920       if ($bn !~ /$libname_rx$/)
2921         {
2922           my $type = 'library';
2923           if ($libname_rx eq '\.la')
2924             {
2925               $bn =~ s/^(lib|)(.*?)(?:\.[^.]*)?$/$1$2.la/;
2926               $type = 'module';
2927             }
2928           else
2929             {
2930               $bn =~ s/^(?:lib)?(.*?)(?:\.[^.]*)?$/lib$1.la/;
2931             }
2932           my $suggestion = dirname ($onelib) . "/$bn";
2933           $suggestion =~ s|^\./||g;
2934           msg ('error-gnu/warn', $where,
2935                "`$onelib' is not a standard libtool $type name\n"
2936                . "did you mean `$suggestion'?")
2937         }
2939       ($known_libraries{$onelib} = $bn) =~ s/\.la$//;
2941       $where->push_context ("while processing Libtool library `$onelib'");
2942       $where->set (INTERNAL->get);
2944       # Make sure we look at these.
2945       set_seen ($xlib . '_LDFLAGS');
2946       set_seen ($xlib . '_DEPENDENCIES');
2948       # Generate support for conditional object inclusion in
2949       # libraries.
2950       if (var ($xlib . '_LIBADD'))
2951         {
2952           if (&handle_lib_objects ($xlib, $xlib . '_LIBADD'))
2953             {
2954               $seen_libobjs = 1;
2955             }
2956         }
2957       else
2958         {
2959           &define_variable ($xlib . "_LIBADD", '', $where);
2960         }
2962       reject_var ("${xlib}_LDADD",
2963                   "use `${xlib}_LIBADD', not `${xlib}_LDADD'");
2966       my $linker = &handle_source_transform ($xlib, $onelib, $obj, $where,
2967                                              NONLIBTOOL => 0, LIBTOOL => 1);
2969       # Determine program to use for link.
2970       my($xlink, $vlink) = &define_per_target_linker_variable ($linker, $xlib);
2971       $vlink = verbose_flag ($vlink || 'GEN');
2973       my $rpathvar = "am_${xlib}_rpath";
2974       my $rpath = "\$($rpathvar)";
2975       foreach my $rcond ($instconds{$onelib}->conds)
2976         {
2977           my $val;
2978           if ($instdirs{$onelib}{$rcond} eq 'EXTRA'
2979               || $instdirs{$onelib}{$rcond} eq 'noinst'
2980               || $instdirs{$onelib}{$rcond} eq 'check')
2981             {
2982               # It's an EXTRA_ library, so we can't specify -rpath,
2983               # because we don't know where the library will end up.
2984               # The user probably knows, but generally speaking automake
2985               # doesn't -- and in fact configure could decide
2986               # dynamically between two different locations.
2987               $val = '';
2988             }
2989           else
2990             {
2991               $val = ('-rpath $(' . $instdirs{$onelib}{$rcond} . 'dir)');
2992               $val .= $instsubdirs{$onelib}{$rcond}
2993                 if defined $instsubdirs{$onelib}{$rcond};
2994             }
2995           if ($rcond->true)
2996             {
2997               # If $rcond is true there is only one condition and
2998               # there is no point defining an helper variable.
2999               $rpath = $val;
3000             }
3001           else
3002             {
3003               define_pretty_variable ($rpathvar, $rcond, INTERNAL, $val);
3004             }
3005         }
3007       # If the resulting library lies into a subdirectory,
3008       # make sure this directory will exist.
3009       my $dirstamp = require_build_directory_maybe ($onelib);
3011       # Remember to cleanup .libs/ in this directory.
3012       my $dirname = dirname $onelib;
3013       $libtool_clean_directories{$dirname} = 1;
3015       $output_rules .= &file_contents ('ltlibrary',
3016                                        $where,
3017                                        LTLIBRARY  => $onelib,
3018                                        XLTLIBRARY => $xlib,
3019                                        RPATH      => $rpath,
3020                                        XLINK      => $xlink,
3021                                        VERBOSE    => $vlink,
3022                                        DIRSTAMP   => $dirstamp);
3023       if ($seen_libobjs)
3024         {
3025           if (var ($xlib . '_LIBADD'))
3026             {
3027               &check_libobjs_sources ($xlib, $xlib . '_LIBADD');
3028             }
3029         }
3030     }
3033 # See if any _SOURCES variable were misspelled.
3034 sub check_typos ()
3036   # It is ok if the user sets this particular variable.
3037   set_seen 'AM_LDFLAGS';
3039   foreach my $primary ('SOURCES', 'LIBADD', 'LDADD', 'LDFLAGS', 'DEPENDENCIES')
3040     {
3041       foreach my $var (variables $primary)
3042         {
3043           my $varname = $var->name;
3044           # A configure variable is always legitimate.
3045           next if exists $configure_vars{$varname};
3047           for my $cond ($var->conditions->conds)
3048             {
3049               $varname =~ /^(?:nobase_)?(?:dist_|nodist_)?(.*)_[[:alnum:]]+$/;
3050               msg_var ('syntax', $var, "variable `$varname' is defined but no"
3051                        . " program or\nlibrary has `$1' as canonical name"
3052                        . " (possible typo)")
3053                 unless $var->rdef ($cond)->seen;
3054             }
3055         }
3056     }
3060 # Handle scripts.
3061 sub handle_scripts
3063     # NOTE we no longer automatically clean SCRIPTS, because it is
3064     # useful to sometimes distribute scripts verbatim.  This happens
3065     # e.g. in Automake itself.
3066     &am_install_var ('-candist', 'scripts', 'SCRIPTS',
3067                      'bin', 'sbin', 'libexec', 'pkgdata',
3068                      'noinst', 'check');
3074 ## ------------------------ ##
3075 ## Handling Texinfo files.  ##
3076 ## ------------------------ ##
3078 # ($OUTFILE, $VFILE, @CLEAN_FILES)
3079 # &scan_texinfo_file ($FILENAME)
3080 # ------------------------------
3081 # $OUTFILE     - name of the info file produced by $FILENAME.
3082 # $VFILE       - name of the version.texi file used (undef if none).
3083 # @CLEAN_FILES - list of byproducts (indexes etc.)
3084 sub scan_texinfo_file ($)
3086   my ($filename) = @_;
3088   # Some of the following extensions are always created, no matter
3089   # whether indexes are used or not.  Other (like cps, fns, ... pgs)
3090   # are only created when they are used.  We used to scan $FILENAME
3091   # for their use, but that is not enough: they could be used in
3092   # included files.  We can't scan included files because we don't
3093   # know the include path.  Therefore we always erase these files, no
3094   # matter whether they are used or not.
3095   #
3096   # (tmp is only created if an @macro is used and a certain e-TeX
3097   # feature is not available.)
3098   my %clean_suffixes =
3099     map { $_ => 1 } (qw(aux log toc tmp
3100                         cp cps
3101                         fn fns
3102                         ky kys
3103                         vr vrs
3104                         tp tps
3105                         pg pgs)); # grep 'new.*index' texinfo.tex
3107   my $texi = new Automake::XFile "< $filename";
3108   verb "reading $filename";
3110   my ($outfile, $vfile);
3111   while ($_ = $texi->getline)
3112     {
3113       if (/^\@setfilename +(\S+)/)
3114         {
3115           # Honor only the first @setfilename.  (It's possible to have
3116           # more occurrences later if the manual shows examples of how
3117           # to use @setfilename...)
3118           next if $outfile;
3120           $outfile = $1;
3121           if ($outfile =~ /\.([^.]+)$/ && $1 ne 'info')
3122             {
3123               error ("$filename:$.",
3124                      "output `$outfile' has unrecognized extension");
3125               return;
3126             }
3127         }
3128       # A "version.texi" file is actually any file whose name matches
3129       # "vers*.texi".
3130       elsif (/^\@include\s+(vers[^.]*\.texi)\s*$/)
3131         {
3132           $vfile = $1;
3133         }
3135       # Try to find new or unused indexes.
3137       # Creating a new category of index.
3138       elsif (/^\@def(code)?index (\w+)/)
3139         {
3140           $clean_suffixes{$2} = 1;
3141           $clean_suffixes{"$2s"} = 1;
3142         }
3144       # Merging an index into an another.
3145       elsif (/^\@syn(code)?index (\w+) (\w+)/)
3146         {
3147           delete $clean_suffixes{"$2s"};
3148           $clean_suffixes{"$3s"} = 1;
3149         }
3151     }
3153   if (! $outfile)
3154     {
3155       err_am "`$filename' missing \@setfilename";
3156       return;
3157     }
3159   my $infobase = basename ($filename);
3160   $infobase =~ s/\.te?xi(nfo)?$//;
3161   return ($outfile, $vfile,
3162           map { "$infobase.$_" } (sort keys %clean_suffixes));
3166 # ($DIRSTAMP, @CLEAN_FILES)
3167 # output_texinfo_build_rules ($SOURCE, $DEST, $INSRC, @DEPENDENCIES)
3168 # ------------------------------------------------------------------
3169 # SOURCE - the source Texinfo file
3170 # DEST - the destination Info file
3171 # INSRC - wether DEST should be built in the source tree
3172 # DEPENDENCIES - known dependencies
3173 sub output_texinfo_build_rules ($$$@)
3175   my ($source, $dest, $insrc, @deps) = @_;
3177   # Split `a.texi' into `a' and `.texi'.
3178   my ($spfx, $ssfx) = ($source =~ /^(.*?)(\.[^.]*)?$/);
3179   my ($dpfx, $dsfx) = ($dest =~ /^(.*?)(\.[^.]*)?$/);
3181   $ssfx ||= "";
3182   $dsfx ||= "";
3184   # We can output two kinds of rules: the "generic" rules use Make
3185   # suffix rules and are appropriate when $source and $dest do not lie
3186   # in a sub-directory; the "specific" rules are needed in the other
3187   # case.
3188   #
3189   # The former are output only once (this is not really apparent here,
3190   # but just remember that some logic deeper in Automake will not
3191   # output the same rule twice); while the later need to be output for
3192   # each Texinfo source.
3193   my $generic;
3194   my $makeinfoflags;
3195   my $sdir = dirname $source;
3196   if ($sdir eq '.' && dirname ($dest) eq '.')
3197     {
3198       $generic = 1;
3199       $makeinfoflags = '-I $(srcdir)';
3200     }
3201   else
3202     {
3203       $generic = 0;
3204       $makeinfoflags = "-I $sdir -I \$(srcdir)/$sdir";
3205     }
3207   # A directory can contain two kinds of info files: some built in the
3208   # source tree, and some built in the build tree.  The rules are
3209   # different in each case.  However we cannot output two different
3210   # set of generic rules.  Because in-source builds are more usual, we
3211   # use generic rules in this case and fall back to "specific" rules
3212   # for build-dir builds.  (It should not be a problem to invert this
3213   # if needed.)
3214   $generic = 0 unless $insrc;
3216   # We cannot use a suffix rule to build info files with an empty
3217   # extension.  Otherwise we would output a single suffix inference
3218   # rule, with separate dependencies, as in
3219   #
3220   #    .texi:
3221   #             $(MAKEINFO) ...
3222   #    foo.info: foo.texi
3223   #
3224   # which confuse Solaris make.  (See the Autoconf manual for
3225   # details.)  Therefore we use a specific rule in this case.  This
3226   # applies to info files only (dvi and pdf files always have an
3227   # extension).
3228   my $generic_info = ($generic && $dsfx) ? 1 : 0;
3230   # If the resulting file lie into a subdirectory,
3231   # make sure this directory will exist.
3232   my $dirstamp = require_build_directory_maybe ($dest);
3234   my $dipfx = ($insrc ? '$(srcdir)/' : '') . $dpfx;
3236   $output_rules .= file_contents ('texibuild',
3237                                   new Automake::Location,
3238                                   DEPS             => "@deps",
3239                                   DEST_PREFIX      => $dpfx,
3240                                   DEST_INFO_PREFIX => $dipfx,
3241                                   DEST_SUFFIX      => $dsfx,
3242                                   DIRSTAMP         => $dirstamp,
3243                                   GENERIC          => $generic,
3244                                   GENERIC_INFO     => $generic_info,
3245                                   INSRC            => $insrc,
3246                                   MAKEINFOFLAGS    => $makeinfoflags,
3247                                   SOURCE           => ($generic
3248                                                        ? '$<' : $source),
3249                                   SOURCE_INFO      => ($generic_info
3250                                                        ? '$<' : $source),
3251                                   SOURCE_REAL      => $source,
3252                                   SOURCE_SUFFIX    => $ssfx,
3253                                   );
3254   return ($dirstamp, "$dpfx.dvi", "$dpfx.pdf", "$dpfx.ps", "$dpfx.html");
3258 # ($MOSTLYCLEAN, $TEXICLEAN, $MAINTCLEAN)
3259 # handle_texinfo_helper ($info_texinfos)
3260 # --------------------------------------
3261 # Handle all Texinfo source; helper for handle_texinfo.
3262 sub handle_texinfo_helper ($)
3264   my ($info_texinfos) = @_;
3265   my (@infobase, @info_deps_list, @texi_deps);
3266   my %versions;
3267   my $done = 0;
3268   my (@mostly_cleans, @texi_cleans, @maint_cleans) = ('', '', '');
3270   # Build a regex matching user-cleaned files.
3271   my $d = var 'DISTCLEANFILES';
3272   my $c = var 'CLEANFILES';
3273   my @f = ();
3274   push @f, $d->value_as_list_recursive (inner_expand => 1) if $d;
3275   push @f, $c->value_as_list_recursive (inner_expand => 1) if $c;
3276   @f = map { s|[^A-Za-z_0-9*\[\]\-]|\\$&|g; s|\*|[^/]*|g; $_; } @f;
3277   my $user_cleaned_files = '^(?:' . join ('|', @f) . ')$';
3279   foreach my $texi
3280       ($info_texinfos->value_as_list_recursive (inner_expand => 1))
3281     {
3282       my $infobase = $texi;
3283       $infobase =~ s/\.(txi|texinfo|texi)$//;
3285       if ($infobase eq $texi)
3286         {
3287           # FIXME: report line number.
3288           err_am "texinfo file `$texi' has unrecognized extension";
3289           next;
3290         }
3292       push @infobase, $infobase;
3294       # If 'version.texi' is referenced by input file, then include
3295       # automatic versioning capability.
3296       my ($out_file, $vtexi, @clean_files) =
3297         scan_texinfo_file ("$relative_dir/$texi")
3298         or next;
3299       push (@mostly_cleans, @clean_files);
3301       # If the Texinfo source is in a subdirectory, create the
3302       # resulting info in this subdirectory.  If it is in the current
3303       # directory, try hard to not prefix "./" because it breaks the
3304       # generic rules.
3305       my $outdir = dirname ($texi) . '/';
3306       $outdir = "" if $outdir eq './';
3307       $out_file =  $outdir . $out_file;
3309       # Until Automake 1.6.3, .info files were built in the
3310       # source tree.  This was an obstacle to the support of
3311       # non-distributed .info files, and non-distributed .texi
3312       # files.
3313       #
3314       # * Non-distributed .texi files is important in some packages
3315       #   where .texi files are built at make time, probably using
3316       #   other binaries built in the package itself, maybe using
3317       #   tools or information found on the build host.  Because
3318       #   these files are not distributed they are always rebuilt
3319       #   at make time; they should therefore not lie in the source
3320       #   directory.  One plan was to support this using
3321       #   nodist_info_TEXINFOS or something similar.  (Doing this
3322       #   requires some sanity checks.  For instance Automake should
3323       #   not allow:
3324       #      dist_info_TEXINFOS = foo.texi
3325       #      nodist_foo_TEXINFOS = included.texi
3326       #   because a distributed file should never depend on a
3327       #   non-distributed file.)
3328       #
3329       # * If .texi files are not distributed, then .info files should
3330       #   not be distributed either.  There are also cases where one
3331       #   wants to distribute .texi files, but does not want to
3332       #   distribute the .info files.  For instance the Texinfo package
3333       #   distributes the tool used to build these files; it would
3334       #   be a waste of space to distribute them.  It's not clear
3335       #   which syntax we should use to indicate that .info files should
3336       #   not be distributed.  Akim Demaille suggested that eventually
3337       #   we switch to a new syntax:
3338       #   |  Maybe we should take some inspiration from what's already
3339       #   |  done in the rest of Automake.  Maybe there is too much
3340       #   |  syntactic sugar here, and you want
3341       #   |     nodist_INFO = bar.info
3342       #   |     dist_bar_info_SOURCES = bar.texi
3343       #   |     bar_texi_DEPENDENCIES = foo.texi
3344       #   |  with a bit of magic to have bar.info represent the whole
3345       #   |  bar*info set.  That's a lot more verbose that the current
3346       #   |  situation, but it is # not new, hence the user has less
3347       #   |  to learn.
3348       #   |
3349       #   |  But there is still too much room for meaningless specs:
3350       #   |     nodist_INFO = bar.info
3351       #   |     dist_bar_info_SOURCES = bar.texi
3352       #   |     dist_PS = bar.ps something-written-by-hand.ps
3353       #   |     nodist_bar_ps_SOURCES = bar.texi
3354       #   |     bar_texi_DEPENDENCIES = foo.texi
3355       #   |  here bar.texi is dist_ in line 2, and nodist_ in 4.
3356       #
3357       # Back to the point, it should be clear that in order to support
3358       # non-distributed .info files, we need to build them in the
3359       # build tree, not in the source tree (non-distributed .texi
3360       # files are less of a problem, because we do not output build
3361       # rules for them).  In Automake 1.7 .info build rules have been
3362       # largely cleaned up so that .info files get always build in the
3363       # build tree, even when distributed.  The idea was that
3364       #   (1) if during a VPATH build the .info file was found to be
3365       #       absent or out-of-date (in the source tree or in the
3366       #       build tree), Make would rebuild it in the build tree.
3367       #       If an up-to-date source-tree of the .info file existed,
3368       #       make would not rebuild it in the build tree.
3369       #   (2) having two copies of .info files, one in the source tree
3370       #       and one (newer) in the build tree is not a problem
3371       #       because `make dist' always pick files in the build tree
3372       #       first.
3373       # However it turned out the be a bad idea for several reasons:
3374       #   * Tru64, OpenBSD, and FreeBSD (not NetBSD) Make do not behave
3375       #     like GNU Make on point (1) above.  These implementations
3376       #     of Make would always rebuild .info files in the build
3377       #     tree, even if such files were up to date in the source
3378       #     tree.  Consequently, it was impossible to perform a VPATH
3379       #     build of a package containing Texinfo files using these
3380       #     Make implementations.
3381       #     (Refer to the Autoconf Manual, section "Limitation of
3382       #     Make", paragraph "VPATH", item "target lookup", for
3383       #     an account of the differences between these
3384       #     implementations.)
3385       #   * The GNU Coding Standards require these files to be built
3386       #     in the source-tree (when they are distributed, that is).
3387       #   * Keeping a fresher copy of distributed files in the
3388       #     build tree can be annoying during development because
3389       #     - if the files is kept under CVS, you really want it
3390       #       to be updated in the source tree
3391       #     - it is confusing that `make distclean' does not erase
3392       #       all files in the build tree.
3393       #
3394       # Consequently, starting with Automake 1.8, .info files are
3395       # built in the source tree again.  Because we still plan to
3396       # support non-distributed .info files at some point, we
3397       # have a single variable ($INSRC) that controls whether
3398       # the current .info file must be built in the source tree
3399       # or in the build tree.  Actually this variable is switched
3400       # off for .info files that appear to be cleaned; this is
3401       # for backward compatibility with package such as Texinfo,
3402       # which do things like
3403       #   info_TEXINFOS = texinfo.txi info-stnd.texi info.texi
3404       #   DISTCLEANFILES = texinfo texinfo-* info*.info*
3405       #   # Do not create info files for distribution.
3406       #   dist-info:
3407       # in order not to distribute .info files.
3408       my $insrc = ($out_file =~ $user_cleaned_files) ? 0 : 1;
3410       my $soutdir = '$(srcdir)/' . $outdir;
3411       $outdir = $soutdir if $insrc;
3413       # If user specified file_TEXINFOS, then use that as explicit
3414       # dependency list.
3415       @texi_deps = ();
3416       push (@texi_deps, "$soutdir$vtexi") if $vtexi;
3418       my $canonical = canonicalize ($infobase);
3419       if (var ($canonical . "_TEXINFOS"))
3420         {
3421           push (@texi_deps, '$(' . $canonical . '_TEXINFOS)');
3422           push_dist_common ('$(' . $canonical . '_TEXINFOS)');
3423         }
3425       my ($dirstamp, @cfiles) =
3426         output_texinfo_build_rules ($texi, $out_file, $insrc, @texi_deps);
3427       push (@texi_cleans, @cfiles);
3429       push (@info_deps_list, $out_file);
3431       # If a vers*.texi file is needed, emit the rule.
3432       if ($vtexi)
3433         {
3434           err_am ("`$vtexi', included in `$texi', "
3435                   . "also included in `$versions{$vtexi}'")
3436             if defined $versions{$vtexi};
3437           $versions{$vtexi} = $texi;
3439           # We number the stamp-vti files.  This is doable since the
3440           # actual names don't matter much.  We only number starting
3441           # with the second one, so that the common case looks nice.
3442           my $vti = ($done ? $done : 'vti');
3443           ++$done;
3445           # This is ugly, but it is our historical practice.
3446           if ($config_aux_dir_set_in_configure_ac)
3447             {
3448               require_conf_file_with_macro (TRUE, 'info_TEXINFOS', FOREIGN,
3449                                             'mdate-sh');
3450             }
3451           else
3452             {
3453               require_file_with_macro (TRUE, 'info_TEXINFOS',
3454                                        FOREIGN, 'mdate-sh');
3455             }
3457           my $conf_dir;
3458           if ($config_aux_dir_set_in_configure_ac)
3459             {
3460               $conf_dir = "$am_config_aux_dir/";
3461             }
3462           else
3463             {
3464               $conf_dir = '$(srcdir)/';
3465             }
3466           $output_rules .= file_contents ('texi-vers',
3467                                           new Automake::Location,
3468                                           TEXI     => $texi,
3469                                           VTI      => $vti,
3470                                           STAMPVTI => "${soutdir}stamp-$vti",
3471                                           VTEXI    => "$soutdir$vtexi",
3472                                           MDDIR    => $conf_dir,
3473                                           DIRSTAMP => $dirstamp);
3474         }
3475     }
3477   # Handle location of texinfo.tex.
3478   my $need_texi_file = 0;
3479   my $texinfodir;
3480   if (var ('TEXINFO_TEX'))
3481     {
3482       # The user defined TEXINFO_TEX so assume he knows what he is
3483       # doing.
3484       $texinfodir = ('$(srcdir)/'
3485                      . dirname (variable_value ('TEXINFO_TEX')));
3486     }
3487   elsif (option 'cygnus')
3488     {
3489       $texinfodir = '$(top_srcdir)/../texinfo';
3490       define_variable ('TEXINFO_TEX', "$texinfodir/texinfo.tex", INTERNAL);
3491     }
3492   elsif ($config_aux_dir_set_in_configure_ac)
3493     {
3494       $texinfodir = $am_config_aux_dir;
3495       define_variable ('TEXINFO_TEX', "$texinfodir/texinfo.tex", INTERNAL);
3496       $need_texi_file = 2; # so that we require_conf_file later
3497     }
3498   else
3499     {
3500       $texinfodir = '$(srcdir)';
3501       $need_texi_file = 1;
3502     }
3503   define_variable ('am__TEXINFO_TEX_DIR', $texinfodir, INTERNAL);
3505   push (@dist_targets, 'dist-info');
3507   if (! option 'no-installinfo')
3508     {
3509       # Make sure documentation is made and installed first.  Use
3510       # $(INFO_DEPS), not 'info', because otherwise recursive makes
3511       # get run twice during "make all".
3512       unshift (@all, '$(INFO_DEPS)');
3513     }
3515   define_files_variable ("DVIS", @infobase, 'dvi', INTERNAL);
3516   define_files_variable ("PDFS", @infobase, 'pdf', INTERNAL);
3517   define_files_variable ("PSS", @infobase, 'ps', INTERNAL);
3518   define_files_variable ("HTMLS", @infobase, 'html', INTERNAL);
3520   # This next isn't strictly needed now -- the places that look here
3521   # could easily be changed to look in info_TEXINFOS.  But this is
3522   # probably better, in case noinst_TEXINFOS is ever supported.
3523   define_variable ("TEXINFOS", variable_value ('info_TEXINFOS'), INTERNAL);
3525   # Do some error checking.  Note that this file is not required
3526   # when in Cygnus mode; instead we defined TEXINFO_TEX explicitly
3527   # up above.
3528   if ($need_texi_file && ! option 'no-texinfo.tex')
3529     {
3530       if ($need_texi_file > 1)
3531         {
3532           require_conf_file_with_macro (TRUE, 'info_TEXINFOS', FOREIGN,
3533                                         'texinfo.tex');
3534         }
3535       else
3536         {
3537           require_file_with_macro (TRUE, 'info_TEXINFOS', FOREIGN,
3538                                    'texinfo.tex');
3539         }
3540     }
3542   return (makefile_wrap ("", "\t  ", @mostly_cleans),
3543           makefile_wrap ("", "\t  ", @texi_cleans),
3544           makefile_wrap ("", "\t  ", @maint_cleans));
3548 # handle_texinfo ()
3549 # -----------------
3550 # Handle all Texinfo source.
3551 sub handle_texinfo ()
3553   reject_var 'TEXINFOS', "`TEXINFOS' is an anachronism; use `info_TEXINFOS'";
3554   # FIXME: I think this is an obsolete future feature name.
3555   reject_var 'html_TEXINFOS', "HTML generation not yet supported";
3557   my $info_texinfos = var ('info_TEXINFOS');
3558   my ($mostlyclean, $clean, $maintclean) = ('', '', '');
3559   if ($info_texinfos)
3560     {
3561       ($mostlyclean, $clean, $maintclean) = handle_texinfo_helper ($info_texinfos);
3562       chomp $mostlyclean;
3563       chomp $clean;
3564       chomp $maintclean;
3565     }
3567   $output_rules .=  file_contents ('texinfos',
3568                                    new Automake::Location,
3569                                    MOSTLYCLEAN   => $mostlyclean,
3570                                    TEXICLEAN     => $clean,
3571                                    MAINTCLEAN    => $maintclean,
3572                                    'LOCAL-TEXIS' => !!$info_texinfos);
3576 # Handle any man pages.
3577 sub handle_man_pages
3579   reject_var 'MANS', "`MANS' is an anachronism; use `man_MANS'";
3581   # Find all the sections in use.  We do this by first looking for
3582   # "standard" sections, and then looking for any additional
3583   # sections used in man_MANS.
3584   my (%sections, %notrans_sections, %trans_sections,
3585       %notrans_vars, %trans_vars, %notrans_sect_vars, %trans_sect_vars);
3586   # We handle nodist_ for uniformity.  man pages aren't distributed
3587   # by default so it isn't actually very important.
3588   foreach my $npfx ('', 'notrans_')
3589     {
3590       foreach my $pfx ('', 'dist_', 'nodist_')
3591         {
3592           # Add more sections as needed.
3593           foreach my $section ('0'..'9', 'n', 'l')
3594             {
3595               my $varname = $npfx . $pfx . 'man' . $section . '_MANS';
3596               if (var ($varname))
3597                 {
3598                   $sections{$section} = 1;
3599                   $varname = '$(' . $varname . ')';
3600                   if ($npfx eq 'notrans_')
3601                     {
3602                       $notrans_sections{$section} = 1;
3603                       $notrans_sect_vars{$varname} = 1;
3604                     }
3605                   else
3606                     {
3607                       $trans_sections{$section} = 1;
3608                       $trans_sect_vars{$varname} = 1;
3609                     }
3611                   &push_dist_common ($varname)
3612                     if $pfx eq 'dist_';
3613                 }
3614             }
3616           my $varname = $npfx . $pfx . 'man_MANS';
3617           my $var = var ($varname);
3618           if ($var)
3619             {
3620               foreach ($var->value_as_list_recursive)
3621                 {
3622                   # A page like `foo.1c' goes into man1dir.
3623                   if (/\.([0-9a-z])([a-z]*)$/)
3624                     {
3625                       $sections{$1} = 1;
3626                       if ($npfx eq 'notrans_')
3627                         {
3628                           $notrans_sections{$1} = 1;
3629                         }
3630                       else
3631                         {
3632                           $trans_sections{$1} = 1;
3633                         }
3634                     }
3635                 }
3637               $varname = '$(' . $varname . ')';
3638               if ($npfx eq 'notrans_')
3639                 {
3640                   $notrans_vars{$varname} = 1;
3641                 }
3642               else
3643                 {
3644                   $trans_vars{$varname} = 1;
3645                 }
3646               &push_dist_common ($varname)
3647                 if $pfx eq 'dist_';
3648             }
3649         }
3650     }
3652   return unless %sections;
3654   my @unsorted_deps;
3656   # Build section independent variables.
3657   my $have_notrans = %notrans_vars;
3658   my @notrans_list = sort keys %notrans_vars;
3659   my $have_trans = %trans_vars;
3660   my @trans_list = sort keys %trans_vars;
3662   # Now for each section, generate an install and uninstall rule.
3663   # Sort sections so output is deterministic.
3664   foreach my $section (sort keys %sections)
3665     {
3666       # Build section dependent variables.
3667       my $notrans_mans = $have_notrans || exists $notrans_sections{$section};
3668       my $trans_mans = $have_trans || exists $trans_sections{$section};
3669       my (%notrans_this_sect, %trans_this_sect);
3670       my $expr = 'man' . $section . '_MANS';
3671       foreach my $varname (keys %notrans_sect_vars)
3672         {
3673           if ($varname =~ /$expr/)
3674             {
3675               $notrans_this_sect{$varname} = 1;
3676             }
3677         }
3678       foreach my $varname (keys %trans_sect_vars)
3679         {
3680           if ($varname =~ /$expr/)
3681             {
3682               $trans_this_sect{$varname} = 1;
3683             }
3684         }
3685       my @notrans_sect_list = sort keys %notrans_this_sect;
3686       my @trans_sect_list = sort keys %trans_this_sect;
3687       @unsorted_deps = (keys %notrans_vars, keys %trans_vars,
3688                         keys %notrans_this_sect, keys %trans_this_sect);
3689       my @deps = sort @unsorted_deps;
3690       $output_rules .= &file_contents ('mans',
3691                                        new Automake::Location,
3692                                        SECTION           => $section,
3693                                        DEPS              => "@deps",
3694                                        NOTRANS_MANS      => $notrans_mans,
3695                                        NOTRANS_SECT_LIST => "@notrans_sect_list",
3696                                        HAVE_NOTRANS      => $have_notrans,
3697                                        NOTRANS_LIST      => "@notrans_list",
3698                                        TRANS_MANS        => $trans_mans,
3699                                        TRANS_SECT_LIST   => "@trans_sect_list",
3700                                        HAVE_TRANS        => $have_trans,
3701                                        TRANS_LIST        => "@trans_list");
3702     }
3704   @unsorted_deps  = (keys %notrans_vars, keys %trans_vars,
3705                      keys %notrans_sect_vars, keys %trans_sect_vars);
3706   my @mans = sort @unsorted_deps;
3707   $output_vars .= file_contents ('mans-vars',
3708                                  new Automake::Location,
3709                                  MANS => "@mans");
3711   push (@all, '$(MANS)')
3712     unless option 'no-installman';
3715 # Handle DATA variables.
3716 sub handle_data
3718     &am_install_var ('-noextra', '-candist', 'data', 'DATA',
3719                      'data', 'dataroot', 'dvi', 'html', 'pdf', 'ps',
3720                      'sysconf', 'sharedstate', 'localstate',
3721                      'pkgdata', 'lisp', 'noinst', 'check');
3724 # Handle TAGS.
3725 sub handle_tags
3727     my @tag_deps = ();
3728     my @ctag_deps = ();
3729     if (var ('SUBDIRS'))
3730     {
3731         $output_rules .= ("tags-recursive:\n"
3732                           . "\tlist=\'\$(SUBDIRS)\'; for subdir in \$\$list; do \\\n"
3733                           # Never fail here if a subdir fails; it
3734                           # isn't important.
3735                           . "\t  test \"\$\$subdir\" = . || (\$(am__cd) \$\$subdir"
3736                           . " && \$(MAKE) \$(AM_MAKEFLAGS) tags); \\\n"
3737                           . "\tdone\n");
3738         push (@tag_deps, 'tags-recursive');
3739         &depend ('.PHONY', 'tags-recursive');
3740         &depend ('.MAKE', 'tags-recursive');
3742         $output_rules .= ("ctags-recursive:\n"
3743                           . "\tlist=\'\$(SUBDIRS)\'; for subdir in \$\$list; do \\\n"
3744                           # Never fail here if a subdir fails; it
3745                           # isn't important.
3746                           . "\t  test \"\$\$subdir\" = . || (\$(am__cd) \$\$subdir"
3747                           . " && \$(MAKE) \$(AM_MAKEFLAGS) ctags); \\\n"
3748                           . "\tdone\n");
3749         push (@ctag_deps, 'ctags-recursive');
3750         &depend ('.PHONY', 'ctags-recursive');
3751         &depend ('.MAKE', 'ctags-recursive');
3752     }
3754     if (&saw_sources_p (1)
3755         || var ('ETAGS_ARGS')
3756         || @tag_deps)
3757     {
3758         my @config;
3759         foreach my $spec (@config_headers)
3760         {
3761             my ($out, @ins) = split_config_file_spec ($spec);
3762             foreach my $in (@ins)
3763               {
3764                 # If the config header source is in this directory,
3765                 # require it.
3766                 push @config, basename ($in)
3767                   if $relative_dir eq dirname ($in);
3768               }
3769         }
3770         $output_rules .= &file_contents ('tags',
3771                                          new Automake::Location,
3772                                          CONFIG    => "@config",
3773                                          TAGSDIRS  => "@tag_deps",
3774                                          CTAGSDIRS => "@ctag_deps");
3776         set_seen 'TAGS_DEPENDENCIES';
3777     }
3778     elsif (reject_var ('TAGS_DEPENDENCIES',
3779                        "doesn't make sense to define `TAGS_DEPENDENCIES'"
3780                        . "without\nsources or `ETAGS_ARGS'"))
3781     {
3782     }
3783     else
3784     {
3785         # Every Makefile must define some sort of TAGS rule.
3786         # Otherwise, it would be possible for a top-level "make TAGS"
3787         # to fail because some subdirectory failed.
3788         $output_rules .= "tags: TAGS\nTAGS:\n\n";
3789         # Ditto ctags.
3790         $output_rules .= "ctags: CTAGS\nCTAGS:\n\n";
3791     }
3794 # Handle multilib support.
3795 sub handle_multilib
3797   if ($seen_multilib && $relative_dir eq '.')
3798     {
3799       $output_rules .= &file_contents ('multilib', new Automake::Location);
3800       push (@all, 'all-multi');
3801     }
3805 # user_phony_rule ($NAME)
3806 # -----------------------
3807 # Return false if rule $NAME does not exist.  Otherwise,
3808 # declare it as phony, complete its definition (in case it is
3809 # conditional), and return its Automake::Rule instance.
3810 sub user_phony_rule ($)
3812   my ($name) = @_;
3813   my $rule = rule $name;
3814   if ($rule)
3815     {
3816       depend ('.PHONY', $name);
3817       # Define $NAME in all condition where it is not already defined,
3818       # so that it is always OK to depend on $NAME.
3819       for my $c ($rule->not_always_defined_in_cond (TRUE)->conds)
3820         {
3821           Automake::Rule::define ($name, 'internal', RULE_AUTOMAKE,
3822                                   $c, INTERNAL);
3823           $output_rules .= $c->subst_string . "$name:\n";
3824         }
3825     }
3826   return $rule;
3830 # $BOOLEAN
3831 # &for_dist_common ($A, $B)
3832 # -------------------------
3833 # Subroutine for &handle_dist: sort files to dist.
3835 # We put README first because it then becomes easier to make a
3836 # Usenet-compliant shar file (in these, README must be first).
3838 # FIXME: do more ordering of files here.
3839 sub for_dist_common
3841     return 0
3842         if $a eq $b;
3843     return -1
3844         if $a eq 'README';
3845     return 1
3846         if $b eq 'README';
3847     return $a cmp $b;
3850 # handle_dist
3851 # -----------
3852 # Handle 'dist' target.
3853 sub handle_dist ()
3855   # Substitutions for distdir.am
3856   my %transform;
3858   # Define DIST_SUBDIRS.  This must always be done, regardless of the
3859   # no-dist setting: target like `distclean' or `maintainer-clean' use it.
3860   my $subdirs = var ('SUBDIRS');
3861   if ($subdirs)
3862     {
3863       # If SUBDIRS is conditionally defined, then set DIST_SUBDIRS
3864       # to all possible directories, and use it.  If DIST_SUBDIRS is
3865       # defined, just use it.
3867       # Note that we check DIST_SUBDIRS first on purpose, so that
3868       # we don't call has_conditional_contents for now reason.
3869       # (In the past one project used so many conditional subdirectories
3870       # that calling has_conditional_contents on SUBDIRS caused
3871       # automake to grow to 150Mb -- this should not happen with
3872       # the current implementation of has_conditional_contents,
3873       # but it's more efficient to avoid the call anyway.)
3874       if (var ('DIST_SUBDIRS'))
3875         {
3876         }
3877       elsif ($subdirs->has_conditional_contents)
3878         {
3879           define_pretty_variable
3880             ('DIST_SUBDIRS', TRUE, INTERNAL,
3881              uniq ($subdirs->value_as_list_recursive));
3882         }
3883       else
3884         {
3885           # We always define this because that is what `distclean'
3886           # wants.
3887           define_pretty_variable ('DIST_SUBDIRS', TRUE, INTERNAL,
3888                                   '$(SUBDIRS)');
3889         }
3890     }
3892   # The remaining definitions are only required when a dist target is used.
3893   return if option 'no-dist';
3895   # At least one of the archive formats must be enabled.
3896   if ($relative_dir eq '.')
3897     {
3898       my $archive_defined = option 'no-dist-gzip' ? 0 : 1;
3899       $archive_defined ||=
3900         grep { option "dist-$_" } qw(shar zip tarZ bzip2 lzma xz);
3901       error (option 'no-dist-gzip',
3902              "no-dist-gzip specified but no dist-* specified, "
3903              . "at least one archive format must be enabled")
3904         unless $archive_defined;
3905     }
3907   # Look for common files that should be included in distribution.
3908   # If the aux dir is set, and it does not have a Makefile.am, then
3909   # we check for these files there as well.
3910   my $check_aux = 0;
3911   if ($relative_dir eq '.'
3912       && $config_aux_dir_set_in_configure_ac)
3913     {
3914       if (! &is_make_dir ($config_aux_dir))
3915         {
3916           $check_aux = 1;
3917         }
3918     }
3919   foreach my $cfile (@common_files)
3920     {
3921       if (dir_has_case_matching_file ($relative_dir, $cfile)
3922           # The file might be absent, but if it can be built it's ok.
3923           || rule $cfile)
3924         {
3925           &push_dist_common ($cfile);
3926         }
3928       # Don't use `elsif' here because a file might meaningfully
3929       # appear in both directories.
3930       if ($check_aux && dir_has_case_matching_file ($config_aux_dir, $cfile))
3931         {
3932           &push_dist_common ("$config_aux_dir/$cfile")
3933         }
3934     }
3936   # We might copy elements from $configure_dist_common to
3937   # %dist_common if we think we need to.  If the file appears in our
3938   # directory, we would have discovered it already, so we don't
3939   # check that.  But if the file is in a subdir without a Makefile,
3940   # we want to distribute it here if we are doing `.'.  Ugly!
3941   if ($relative_dir eq '.')
3942     {
3943       foreach my $file (split (' ' , $configure_dist_common))
3944         {
3945           push_dist_common ($file)
3946             unless is_make_dir (dirname ($file));
3947         }
3948     }
3950   # Files to distributed.  Don't use ->value_as_list_recursive
3951   # as it recursively expands `$(dist_pkgdata_DATA)' etc.
3952   my @dist_common = split (' ', rvar ('DIST_COMMON')->variable_value);
3953   @dist_common = uniq (sort for_dist_common (@dist_common));
3954   variable_delete 'DIST_COMMON';
3955   define_pretty_variable ('DIST_COMMON', TRUE, INTERNAL, @dist_common);
3957   # Now that we've processed DIST_COMMON, disallow further attempts
3958   # to set it.
3959   $handle_dist_run = 1;
3961   # Scan EXTRA_DIST to see if we need to distribute anything from a
3962   # subdir.  If so, add it to the list.  I didn't want to do this
3963   # originally, but there were so many requests that I finally
3964   # relented.
3965   my $extra_dist = var ('EXTRA_DIST');
3967   $transform{'DISTCHECK-HOOK'} = !! rule 'distcheck-hook';
3968   $transform{'GETTEXT'} = $seen_gettext && !$seen_gettext_external;
3970   # If the target `dist-hook' exists, make sure it is run.  This
3971   # allows users to do random weird things to the distribution
3972   # before it is packaged up.
3973   push (@dist_targets, 'dist-hook')
3974     if user_phony_rule 'dist-hook';
3975   $transform{'DIST-TARGETS'} = join (' ', @dist_targets);
3977   my $flm = option ('filename-length-max');
3978   my $filename_filter = $flm ? '.' x $flm->[1] : '';
3980   $output_rules .= &file_contents ('distdir',
3981                                    new Automake::Location,
3982                                    %transform,
3983                                    FILENAME_FILTER => $filename_filter);
3987 # check_directory ($NAME, $WHERE)
3988 # -------------------------------
3989 # Ensure $NAME is a directory, and that it uses a sane name.
3990 # Use $WHERE as a location in the diagnostic, if any.
3991 sub check_directory ($$)
3993   my ($dir, $where) = @_;
3995   error $where, "required directory $relative_dir/$dir does not exist"
3996     unless -d "$relative_dir/$dir";
3998   # If an `obj/' directory exists, BSD make will enter it before
3999   # reading `Makefile'.  Hence the `Makefile' in the current directory
4000   # will not be read.
4001   #
4002   #  % cat Makefile
4003   #  all:
4004   #          echo Hello
4005   #  % cat obj/Makefile
4006   #  all:
4007   #          echo World
4008   #  % make      # GNU make
4009   #  echo Hello
4010   #  Hello
4011   #  % pmake     # BSD make
4012   #  echo World
4013   #  World
4014   msg ('portability', $where,
4015        "naming a subdirectory `obj' causes troubles with BSD make")
4016     if $dir eq 'obj';
4018   # `aux' is probably the most important of the following forbidden name,
4019   # since it's tempting to use it as an AC_CONFIG_AUX_DIR.
4020   msg ('portability', $where,
4021        "name `$dir' is reserved on W32 and DOS platforms")
4022     if grep (/^\Q$dir\E$/i, qw/aux lpt1 lpt2 lpt3 com1 com2 com3 com4 con prn/);
4025 # check_directories_in_var ($VARIABLE)
4026 # ------------------------------------
4027 # Recursively check all items in variables $VARIABLE as directories
4028 sub check_directories_in_var ($)
4030   my ($var) = @_;
4031   $var->traverse_recursively
4032     (sub
4033      {
4034        my ($var, $val, $cond, $full_cond) = @_;
4035        check_directory ($val, $var->rdef ($cond)->location);
4036        return ();
4037      },
4038      undef,
4039      skip_ac_subst => 1);
4042 # &handle_subdirs ()
4043 # ------------------
4044 # Handle subdirectories.
4045 sub handle_subdirs ()
4047   my $subdirs = var ('SUBDIRS');
4048   return
4049     unless $subdirs;
4051   check_directories_in_var $subdirs;
4053   my $dsubdirs = var ('DIST_SUBDIRS');
4054   check_directories_in_var $dsubdirs
4055     if $dsubdirs;
4057   $output_rules .= &file_contents ('subdirs', new Automake::Location);
4058   rvar ('RECURSIVE_TARGETS')->rdef (TRUE)->{'pretty'} = VAR_SORTED; # Gross!
4062 # ($REGEN, @DEPENDENCIES)
4063 # &scan_aclocal_m4
4064 # ----------------
4065 # If aclocal.m4 creation is automated, return the list of its dependencies.
4066 sub scan_aclocal_m4 ()
4068   my $regen_aclocal = 0;
4070   set_seen 'CONFIG_STATUS_DEPENDENCIES';
4071   set_seen 'CONFIGURE_DEPENDENCIES';
4073   if (-f 'aclocal.m4')
4074     {
4075       &define_variable ("ACLOCAL_M4", '$(top_srcdir)/aclocal.m4', INTERNAL);
4077       my $aclocal = new Automake::XFile "< aclocal.m4";
4078       my $line = $aclocal->getline;
4079       $regen_aclocal = $line =~ 'generated automatically by aclocal';
4080     }
4082   my @ac_deps = ();
4084   if (set_seen ('ACLOCAL_M4_SOURCES'))
4085     {
4086       push (@ac_deps, '$(ACLOCAL_M4_SOURCES)');
4087       msg_var ('obsolete', 'ACLOCAL_M4_SOURCES',
4088                "`ACLOCAL_M4_SOURCES' is obsolete.\n"
4089                . "It should be safe to simply remove it.");
4090     }
4092   # Note that it might be possible that aclocal.m4 doesn't exist but
4093   # should be auto-generated.  This case probably isn't very
4094   # important.
4096   return ($regen_aclocal, @ac_deps);
4100 # Helper function for substitute_ac_subst_variables.
4101 sub substitute_ac_subst_variables_worker($)
4103   my ($token) = @_;
4104   return "\@$token\@" if var $token;
4105   return "\${$token\}";
4108 # substitute_ac_subst_variables ($TEXT)
4109 # -------------------------------------
4110 # Replace any occurrence of ${FOO} in $TEXT by @FOO@ if FOO is an AC_SUBST
4111 # variable.
4112 sub substitute_ac_subst_variables ($)
4114   my ($text) = @_;
4115   $text =~ s/\${([^ \t=:+{}]+)}/&substitute_ac_subst_variables_worker ($1)/ge;
4116   return $text;
4119 # @DEPENDENCIES
4120 # &prepend_srcdir (@INPUTS)
4121 # -------------------------
4122 # Prepend $(srcdir) or $(top_srcdir) to all @INPUTS.  The idea is that
4123 # if an input file has a directory part the same as the current
4124 # directory, then the directory part is simply replaced by $(srcdir).
4125 # But if the directory part is different, then $(top_srcdir) is
4126 # prepended.
4127 sub prepend_srcdir (@)
4129   my (@inputs) = @_;
4130   my @newinputs;
4132   foreach my $single (@inputs)
4133     {
4134       if (dirname ($single) eq $relative_dir)
4135         {
4136           push (@newinputs, '$(srcdir)/' . basename ($single));
4137         }
4138       else
4139         {
4140           push (@newinputs, '$(top_srcdir)/' . $single);
4141         }
4142     }
4143   return @newinputs;
4146 # @DEPENDENCIES
4147 # rewrite_inputs_into_dependencies ($OUTPUT, @INPUTS)
4148 # ---------------------------------------------------
4149 # Compute a list of dependencies appropriate for the rebuild
4150 # rule of
4151 #   AC_CONFIG_FILES($OUTPUT:$INPUT[0]:$INPUTS[1]:...)
4152 # Also distribute $INPUTs which are not built by another AC_CONFIG_FOOS.
4153 sub rewrite_inputs_into_dependencies ($@)
4155   my ($file, @inputs) = @_;
4156   my @res = ();
4158   for my $i (@inputs)
4159     {
4160       # We cannot create dependencies on shell variables.
4161       next if (substitute_ac_subst_variables $i) =~ /\$/;
4163       if (exists $ac_config_files_location{$i} && $i ne $file)
4164         {
4165           my $di = dirname $i;
4166           if ($di eq $relative_dir)
4167             {
4168               $i = basename $i;
4169             }
4170           # In the top-level Makefile we do not use $(top_builddir), because
4171           # we are already there, and since the targets are built without
4172           # a $(top_builddir), it helps BSD Make to match them with
4173           # dependencies.
4174           elsif ($relative_dir ne '.')
4175             {
4176               $i = '$(top_builddir)/' . $i;
4177             }
4178         }
4179       else
4180         {
4181           msg ('error', $ac_config_files_location{$file},
4182                "required file `$i' not found")
4183             unless $i =~ /\$/ || exists $output_files{$i} || -f $i;
4184           ($i) = prepend_srcdir ($i);
4185           push_dist_common ($i);
4186         }
4187       push @res, $i;
4188     }
4189   return @res;
4194 # &handle_configure ($MAKEFILE_AM, $MAKEFILE_IN, $MAKEFILE, @INPUTS)
4195 # ------------------------------------------------------------------
4196 # Handle remaking and configure stuff.
4197 # We need the name of the input file, to do proper remaking rules.
4198 sub handle_configure ($$$@)
4200   my ($makefile_am, $makefile_in, $makefile, @inputs) = @_;
4202   prog_error 'empty @inputs'
4203     unless @inputs;
4205   my ($rel_makefile_am, $rel_makefile_in) = prepend_srcdir ($makefile_am,
4206                                                             $makefile_in);
4207   my $rel_makefile = basename $makefile;
4209   my $colon_infile = ':' . join (':', @inputs);
4210   $colon_infile = '' if $colon_infile eq ":$makefile.in";
4211   my @rewritten = rewrite_inputs_into_dependencies ($makefile, @inputs);
4212   my ($regen_aclocal_m4, @aclocal_m4_deps) = scan_aclocal_m4;
4213   define_pretty_variable ('am__aclocal_m4_deps', TRUE, INTERNAL,
4214                           @configure_deps, @aclocal_m4_deps,
4215                           '$(top_srcdir)/' . $configure_ac);
4216   my @configuredeps = ('$(am__aclocal_m4_deps)', '$(CONFIGURE_DEPENDENCIES)');
4217   push @configuredeps, '$(ACLOCAL_M4)' if -f 'aclocal.m4';
4218   define_pretty_variable ('am__configure_deps', TRUE, INTERNAL,
4219                           @configuredeps);
4221   my $automake_options = '--' . (global_option 'cygnus' ? 'cygnus' : $strictness_name)
4222                          . (global_option 'no-dependencies' ? ' --ignore-deps' : '');
4224   $output_rules .= file_contents
4225     ('configure',
4226      new Automake::Location,
4227      MAKEFILE              => $rel_makefile,
4228      'MAKEFILE-DEPS'       => "@rewritten",
4229      'CONFIG-MAKEFILE'     => ($relative_dir eq '.') ? '$@' : '$(subdir)/$@',
4230      'MAKEFILE-IN'         => $rel_makefile_in,
4231      'MAKEFILE-IN-DEPS'    => "@include_stack",
4232      'MAKEFILE-AM'         => $rel_makefile_am,
4233      'AUTOMAKE-OPTIONS'    => $automake_options,
4234      'MAKEFILE-AM-SOURCES' => "$makefile$colon_infile",
4235      'REGEN-ACLOCAL-M4'    => $regen_aclocal_m4,
4236      VERBOSE               => verbose_flag ('GEN'));
4238   if ($relative_dir eq '.')
4239     {
4240       &push_dist_common ('acconfig.h')
4241         if -f 'acconfig.h';
4242     }
4244   # If we have a configure header, require it.
4245   my $hdr_index = 0;
4246   my @distclean_config;
4247   foreach my $spec (@config_headers)
4248     {
4249       $hdr_index += 1;
4250       # $CONFIG_H_PATH: config.h from top level.
4251       my ($config_h_path, @ins) = split_config_file_spec ($spec);
4252       my $config_h_dir = dirname ($config_h_path);
4254       # If the header is in the current directory we want to build
4255       # the header here.  Otherwise, if we're at the topmost
4256       # directory and the header's directory doesn't have a
4257       # Makefile, then we also want to build the header.
4258       if ($relative_dir eq $config_h_dir
4259           || ($relative_dir eq '.' && ! &is_make_dir ($config_h_dir)))
4260         {
4261           my ($cn_sans_dir, $stamp_dir);
4262           if ($relative_dir eq $config_h_dir)
4263             {
4264               $cn_sans_dir = basename ($config_h_path);
4265               $stamp_dir = '';
4266             }
4267           else
4268             {
4269               $cn_sans_dir = $config_h_path;
4270               if ($config_h_dir eq '.')
4271                 {
4272                   $stamp_dir = '';
4273                 }
4274               else
4275                 {
4276                   $stamp_dir = $config_h_dir . '/';
4277                 }
4278             }
4280           # This will also distribute all inputs.
4281           @ins = rewrite_inputs_into_dependencies ($config_h_path, @ins);
4283           # Cannot define rebuild rules for filenames with shell variables.
4284           next if (substitute_ac_subst_variables $config_h_path) =~ /\$/;
4286           # Header defined in this directory.
4287           my @files;
4288           if (-f $config_h_path . '.top')
4289             {
4290               push (@files, "$cn_sans_dir.top");
4291             }
4292           if (-f $config_h_path . '.bot')
4293             {
4294               push (@files, "$cn_sans_dir.bot");
4295             }
4297           push_dist_common (@files);
4299           # For now, acconfig.h can only appear in the top srcdir.
4300           if (-f 'acconfig.h')
4301             {
4302               push (@files, '$(top_srcdir)/acconfig.h');
4303             }
4305           my $stamp = "${stamp_dir}stamp-h${hdr_index}";
4306           $output_rules .=
4307             file_contents ('remake-hdr',
4308                            new Automake::Location,
4309                            FILES            => "@files",
4310                            CONFIG_H         => $cn_sans_dir,
4311                            CONFIG_HIN       => $ins[0],
4312                            CONFIG_H_DEPS    => "@ins",
4313                            CONFIG_H_PATH    => $config_h_path,
4314                            STAMP            => "$stamp");
4316           push @distclean_config, $cn_sans_dir, $stamp;
4317         }
4318     }
4320   $output_rules .= file_contents ('clean-hdr',
4321                                   new Automake::Location,
4322                                   FILES => "@distclean_config")
4323     if @distclean_config;
4325   # Distribute and define mkinstalldirs only if it is already present
4326   # in the package, for backward compatibility (some people may still
4327   # use $(mkinstalldirs)).
4328   my $mkidpath = "$config_aux_dir/mkinstalldirs";
4329   if (-f $mkidpath)
4330     {
4331       # Use require_file so that any existing script gets updated
4332       # by --force-missing.
4333       require_conf_file ($mkidpath, FOREIGN, 'mkinstalldirs');
4334       define_variable ('mkinstalldirs',
4335                        "\$(SHELL) $am_config_aux_dir/mkinstalldirs", INTERNAL);
4336     }
4337   else
4338     {
4339       # Use $(install_sh), not $(MKDIR_P) because the latter requires
4340       # at least one argument, and $(mkinstalldirs) used to work
4341       # even without arguments (e.g. $(mkinstalldirs) $(conditional_dir)).
4342       define_variable ('mkinstalldirs', '$(install_sh) -d', INTERNAL);
4343     }
4345   reject_var ('CONFIG_HEADER',
4346               "`CONFIG_HEADER' is an anachronism; now determined "
4347               . "automatically\nfrom `$configure_ac'");
4349   my @config_h;
4350   foreach my $spec (@config_headers)
4351     {
4352       my ($out, @ins) = split_config_file_spec ($spec);
4353       # Generate CONFIG_HEADER define.
4354       if ($relative_dir eq dirname ($out))
4355         {
4356           push @config_h, basename ($out);
4357         }
4358       else
4359         {
4360           push @config_h, "\$(top_builddir)/$out";
4361         }
4362     }
4363   define_variable ("CONFIG_HEADER", "@config_h", INTERNAL)
4364     if @config_h;
4366   # Now look for other files in this directory which must be remade
4367   # by config.status, and generate rules for them.
4368   my @actual_other_files = ();
4369   # These get cleaned only in a VPATH build.
4370   my @actual_other_vpath_files = ();
4371   foreach my $lfile (@other_input_files)
4372     {
4373       my $file;
4374       my @inputs;
4375       if ($lfile =~ /^([^:]*):(.*)$/)
4376         {
4377           # This is the ":" syntax of AC_OUTPUT.
4378           $file = $1;
4379           @inputs = split (':', $2);
4380         }
4381       else
4382         {
4383           # Normal usage.
4384           $file = $lfile;
4385           @inputs = $file . '.in';
4386         }
4388       # Automake files should not be stored in here, but in %MAKE_LIST.
4389       prog_error ("$lfile in \@other_input_files\n"
4390                   . "\@other_input_files = (@other_input_files)")
4391         if -f $file . '.am';
4393       my $local = basename ($file);
4395       # We skip files that aren't in this directory.  However, if
4396       # the file's directory does not have a Makefile, and we are
4397       # currently doing `.', then we create a rule to rebuild the
4398       # file in the subdir.
4399       my $fd = dirname ($file);
4400       if ($fd ne $relative_dir)
4401         {
4402           if ($relative_dir eq '.' && ! &is_make_dir ($fd))
4403             {
4404               $local = $file;
4405             }
4406           else
4407             {
4408               next;
4409             }
4410         }
4412       my @rewritten_inputs = rewrite_inputs_into_dependencies ($file, @inputs);
4414       # Cannot output rules for shell variables.
4415       next if (substitute_ac_subst_variables $local) =~ /\$/;
4417       my $condstr = '';
4418       my $cond = $ac_config_files_condition{$lfile};
4419       if (defined $cond)
4420         {
4421           $condstr = $cond->subst_string;
4422           Automake::Rule::define ($local, $configure_ac, RULE_AUTOMAKE, $cond,
4423                                   $ac_config_files_location{$file});
4424         }
4425       $output_rules .= ($condstr . $local . ': '
4426                         . '$(top_builddir)/config.status '
4427                         . "@rewritten_inputs\n"
4428                         . $condstr . "\t"
4429                         . 'cd $(top_builddir) && '
4430                         . '$(SHELL) ./config.status '
4431                         . ($relative_dir eq '.' ? '' : '$(subdir)/')
4432                         . '$@'
4433                         . "\n");
4434       push (@actual_other_files, $local);
4435     }
4437   # For links we should clean destinations and distribute sources.
4438   foreach my $spec (@config_links)
4439     {
4440       my ($link, $file) = split /:/, $spec;
4441       # Some people do AC_CONFIG_LINKS($computed).  We only handle
4442       # the DEST:SRC form.
4443       next unless $file;
4444       my $where = $ac_config_files_location{$link};
4446       # Skip destinations that contain shell variables.
4447       if ((substitute_ac_subst_variables $link) !~ /\$/)
4448         {
4449           # We skip links that aren't in this directory.  However, if
4450           # the link's directory does not have a Makefile, and we are
4451           # currently doing `.', then we add the link to CONFIG_CLEAN_FILES
4452           # in `.'s Makefile.in.
4453           my $local = basename ($link);
4454           my $fd = dirname ($link);
4455           if ($fd ne $relative_dir)
4456             {
4457               if ($relative_dir eq '.' && ! &is_make_dir ($fd))
4458                 {
4459                   $local = $link;
4460                 }
4461               else
4462                 {
4463                   $local = undef;
4464                 }
4465             }
4466           if ($file ne $link)
4467             {
4468               push @actual_other_files, $local if $local;
4469             }
4470           else
4471             {
4472               push @actual_other_vpath_files, $local if $local;
4473             }
4474         }
4476       # Do not process sources that contain shell variables.
4477       if ((substitute_ac_subst_variables $file) !~ /\$/)
4478         {
4479           my $fd = dirname ($file);
4481           # We distribute files that are in this directory.
4482           # At the top-level (`.') we also distribute files whose
4483           # directory does not have a Makefile.
4484           if (($fd eq $relative_dir)
4485               || ($relative_dir eq '.' && ! &is_make_dir ($fd)))
4486             {
4487               # The following will distribute $file as a side-effect when
4488               # it is appropriate (i.e., when $file is not already an output).
4489               # We do not need the result, just the side-effect.
4490               rewrite_inputs_into_dependencies ($link, $file);
4491             }
4492         }
4493     }
4495   # These files get removed by "make distclean".
4496   define_pretty_variable ('CONFIG_CLEAN_FILES', TRUE, INTERNAL,
4497                           @actual_other_files);
4498   define_pretty_variable ('CONFIG_CLEAN_VPATH_FILES', TRUE, INTERNAL,
4499                           @actual_other_vpath_files);
4502 # Handle C headers.
4503 sub handle_headers
4505     my @r = &am_install_var ('-defaultdist', 'header', 'HEADERS', 'include',
4506                              'oldinclude', 'pkginclude',
4507                              'noinst', 'check');
4508     foreach (@r)
4509     {
4510       next unless $_->[1] =~ /\..*$/;
4511       &saw_extension ($&);
4512     }
4515 sub handle_gettext
4517   return if ! $seen_gettext || $relative_dir ne '.';
4519   my $subdirs = var 'SUBDIRS';
4521   if (! $subdirs)
4522     {
4523       err_ac "AM_GNU_GETTEXT used but SUBDIRS not defined";
4524       return;
4525     }
4527   # Perform some sanity checks to help users get the right setup.
4528   # We disable these tests when po/ doesn't exist in order not to disallow
4529   # unusual gettext setups.
4530   #
4531   # Bruno Haible:
4532   # | The idea is:
4533   # |
4534   # |  1) If a package doesn't have a directory po/ at top level, it
4535   # |     will likely have multiple po/ directories in subpackages.
4536   # |
4537   # |  2) It is useful to warn for the absence of intl/ if AM_GNU_GETTEXT
4538   # |     is used without 'external'. It is also useful to warn for the
4539   # |     presence of intl/ if AM_GNU_GETTEXT([external]) is used. Both
4540   # |     warnings apply only to the usual layout of packages, therefore
4541   # |     they should both be disabled if no po/ directory is found at
4542   # |     top level.
4544   if (-d 'po')
4545     {
4546       my @subdirs = $subdirs->value_as_list_recursive;
4548       msg_var ('syntax', $subdirs,
4549                "AM_GNU_GETTEXT used but `po' not in SUBDIRS")
4550         if ! grep ($_ eq 'po', @subdirs);
4552       # intl/ is not required when AM_GNU_GETTEXT is called with the
4553       # `external' option and AM_GNU_GETTEXT_INTL_SUBDIR is not called.
4554       msg_var ('syntax', $subdirs,
4555                "AM_GNU_GETTEXT used but `intl' not in SUBDIRS")
4556         if (! ($seen_gettext_external && ! $seen_gettext_intl)
4557             && ! grep ($_ eq 'intl', @subdirs));
4559       # intl/ should not be used with AM_GNU_GETTEXT([external]), except
4560       # if AM_GNU_GETTEXT_INTL_SUBDIR is called.
4561       msg_var ('syntax', $subdirs,
4562                "`intl' should not be in SUBDIRS when "
4563                . "AM_GNU_GETTEXT([external]) is used")
4564         if ($seen_gettext_external && ! $seen_gettext_intl
4565             && grep ($_ eq 'intl', @subdirs));
4566     }
4568   require_file ($ac_gettext_location, GNU, 'ABOUT-NLS');
4571 # Handle footer elements.
4572 sub handle_footer
4574     reject_rule ('.SUFFIXES',
4575                  "use variable `SUFFIXES', not target `.SUFFIXES'");
4577     # Note: AIX 4.1 /bin/make will fail if any suffix rule appears
4578     # before .SUFFIXES.  So we make sure that .SUFFIXES appears before
4579     # anything else, by sticking it right after the default: target.
4580     $output_header .= ".SUFFIXES:\n";
4581     my $suffixes = var 'SUFFIXES';
4582     my @suffixes = Automake::Rule::suffixes;
4583     if (@suffixes || $suffixes)
4584     {
4585         # Make sure SUFFIXES has unique elements.  Sort them to ensure
4586         # the output remains consistent.  However, $(SUFFIXES) is
4587         # always at the start of the list, unsorted.  This is done
4588         # because make will choose rules depending on the ordering of
4589         # suffixes, and this lets the user have some control.  Push
4590         # actual suffixes, and not $(SUFFIXES).  Some versions of make
4591         # do not like variable substitutions on the .SUFFIXES line.
4592         my @user_suffixes = ($suffixes
4593                              ? $suffixes->value_as_list_recursive : ());
4595         my %suffixes = map { $_ => 1 } @suffixes;
4596         delete @suffixes{@user_suffixes};
4598         $output_header .= (".SUFFIXES: "
4599                            . join (' ', @user_suffixes, sort keys %suffixes)
4600                            . "\n");
4601     }
4603     $output_trailer .= file_contents ('footer', new Automake::Location);
4607 # Generate `make install' rules.
4608 sub handle_install ()
4610   $output_rules .= &file_contents
4611     ('install',
4612      new Automake::Location,
4613      maybe_BUILT_SOURCES => (set_seen ('BUILT_SOURCES')
4614                              ? (" \$(BUILT_SOURCES)\n"
4615                                 . "\t\$(MAKE) \$(AM_MAKEFLAGS)")
4616                              : ''),
4617      'installdirs-local' => (user_phony_rule 'installdirs-local'
4618                              ? ' installdirs-local' : ''),
4619      am__installdirs => variable_value ('am__installdirs') || '');
4623 # Deal with all and all-am.
4624 sub handle_all ($)
4626     my ($makefile) = @_;
4628     # Output `all-am'.
4630     # Put this at the beginning for the sake of non-GNU makes.  This
4631     # is still wrong if these makes can run parallel jobs.  But it is
4632     # right enough.
4633     unshift (@all, basename ($makefile));
4635     foreach my $spec (@config_headers)
4636       {
4637         my ($out, @ins) = split_config_file_spec ($spec);
4638         push (@all, basename ($out))
4639           if dirname ($out) eq $relative_dir;
4640       }
4642     # Install `all' hooks.
4643     push (@all, "all-local")
4644       if user_phony_rule "all-local";
4646     &pretty_print_rule ("all-am:", "\t\t", @all);
4647     &depend ('.PHONY', 'all-am', 'all');
4650     # Output `all'.
4652     my @local_headers = ();
4653     push @local_headers, '$(BUILT_SOURCES)'
4654       if var ('BUILT_SOURCES');
4655     foreach my $spec (@config_headers)
4656       {
4657         my ($out, @ins) = split_config_file_spec ($spec);
4658         push @local_headers, basename ($out)
4659           if dirname ($out) eq $relative_dir;
4660       }
4662     if (@local_headers)
4663       {
4664         # We need to make sure config.h is built before we recurse.
4665         # We also want to make sure that built sources are built
4666         # before any ordinary `all' targets are run.  We can't do this
4667         # by changing the order of dependencies to the "all" because
4668         # that breaks when using parallel makes.  Instead we handle
4669         # things explicitly.
4670         $output_all .= ("all: @local_headers"
4671                         . "\n\t"
4672                         . '$(MAKE) $(AM_MAKEFLAGS) '
4673                         . (var ('SUBDIRS') ? 'all-recursive' : 'all-am')
4674                         . "\n\n");
4675         depend ('.MAKE', 'all');
4676       }
4677     else
4678       {
4679         $output_all .= "all: " . (var ('SUBDIRS')
4680                                   ? 'all-recursive' : 'all-am') . "\n\n";
4681       }
4685 # &do_check_merge_target ()
4686 # -------------------------
4687 # Handle check merge target specially.
4688 sub do_check_merge_target ()
4690   # Include user-defined local form of target.
4691   push @check_tests, 'check-local'
4692     if user_phony_rule 'check-local';
4694   # In --cygnus mode, check doesn't depend on all.
4695   if (option 'cygnus')
4696     {
4697       # Just run the local check rules.
4698       pretty_print_rule ('check-am:', "\t\t", @check);
4699     }
4700   else
4701     {
4702       # The check target must depend on the local equivalent of
4703       # `all', to ensure all the primary targets are built.  Then it
4704       # must build the local check rules.
4705       $output_rules .= "check-am: all-am\n";
4706       if (@check)
4707         {
4708           pretty_print_rule ("\t\$(MAKE) \$(AM_MAKEFLAGS)", "\t  ",
4709                              @check);
4710           depend ('.MAKE', 'check-am');
4711         }
4712     }
4713   if (@check_tests)
4714     {
4715       pretty_print_rule ("\t\$(MAKE) \$(AM_MAKEFLAGS)", "\t  ",
4716                          @check_tests);
4717       depend ('.MAKE', 'check-am');
4718     }
4720   depend '.PHONY', 'check', 'check-am';
4721   # Handle recursion.  We have to honor BUILT_SOURCES like for `all:'.
4722   $output_rules .= ("check: "
4723                     . (var ('BUILT_SOURCES')
4724                        ? "\$(BUILT_SOURCES)\n\t\$(MAKE) \$(AM_MAKEFLAGS) "
4725                        : '')
4726                     . (var ('SUBDIRS') ? 'check-recursive' : 'check-am')
4727                     . "\n");
4728   depend ('.MAKE', 'check')
4729     if var ('BUILT_SOURCES');
4732 # handle_clean ($MAKEFILE)
4733 # ------------------------
4734 # Handle all 'clean' targets.
4735 sub handle_clean ($)
4737   my ($makefile) = @_;
4739   # Clean the files listed in user variables if they exist.
4740   $clean_files{'$(MOSTLYCLEANFILES)'} = MOSTLY_CLEAN
4741     if var ('MOSTLYCLEANFILES');
4742   $clean_files{'$(CLEANFILES)'} = CLEAN
4743     if var ('CLEANFILES');
4744   $clean_files{'$(DISTCLEANFILES)'} = DIST_CLEAN
4745     if var ('DISTCLEANFILES');
4746   $clean_files{'$(MAINTAINERCLEANFILES)'} = MAINTAINER_CLEAN
4747     if var ('MAINTAINERCLEANFILES');
4749   # Built sources are automatically removed by maintainer-clean.
4750   $clean_files{'$(BUILT_SOURCES)'} = MAINTAINER_CLEAN
4751     if var ('BUILT_SOURCES');
4753   # Compute a list of "rm"s to run for each target.
4754   my %rms = (MOSTLY_CLEAN, [],
4755              CLEAN, [],
4756              DIST_CLEAN, [],
4757              MAINTAINER_CLEAN, []);
4759   foreach my $file (keys %clean_files)
4760     {
4761       my $when = $clean_files{$file};
4762       prog_error 'invalid entry in %clean_files'
4763         unless exists $rms{$when};
4765       my $rm = "rm -f $file";
4766       # If file is a variable, make sure when don't call `rm -f' without args.
4767       $rm ="test -z \"$file\" || $rm"
4768         if ($file =~ /^\s*\$(\(.*\)|\{.*\})\s*$/);
4770       push @{$rms{$when}}, "\t-$rm\n";
4771     }
4773   $output_rules .= &file_contents
4774     ('clean',
4775      new Automake::Location,
4776      MOSTLYCLEAN_RMS      => join ('', sort @{$rms{&MOSTLY_CLEAN}}),
4777      CLEAN_RMS            => join ('', sort @{$rms{&CLEAN}}),
4778      DISTCLEAN_RMS        => join ('', sort @{$rms{&DIST_CLEAN}}),
4779      MAINTAINER_CLEAN_RMS => join ('', sort @{$rms{&MAINTAINER_CLEAN}}),
4780      MAKEFILE             => basename $makefile,
4781      );
4785 # &target_cmp ($A, $B)
4786 # --------------------
4787 # Subroutine for &handle_factored_dependencies to let `.PHONY' and
4788 # other `.TARGETS' be last.
4789 sub target_cmp
4791   return 0 if $a eq $b;
4793   my $a1 = substr ($a, 0, 1);
4794   my $b1 = substr ($b, 0, 1);
4795   if ($a1 ne $b1)
4796     {
4797       return -1 if $b1 eq '.';
4798       return 1 if $a1 eq '.';
4799     }
4800   return $a cmp $b;
4804 # &handle_factored_dependencies ()
4805 # --------------------------------
4806 # Handle everything related to gathered targets.
4807 sub handle_factored_dependencies
4809   # Reject bad hooks.
4810   foreach my $utarg ('uninstall-data-local', 'uninstall-data-hook',
4811                      'uninstall-exec-local', 'uninstall-exec-hook',
4812                      'uninstall-dvi-local',
4813                      'uninstall-html-local',
4814                      'uninstall-info-local',
4815                      'uninstall-pdf-local',
4816                      'uninstall-ps-local')
4817     {
4818       my $x = $utarg;
4819       $x =~ s/-.*-/-/;
4820       reject_rule ($utarg, "use `$x', not `$utarg'");
4821     }
4823   reject_rule ('install-local',
4824                "use `install-data-local' or `install-exec-local', "
4825                . "not `install-local'");
4827   reject_rule ('install-hook',
4828                "use `install-data-hook' or `install-exec-hook', "
4829                . "not `install-hook'");
4831   # Install the -local hooks.
4832   foreach (keys %dependencies)
4833     {
4834       # Hooks are installed on the -am targets.
4835       s/-am$// or next;
4836       depend ("$_-am", "$_-local")
4837         if user_phony_rule "$_-local";
4838     }
4840   # Install the -hook hooks.
4841   # FIXME: Why not be as liberal as we are with -local hooks?
4842   foreach ('install-exec', 'install-data', 'uninstall')
4843     {
4844       if (user_phony_rule "$_-hook")
4845         {
4846           depend ('.MAKE', "$_-am");
4847           register_action("$_-am",
4848                           ("\t\@\$(NORMAL_INSTALL)\n"
4849                            . "\t\$(MAKE) \$(AM_MAKEFLAGS) $_-hook"));
4850         }
4851     }
4853   # All the required targets are phony.
4854   depend ('.PHONY', keys %required_targets);
4856   # Actually output gathered targets.
4857   foreach (sort target_cmp keys %dependencies)
4858     {
4859       # If there is nothing about this guy, skip it.
4860       next
4861         unless (@{$dependencies{$_}}
4862                 || $actions{$_}
4863                 || $required_targets{$_});
4865       # Define gathered targets in undefined conditions.
4866       # FIXME: Right now we must handle .PHONY as an exception,
4867       # because people write things like
4868       #    .PHONY: myphonytarget
4869       # to append dependencies.  This would not work if Automake
4870       # refrained from defining its own .PHONY target as it does
4871       # with other overridden targets.
4872       # Likewise for `.MAKE'.
4873       my @undefined_conds = (TRUE,);
4874       if ($_ ne '.PHONY' && $_ ne '.MAKE')
4875         {
4876           @undefined_conds =
4877             Automake::Rule::define ($_, 'internal',
4878                                     RULE_AUTOMAKE, TRUE, INTERNAL);
4879         }
4880       my @uniq_deps = uniq (sort @{$dependencies{$_}});
4881       foreach my $cond (@undefined_conds)
4882         {
4883           my $condstr = $cond->subst_string;
4884           &pretty_print_rule ("$condstr$_:", "$condstr\t", @uniq_deps);
4885           $output_rules .= $actions{$_} if defined $actions{$_};
4886           $output_rules .= "\n";
4887         }
4888     }
4892 # &handle_tests_dejagnu ()
4893 # ------------------------
4894 sub handle_tests_dejagnu
4896     push (@check_tests, 'check-DEJAGNU');
4897     $output_rules .= file_contents ('dejagnu', new Automake::Location);
4901 # Handle TESTS variable and other checks.
4902 sub handle_tests
4904   if (option 'dejagnu')
4905     {
4906       &handle_tests_dejagnu;
4907     }
4908   else
4909     {
4910       foreach my $c ('DEJATOOL', 'RUNTEST', 'RUNTESTFLAGS')
4911         {
4912           reject_var ($c, "`$c' defined but `dejagnu' not in "
4913                       . "`AUTOMAKE_OPTIONS'");
4914         }
4915     }
4917   if (var ('TESTS'))
4918     {
4919       push (@check_tests, 'check-TESTS');
4920       $output_rules .= &file_contents ('check', new Automake::Location,
4921                                        COLOR => !! option 'color-tests',
4922                                        PARALLEL_TESTS => !! option 'parallel-tests');
4924       # Tests that are known programs should have $(EXEEXT) appended.
4925       # For matching purposes, we need to adjust XFAIL_TESTS as well.
4926       append_exeext { exists $known_programs{$_[0]} } 'TESTS';
4927       append_exeext { exists $known_programs{$_[0]} } 'XFAIL_TESTS'
4928         if (var ('XFAIL_TESTS'));
4930       if (option 'parallel-tests')
4931         {
4932           define_variable ('TEST_SUITE_LOG', 'test-suite.log', INTERNAL);
4933           define_variable ('TEST_SUITE_HTML', '$(TEST_SUITE_LOG:.log=.html)', INTERNAL);
4934           my $suff = '.test';
4935           my $at_exeext = '';
4936           my $handle_exeext = exists $configure_vars{'EXEEXT'};
4937           if ($handle_exeext)
4938             {
4939               $at_exeext = subst ('EXEEXT');
4940               $suff = $at_exeext  . ' ' . $suff;
4941             }
4942           define_variable ('TEST_EXTENSIONS', $suff, INTERNAL);
4943           # FIXME: this mishandles conditions.
4944           my @test_suffixes = (var 'TEST_EXTENSIONS')->value_as_list_recursive;
4945           if ($handle_exeext)
4946             {
4947               unshift (@test_suffixes, $at_exeext)
4948                 unless $test_suffixes[0] eq $at_exeext;
4949             }
4950           unshift (@test_suffixes, '');
4952           transform_variable_recursively
4953             ('TESTS', 'TEST_LOGS', 'am__testlogs', 1, INTERNAL,
4954               sub {
4955                 my ($subvar, $val, $cond, $full_cond) = @_;
4956                 my $obj = $val;
4957                 return $obj
4958                   if $val =~ /^\@.*\@$/;
4959                 $obj =~ s/\$\(EXEEXT\)$//o;
4961                 if ($val =~ /(\$\((top_)?srcdir\))\//o)
4962                   {
4963                     msg ('error', $subvar->rdef ($cond)->location,
4964                          "parallel-tests: using `$1' in TESTS is currently broken: `$val'");
4965                   }
4967                 foreach my $test_suffix (@test_suffixes)
4968                   {
4969                     next
4970                       if $test_suffix eq $at_exeext || $test_suffix eq '';
4971                     return substr ($obj, 0, length ($obj) - length ($test_suffix)) . '.log'
4972                       if substr ($obj, - length ($test_suffix)) eq $test_suffix;
4973                   }
4974                 $obj .= '.log';
4975                 my $compile = 'LOG_COMPILE';
4976                 define_variable ($compile,
4977                                  '$(LOG_COMPILER) $(AM_LOG_FLAGS) $(LOG_FLAGS)', INTERNAL);
4978                 $output_rules .= file_contents ('check2', new Automake::Location,
4979                                                 GENERIC => 0,
4980                                                 OBJ => $obj,
4981                                                 SOURCE => $val,
4982                                                 COMPILE =>'$(' . $compile . ')',
4983                                                 EXT => '',
4984                                                 am__EXEEXT => 'FALSE');
4985                 return $obj;
4986               });
4988           my $nhelper=1;
4989           my $prev = 'TESTS';
4990           my $post = '';
4991           my $last_suffix = $test_suffixes[$#test_suffixes];
4992           my $cur = '';
4993           foreach my $test_suffix (@test_suffixes)
4994             {
4995               if ($test_suffix eq $last_suffix)
4996                 {
4997                   $cur = 'TEST_LOGS';
4998                 }
4999               else
5000                 {
5001                   $cur = 'am__test_logs' . $nhelper;
5002                 }
5003               define_variable ($cur,
5004                 '$(' . $prev . ':' . $test_suffix . $post . '=.log)', INTERNAL);
5005               $post = '.log';
5006               $prev = $cur;
5007               $nhelper++;
5008               if ($test_suffix ne $at_exeext && $test_suffix ne '')
5009                 {
5010                   (my $ext = $test_suffix) =~ s/^\.//;
5011                   $ext = uc $ext;
5012                   my $compile = $ext . '_LOG_COMPILE';
5013                   define_variable ($compile,
5014                                    '$(' . $ext . '_LOG_COMPILER) $(AM_' .  $ext . '_LOG_FLAGS)'
5015                                    . ' $(' . $ext . '_LOG_FLAGS)', INTERNAL);
5016                   my $am_exeext = $handle_exeext ? 'am__EXEEXT' : 'FALSE';
5017                   $output_rules .= file_contents ('check2', new Automake::Location,
5018                                                   GENERIC => 1,
5019                                                   OBJ => '',
5020                                                   SOURCE => '$<',
5021                                                   COMPILE => '$(' . $compile . ')',
5022                                                   EXT => $test_suffix,
5023                                                   am__EXEEXT => $am_exeext);
5024                 }
5025             }
5027           define_variable ('TEST_LOGS_TMP', '$(TEST_LOGS:.log=.log-t)', INTERNAL);
5029           $clean_files{'$(TEST_LOGS_TMP)'} = MOSTLY_CLEAN;
5030           $clean_files{'$(TEST_LOGS)'} = MOSTLY_CLEAN;
5031           $clean_files{'$(TEST_SUITE_LOG)'} = MOSTLY_CLEAN;
5032           $clean_files{'$(TEST_SUITE_HTML)'} = MOSTLY_CLEAN;
5033         }
5034     }
5037 # Handle Emacs Lisp.
5038 sub handle_emacs_lisp
5040   my @elfiles = &am_install_var ('-candist', 'lisp', 'LISP',
5041                                  'lisp', 'noinst');
5043   return if ! @elfiles;
5045   define_pretty_variable ('am__ELFILES', TRUE, INTERNAL,
5046                           map { $_->[1] } @elfiles);
5047   define_pretty_variable ('am__ELCFILES', TRUE, INTERNAL,
5048                           '$(am__ELFILES:.el=.elc)');
5049   # This one can be overridden by users.
5050   define_pretty_variable ('ELCFILES', TRUE, INTERNAL, '$(LISP:.el=.elc)');
5052   push @all, '$(ELCFILES)';
5054   require_variables ($elfiles[0][0], "Emacs Lisp sources seen", TRUE,
5055                      'EMACS', 'lispdir');
5056   require_conf_file ($elfiles[0][0], FOREIGN, 'elisp-comp');
5057   &define_variable ('elisp_comp', "$am_config_aux_dir/elisp-comp", INTERNAL);
5060 # Handle Python
5061 sub handle_python
5063   my @pyfiles = &am_install_var ('-defaultdist', 'python', 'PYTHON',
5064                                  'noinst');
5065   return if ! @pyfiles;
5067   require_variables ($pyfiles[0][0], "Python sources seen", TRUE, 'PYTHON');
5068   require_conf_file ($pyfiles[0][0], FOREIGN, 'py-compile');
5069   &define_variable ('py_compile', "$am_config_aux_dir/py-compile", INTERNAL);
5072 # Handle Java.
5073 sub handle_java
5075     my @sourcelist = &am_install_var ('-candist',
5076                                       'java', 'JAVA',
5077                                       'java', 'noinst', 'check');
5078     return if ! @sourcelist;
5080     my @prefix = am_primary_prefixes ('JAVA', 1,
5081                                       'java', 'noinst', 'check');
5083     my $dir;
5084     foreach my $curs (@prefix)
5085       {
5086         next
5087           if $curs eq 'EXTRA';
5089         err_var "${curs}_JAVA", "multiple _JAVA primaries in use"
5090           if defined $dir;
5091         $dir = $curs;
5092       }
5095     push (@all, 'class' . $dir . '.stamp');
5099 # Handle some of the minor options.
5100 sub handle_minor_options
5102   if (option 'readme-alpha')
5103     {
5104       if ($relative_dir eq '.')
5105         {
5106           if ($package_version !~ /^$GNITS_VERSION_PATTERN$/)
5107             {
5108               msg ('error-gnits', $package_version_location,
5109                    "version `$package_version' doesn't follow " .
5110                    "Gnits standards");
5111             }
5112           if (defined $1 && -f 'README-alpha')
5113             {
5114               # This means we have an alpha release.  See
5115               # GNITS_VERSION_PATTERN for details.
5116               push_dist_common ('README-alpha');
5117             }
5118         }
5119     }
5122 ################################################################
5124 # ($OUTPUT, @INPUTS)
5125 # &split_config_file_spec ($SPEC)
5126 # -------------------------------
5127 # Decode the Autoconf syntax for config files (files, headers, links
5128 # etc.).
5129 sub split_config_file_spec ($)
5131   my ($spec) = @_;
5132   my ($output, @inputs) = split (/:/, $spec);
5134   push @inputs, "$output.in"
5135     unless @inputs;
5137   return ($output, @inputs);
5140 # $input
5141 # locate_am (@POSSIBLE_SOURCES)
5142 # -----------------------------
5143 # AC_CONFIG_FILES allow specifications such as Makefile:top.in:mid.in:bot.in
5144 # This functions returns the first *.in file for which a *.am exists.
5145 # It returns undef otherwise.
5146 sub locate_am (@)
5148   my (@rest) = @_;
5149   my $input;
5150   foreach my $file (@rest)
5151     {
5152       if (($file =~ /^(.*)\.in$/) && -f "$1.am")
5153         {
5154           $input = $file;
5155           last;
5156         }
5157     }
5158   return $input;
5161 my %make_list;
5163 # &scan_autoconf_config_files ($WHERE, $CONFIG-FILES)
5164 # ---------------------------------------------------
5165 # Study $CONFIG-FILES which is the first argument to AC_CONFIG_FILES
5166 # (or AC_OUTPUT).
5167 sub scan_autoconf_config_files ($$)
5169   my ($where, $config_files) = @_;
5171   # Look at potential Makefile.am's.
5172   foreach (split ' ', $config_files)
5173     {
5174       # Must skip empty string for Perl 4.
5175       next if $_ eq "\\" || $_ eq '';
5177       # Handle $local:$input syntax.
5178       my ($local, @rest) = split (/:/);
5179       @rest = ("$local.in",) unless @rest;
5180       msg ('portability', $where,
5181           "Omit leading `./' from config file names such as `$local',"
5182           . "\nas not all make implementations treat `file' and `./file' equally.")
5183         if ($local =~ /^\.\//);
5184       my $input = locate_am @rest;
5185       if ($input)
5186         {
5187           # We have a file that automake should generate.
5188           $make_list{$input} = join (':', ($local, @rest));
5189         }
5190       else
5191         {
5192           # We have a file that automake should cause to be
5193           # rebuilt, but shouldn't generate itself.
5194           push (@other_input_files, $_);
5195         }
5196       $ac_config_files_location{$local} = $where;
5197       $ac_config_files_condition{$local} =
5198         new Automake::Condition (@cond_stack)
5199           if (@cond_stack);
5200     }
5204 # &scan_autoconf_traces ($FILENAME)
5205 # ---------------------------------
5206 sub scan_autoconf_traces ($)
5208   my ($filename) = @_;
5210   # Macros to trace, with their minimal number of arguments.
5211   #
5212   # IMPORTANT: If you add a macro here, you should also add this macro
5213   # =========  to Automake-preselection in autoconf/lib/autom4te.in.
5214   my %traced = (
5215                 AC_CANONICAL_BUILD => 0,
5216                 AC_CANONICAL_HOST => 0,
5217                 AC_CANONICAL_TARGET => 0,
5218                 AC_CONFIG_AUX_DIR => 1,
5219                 AC_CONFIG_FILES => 1,
5220                 AC_CONFIG_HEADERS => 1,
5221                 AC_CONFIG_LIBOBJ_DIR => 1,
5222                 AC_CONFIG_LINKS => 1,
5223                 AC_FC_SRCEXT => 1,
5224                 AC_INIT => 0,
5225                 AC_LIBSOURCE => 1,
5226                 AC_REQUIRE_AUX_FILE => 1,
5227                 AC_SUBST_TRACE => 1,
5228                 AM_AUTOMAKE_VERSION => 1,
5229                 AM_CONDITIONAL => 2,
5230                 AM_ENABLE_MULTILIB => 0,
5231                 AM_GNU_GETTEXT => 0,
5232                 AM_GNU_GETTEXT_INTL_SUBDIR => 0,
5233                 AM_INIT_AUTOMAKE => 0,
5234                 AM_MAINTAINER_MODE => 0,
5235                 AM_PROG_CC_C_O => 0,
5236                 AM_SILENT_RULES => 0,
5237                 _AM_SUBST_NOTMAKE => 1,
5238                 _AM_COND_IF => 1,
5239                 _AM_COND_ELSE => 1,
5240                 _AM_COND_ENDIF => 1,
5241                 LT_SUPPORTED_TAG => 1,
5242                 _LT_AC_TAGCONFIG => 0,
5243                 m4_include => 1,
5244                 m4_sinclude => 1,
5245                 sinclude => 1,
5246               );
5248   my $traces = ($ENV{AUTOCONF} || 'autoconf') . " ";
5250   # Use a separator unlikely to be used, not `:', the default, which
5251   # has a precise meaning for AC_CONFIG_FILES and so on.
5252   $traces .= join (' ',
5253                    map { "--trace=$_" . ':\$f:\$l::\$d::\$n::\${::}%' }
5254                    (keys %traced));
5256   my $tracefh = new Automake::XFile ("$traces $filename |");
5257   verb "reading $traces";
5259   @cond_stack = ();
5260   my $where;
5262   while ($_ = $tracefh->getline)
5263     {
5264       chomp;
5265       my ($here, $depth, @args) = split (/::/);
5266       $where = new Automake::Location $here;
5267       my $macro = $args[0];
5269       prog_error ("unrequested trace `$macro'")
5270         unless exists $traced{$macro};
5272       # Skip and diagnose malformed calls.
5273       if ($#args < $traced{$macro})
5274         {
5275           msg ('syntax', $where, "not enough arguments for $macro");
5276           next;
5277         }
5279       # Alphabetical ordering please.
5280       if ($macro eq 'AC_CANONICAL_BUILD')
5281         {
5282           if ($seen_canonical <= AC_CANONICAL_BUILD)
5283             {
5284               $seen_canonical = AC_CANONICAL_BUILD;
5285               $canonical_location = $where;
5286             }
5287         }
5288       elsif ($macro eq 'AC_CANONICAL_HOST')
5289         {
5290           if ($seen_canonical <= AC_CANONICAL_HOST)
5291             {
5292               $seen_canonical = AC_CANONICAL_HOST;
5293               $canonical_location = $where;
5294             }
5295         }
5296       elsif ($macro eq 'AC_CANONICAL_TARGET')
5297         {
5298           $seen_canonical = AC_CANONICAL_TARGET;
5299           $canonical_location = $where;
5300         }
5301       elsif ($macro eq 'AC_CONFIG_AUX_DIR')
5302         {
5303           if ($seen_init_automake)
5304             {
5305               error ($where, "AC_CONFIG_AUX_DIR must be called before "
5306                      . "AM_INIT_AUTOMAKE...", partial => 1);
5307               error ($seen_init_automake, "... AM_INIT_AUTOMAKE called here");
5308             }
5309           $config_aux_dir = $args[1];
5310           $config_aux_dir_set_in_configure_ac = 1;
5311           $relative_dir = '.';
5312           check_directory ($config_aux_dir, $where);
5313         }
5314       elsif ($macro eq 'AC_CONFIG_FILES')
5315         {
5316           # Look at potential Makefile.am's.
5317           scan_autoconf_config_files ($where, $args[1]);
5318         }
5319       elsif ($macro eq 'AC_CONFIG_HEADERS')
5320         {
5321           foreach my $spec (split (' ', $args[1]))
5322             {
5323               my ($dest, @src) = split (':', $spec);
5324               $ac_config_files_location{$dest} = $where;
5325               push @config_headers, $spec;
5326             }
5327         }
5328       elsif ($macro eq 'AC_CONFIG_LIBOBJ_DIR')
5329         {
5330           $config_libobj_dir = $args[1];
5331           $relative_dir = '.';
5332           check_directory ($config_libobj_dir, $where);
5333         }
5334       elsif ($macro eq 'AC_CONFIG_LINKS')
5335         {
5336           foreach my $spec (split (' ', $args[1]))
5337             {
5338               my ($dest, $src) = split (':', $spec);
5339               $ac_config_files_location{$dest} = $where;
5340               push @config_links, $spec;
5341             }
5342         }
5343       elsif ($macro eq 'AC_FC_SRCEXT')
5344         {
5345           my $suffix = $args[1];
5346           # These flags are used as %SOURCEFLAG% in depend2.am,
5347           # where the trailing space is important.
5348           $sourceflags{'.' . $suffix} = '$(FCFLAGS_' . $suffix . ') '
5349             if ($suffix eq 'f90' || $suffix eq 'f95' || $suffix eq 'f03' || $suffix eq 'f08');
5350         }
5351       elsif ($macro eq 'AC_INIT')
5352         {
5353           if (defined $args[2])
5354             {
5355               $package_version = $args[2];
5356               $package_version_location = $where;
5357             }
5358         }
5359       elsif ($macro eq 'AC_LIBSOURCE')
5360         {
5361           $libsources{$args[1]} = $here;
5362         }
5363       elsif ($macro eq 'AC_REQUIRE_AUX_FILE')
5364         {
5365           # Only remember the first time a file is required.
5366           $required_aux_file{$args[1]} = $where
5367             unless exists $required_aux_file{$args[1]};
5368         }
5369       elsif ($macro eq 'AC_SUBST_TRACE')
5370         {
5371           # Just check for alphanumeric in AC_SUBST_TRACE.  If you do
5372           # AC_SUBST(5), then too bad.
5373           $configure_vars{$args[1]} = $where
5374             if $args[1] =~ /^\w+$/;
5375         }
5376       elsif ($macro eq 'AM_AUTOMAKE_VERSION')
5377         {
5378           error ($where,
5379                  "version mismatch.  This is Automake $VERSION,\n" .
5380                  "but the definition used by this AM_INIT_AUTOMAKE\n" .
5381                  "comes from Automake $args[1].  You should recreate\n" .
5382                  "aclocal.m4 with aclocal and run automake again.\n",
5383                  # $? = 63 is used to indicate version mismatch to missing.
5384                  exit_code => 63)
5385             if $VERSION ne $args[1];
5387           $seen_automake_version = 1;
5388         }
5389       elsif ($macro eq 'AM_CONDITIONAL')
5390         {
5391           $configure_cond{$args[1]} = $where;
5392         }
5393       elsif ($macro eq 'AM_ENABLE_MULTILIB')
5394         {
5395           $seen_multilib = $where;
5396         }
5397       elsif ($macro eq 'AM_GNU_GETTEXT')
5398         {
5399           $seen_gettext = $where;
5400           $ac_gettext_location = $where;
5401           $seen_gettext_external = grep ($_ eq 'external', @args);
5402         }
5403       elsif ($macro eq 'AM_GNU_GETTEXT_INTL_SUBDIR')
5404         {
5405           $seen_gettext_intl = $where;
5406         }
5407       elsif ($macro eq 'AM_INIT_AUTOMAKE')
5408         {
5409           $seen_init_automake = $where;
5410           if (defined $args[2])
5411             {
5412               $package_version = $args[2];
5413               $package_version_location = $where;
5414             }
5415           elsif (defined $args[1])
5416             {
5417               exit $exit_code
5418                 if (process_global_option_list ($where,
5419                                                 split (' ', $args[1])));
5420             }
5421         }
5422       elsif ($macro eq 'AM_MAINTAINER_MODE')
5423         {
5424           $seen_maint_mode = $where;
5425         }
5426       elsif ($macro eq 'AM_PROG_CC_C_O')
5427         {
5428           $seen_cc_c_o = $where;
5429         }
5430       elsif ($macro eq 'AM_SILENT_RULES')
5431         {
5432           set_global_option ('silent-rules', $where);
5433         }
5434       elsif ($macro eq '_AM_COND_IF')
5435         {
5436           cond_stack_if ('', $args[1], $where);
5437           error ($where, "missing m4 quoting, macro depth $depth")
5438             if ($depth != 1);
5439         }
5440       elsif ($macro eq '_AM_COND_ELSE')
5441         {
5442           cond_stack_else ('!', $args[1], $where);
5443           error ($where, "missing m4 quoting, macro depth $depth")
5444             if ($depth != 1);
5445         }
5446       elsif ($macro eq '_AM_COND_ENDIF')
5447         {
5448           cond_stack_endif (undef, undef, $where);
5449           error ($where, "missing m4 quoting, macro depth $depth")
5450             if ($depth != 1);
5451         }
5452       elsif ($macro eq '_AM_SUBST_NOTMAKE')
5453         {
5454           $ignored_configure_vars{$args[1]} = $where;
5455         }
5456       elsif ($macro eq 'm4_include'
5457              || $macro eq 'm4_sinclude'
5458              || $macro eq 'sinclude')
5459         {
5460           # Skip missing `sinclude'd files.
5461           next if $macro ne 'm4_include' && ! -f $args[1];
5463           # Some modified versions of Autoconf don't use
5464           # frozen files.  Consequently it's possible that we see all
5465           # m4_include's performed during Autoconf's startup.
5466           # Obviously we don't want to distribute Autoconf's files
5467           # so we skip absolute filenames here.
5468           push @configure_deps, '$(top_srcdir)/' . $args[1]
5469             unless $here =~ m,^(?:\w:)?[\\/],;
5470           # Keep track of the greatest timestamp.
5471           if (-e $args[1])
5472             {
5473               my $mtime = mtime $args[1];
5474               $configure_deps_greatest_timestamp = $mtime
5475                 if $mtime > $configure_deps_greatest_timestamp;
5476             }
5477         }
5478       elsif ($macro eq 'LT_SUPPORTED_TAG')
5479         {
5480           $libtool_tags{$args[1]} = 1;
5481           $libtool_new_api = 1;
5482         }
5483       elsif ($macro eq '_LT_AC_TAGCONFIG')
5484         {
5485           # _LT_AC_TAGCONFIG is an old macro present in Libtool 1.5.
5486           # We use it to detect whether tags are supported.  Our
5487           # preferred interface is LT_SUPPORTED_TAG, but it was
5488           # introduced in Libtool 1.6.
5489           if (0 == keys %libtool_tags)
5490             {
5491               # Hardcode the tags supported by Libtool 1.5.
5492               %libtool_tags = (CC => 1, CXX => 1, GCJ => 1, F77 => 1);
5493             }
5494         }
5495     }
5497   error ($where, "condition stack not properly closed")
5498     if (@cond_stack);
5500   $tracefh->close;
5504 # &scan_autoconf_files ()
5505 # -----------------------
5506 # Check whether we use `configure.ac' or `configure.in'.
5507 # Scan it (and possibly `aclocal.m4') for interesting things.
5508 # We must scan aclocal.m4 because there might be AC_SUBSTs and such there.
5509 sub scan_autoconf_files ()
5511   # Reinitialize libsources here.  This isn't really necessary,
5512   # since we currently assume there is only one configure.ac.  But
5513   # that won't always be the case.
5514   %libsources = ();
5516   # Keep track of the youngest configure dependency.
5517   $configure_deps_greatest_timestamp = mtime $configure_ac;
5518   if (-e 'aclocal.m4')
5519     {
5520       my $mtime = mtime 'aclocal.m4';
5521       $configure_deps_greatest_timestamp = $mtime
5522         if $mtime > $configure_deps_greatest_timestamp;
5523     }
5525   scan_autoconf_traces ($configure_ac);
5527   @configure_input_files = sort keys %make_list;
5528   # Set input and output files if not specified by user.
5529   if (! @input_files)
5530     {
5531       @input_files = @configure_input_files;
5532       %output_files = %make_list;
5533     }
5536   if (! $seen_init_automake)
5537     {
5538       err_ac ("no proper invocation of AM_INIT_AUTOMAKE was found.\nYou "
5539               . "should verify that $configure_ac invokes AM_INIT_AUTOMAKE,"
5540               . "\nthat aclocal.m4 is present in the top-level directory,\n"
5541               . "and that aclocal.m4 was recently regenerated "
5542               . "(using aclocal).");
5543     }
5544   else
5545     {
5546       if (! $seen_automake_version)
5547         {
5548           if (-f 'aclocal.m4')
5549             {
5550               error ($seen_init_automake,
5551                      "your implementation of AM_INIT_AUTOMAKE comes from " .
5552                      "an\nold Automake version.  You should recreate " .
5553                      "aclocal.m4\nwith aclocal and run automake again.\n",
5554                      # $? = 63 is used to indicate version mismatch to missing.
5555                      exit_code => 63);
5556             }
5557           else
5558             {
5559               error ($seen_init_automake,
5560                      "no proper implementation of AM_INIT_AUTOMAKE was " .
5561                      "found,\nprobably because aclocal.m4 is missing...\n" .
5562                      "You should run aclocal to create this file, then\n" .
5563                      "run automake again.\n");
5564             }
5565         }
5566     }
5568   locate_aux_dir ();
5570   # Reorder @input_files so that the Makefile that distributes aux
5571   # files is processed last.  This is important because each directory
5572   # can require auxiliary scripts and we should wait until they have
5573   # been installed before distributing them.
5575   # The Makefile.in that distribute the aux files is the one in
5576   # $config_aux_dir or the top-level Makefile.
5577   my $auxdirdist = is_make_dir ($config_aux_dir) ? $config_aux_dir : '.';
5578   my @new_input_files = ();
5579   while (@input_files)
5580     {
5581       my $in = pop @input_files;
5582       my @ins = split (/:/, $output_files{$in});
5583       if (dirname ($ins[0]) eq $auxdirdist)
5584         {
5585           push @new_input_files, $in;
5586           $automake_will_process_aux_dir = 1;
5587         }
5588       else
5589         {
5590           unshift @new_input_files, $in;
5591         }
5592     }
5593   @input_files = @new_input_files;
5595   # If neither the auxdir/Makefile nor the ./Makefile are generated
5596   # by Automake, we won't distribute the aux files anyway.  Assume
5597   # the user know what (s)he does, and pretend we will distribute
5598   # them to disable the error in require_file_internal.
5599   $automake_will_process_aux_dir = 1 if ! is_make_dir ($auxdirdist);
5601   # Look for some files we need.  Always check for these.  This
5602   # check must be done for every run, even those where we are only
5603   # looking at a subdir Makefile.  We must set relative_dir for
5604   # maybe_push_required_file to work.
5605   # Sort the files for stable verbose output.
5606   $relative_dir = '.';
5607   foreach my $file (sort keys %required_aux_file)
5608     {
5609       require_conf_file ($required_aux_file{$file}->get, FOREIGN, $file)
5610     }
5611   err_am "`install.sh' is an anachronism; use `install-sh' instead"
5612     if -f $config_aux_dir . '/install.sh';
5614   # Preserve dist_common for later.
5615   $configure_dist_common = variable_value ('DIST_COMMON') || '';
5619 ################################################################
5621 # Set up for Cygnus mode.
5622 sub check_cygnus
5624   my $cygnus = option 'cygnus';
5625   return unless $cygnus;
5627   set_strictness ('foreign');
5628   set_option ('no-installinfo', $cygnus);
5629   set_option ('no-dependencies', $cygnus);
5630   set_option ('no-dist', $cygnus);
5632   err_ac "`AM_MAINTAINER_MODE' required when --cygnus specified"
5633     if !$seen_maint_mode;
5636 # Do any extra checking for GNU standards.
5637 sub check_gnu_standards
5639   if ($relative_dir eq '.')
5640     {
5641       # In top level (or only) directory.
5642       require_file ("$am_file.am", GNU,
5643                     qw/INSTALL NEWS README AUTHORS ChangeLog/);
5645       # Accept one of these three licenses; default to COPYING.
5646       # Make sure we do not overwrite an existing license.
5647       my $license;
5648       foreach (qw /COPYING COPYING.LIB COPYING.LESSER/)
5649         {
5650           if (-f $_)
5651             {
5652               $license = $_;
5653               last;
5654             }
5655         }
5656       require_file ("$am_file.am", GNU, 'COPYING')
5657         unless $license;
5658     }
5660   for my $opt ('no-installman', 'no-installinfo')
5661     {
5662       msg ('error-gnu', option $opt,
5663            "option `$opt' disallowed by GNU standards")
5664         if option $opt;
5665     }
5668 # Do any extra checking for GNITS standards.
5669 sub check_gnits_standards
5671   if ($relative_dir eq '.')
5672     {
5673       # In top level (or only) directory.
5674       require_file ("$am_file.am", GNITS, 'THANKS');
5675     }
5678 ################################################################
5680 # Functions to handle files of each language.
5682 # Each `lang_X_rewrite($DIRECTORY, $BASE, $EXT)' function follows a
5683 # simple formula: Return value is LANG_SUBDIR if the resulting object
5684 # file should be in a subdir if the source file is, LANG_PROCESS if
5685 # file is to be dealt with, LANG_IGNORE otherwise.
5687 # Much of the actual processing is handled in
5688 # handle_single_transform.  These functions exist so that
5689 # auxiliary information can be recorded for a later cleanup pass.
5690 # Note that the calls to these functions are computed, so don't bother
5691 # searching for their precise names in the source.
5693 # This is just a convenience function that can be used to determine
5694 # when a subdir object should be used.
5695 sub lang_sub_obj
5697     return option 'subdir-objects' ? LANG_SUBDIR : LANG_PROCESS;
5700 # Rewrite a single C source file.
5701 sub lang_c_rewrite
5703   my ($directory, $base, $ext, $nonansi_obj, $have_per_exec_flags, $var) = @_;
5705   if (option 'ansi2knr' && $base =~ /_$/)
5706     {
5707       # FIXME: include line number in error.
5708       err_am "C source file `$base.c' would be deleted by ansi2knr rules";
5709     }
5711   my $r = LANG_PROCESS;
5712   if (option 'subdir-objects')
5713     {
5714       $r = LANG_SUBDIR;
5715       if ($directory && $directory ne '.')
5716         {
5717           $base = $directory . '/' . $base;
5719           # libtool is always able to put the object at the proper place,
5720           # so we do not have to require AM_PROG_CC_C_O when building .lo files.
5721           msg_var ('portability', $var,
5722                    "compiling `$base.c' in subdir requires "
5723                    . "`AM_PROG_CC_C_O' in `$configure_ac'",
5724                    uniq_scope => US_GLOBAL,
5725                    uniq_part => 'AM_PROG_CC_C_O subdir')
5726             unless $seen_cc_c_o || $nonansi_obj eq '.lo';
5727         }
5729       # In this case we already have the directory information, so
5730       # don't add it again.
5731       $de_ansi_files{$base} = '';
5732     }
5733   else
5734     {
5735       $de_ansi_files{$base} = (($directory eq '.' || $directory eq '')
5736                                ? ''
5737                                : "$directory/");
5738     }
5740   if (! $seen_cc_c_o
5741       && $have_per_exec_flags
5742       && ! option 'subdir-objects'
5743       && $nonansi_obj ne '.lo')
5744     {
5745       msg_var ('portability',
5746                $var, "compiling `$base.c' with per-target flags requires "
5747                . "`AM_PROG_CC_C_O' in `$configure_ac'",
5748                uniq_scope => US_GLOBAL,
5749                uniq_part => 'AM_PROG_CC_C_O per-target')
5750     }
5752     return $r;
5755 # Rewrite a single C++ source file.
5756 sub lang_cxx_rewrite
5758     return &lang_sub_obj;
5761 # Rewrite a single header file.
5762 sub lang_header_rewrite
5764     # Header files are simply ignored.
5765     return LANG_IGNORE;
5768 # Rewrite a single Vala source file.
5769 sub lang_vala_rewrite
5771     my ($directory, $base, $ext) = @_;
5773     (my $newext = $ext) =~ s/vala$/c/;
5774     return (LANG_SUBDIR, $newext);
5777 # Rewrite a single yacc file.
5778 sub lang_yacc_rewrite
5780     my ($directory, $base, $ext) = @_;
5782     my $r = &lang_sub_obj;
5783     (my $newext = $ext) =~ tr/y/c/;
5784     return ($r, $newext);
5787 # Rewrite a single yacc++ file.
5788 sub lang_yaccxx_rewrite
5790     my ($directory, $base, $ext) = @_;
5792     my $r = &lang_sub_obj;
5793     (my $newext = $ext) =~ tr/y/c/;
5794     return ($r, $newext);
5797 # Rewrite a single lex file.
5798 sub lang_lex_rewrite
5800     my ($directory, $base, $ext) = @_;
5802     my $r = &lang_sub_obj;
5803     (my $newext = $ext) =~ tr/l/c/;
5804     return ($r, $newext);
5807 # Rewrite a single lex++ file.
5808 sub lang_lexxx_rewrite
5810     my ($directory, $base, $ext) = @_;
5812     my $r = &lang_sub_obj;
5813     (my $newext = $ext) =~ tr/l/c/;
5814     return ($r, $newext);
5817 # Rewrite a single assembly file.
5818 sub lang_asm_rewrite
5820     return &lang_sub_obj;
5823 # Rewrite a single preprocessed assembly file.
5824 sub lang_cppasm_rewrite
5826     return &lang_sub_obj;
5829 # Rewrite a single Fortran 77 file.
5830 sub lang_f77_rewrite
5832     return &lang_sub_obj;
5835 # Rewrite a single Fortran file.
5836 sub lang_fc_rewrite
5838     return &lang_sub_obj;
5841 # Rewrite a single preprocessed Fortran file.
5842 sub lang_ppfc_rewrite
5844     return &lang_sub_obj;
5847 # Rewrite a single preprocessed Fortran 77 file.
5848 sub lang_ppf77_rewrite
5850     return &lang_sub_obj;
5853 # Rewrite a single ratfor file.
5854 sub lang_ratfor_rewrite
5856     return &lang_sub_obj;
5859 # Rewrite a single Objective C file.
5860 sub lang_objc_rewrite
5862     return &lang_sub_obj;
5865 # Rewrite a single Unified Parallel C file.
5866 sub lang_upc_rewrite
5868     return &lang_sub_obj;
5871 # Rewrite a single Java file.
5872 sub lang_java_rewrite
5874     return LANG_SUBDIR;
5877 # The lang_X_finish functions are called after all source file
5878 # processing is done.  Each should handle defining rules for the
5879 # language, etc.  A finish function is only called if a source file of
5880 # the appropriate type has been seen.
5882 sub lang_c_finish
5884     # Push all libobjs files onto de_ansi_files.  We actually only
5885     # push files which exist in the current directory, and which are
5886     # genuine source files.
5887     foreach my $file (keys %libsources)
5888     {
5889         if ($file =~ /^(.*)\.[cly]$/ && -f "$relative_dir/$file")
5890         {
5891             $de_ansi_files{$1} = ''
5892         }
5893     }
5895     if (option 'ansi2knr' && keys %de_ansi_files)
5896     {
5897         # Make all _.c files depend on their corresponding .c files.
5898         my @objects;
5899         foreach my $base (sort keys %de_ansi_files)
5900         {
5901             # Each _.c file must depend on ansi2knr; otherwise it
5902             # might be used in a parallel build before it is built.
5903             # We need to support files in the srcdir and in the build
5904             # dir (because these files might be auto-generated.  But
5905             # we can't use $< -- some makes only define $< during a
5906             # suffix rule.
5907             my $ansfile = $de_ansi_files{$base} . $base . '.c';
5908             $output_rules .= ($base . "_.c: $ansfile \$(ANSI2KNR)\n\t"
5909                               . '$(CPP) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) '
5910                               . '`if test -f $(srcdir)/' . $ansfile
5911                               . '; then echo $(srcdir)/' . $ansfile
5912                               . '; else echo ' . $ansfile . '; fi` '
5913                               . "| sed 's/^# \\([0-9]\\)/#line \\1/' "
5914                               . '| $(ANSI2KNR) > $@'
5915                               # If ansi2knr fails then we shouldn't
5916                               # create the _.c file
5917                               . " || rm -f \$\@\n");
5918             push (@objects, $base . '_.$(OBJEXT)');
5919             push (@objects, $base . '_.lo')
5920               if var ('LIBTOOL');
5922             # Explicitly clean the _.c files if they are in a
5923             # subdirectory. (In the current directory they get erased
5924             # by a `rm -f *_.c' rule.)
5925             $clean_files{$base . '_.c'} = MOSTLY_CLEAN
5926               if dirname ($base) ne '.';
5927         }
5929         # Make all _.o (and _.lo) files depend on ansi2knr.
5930         # Use a sneaky little hack to make it print nicely.
5931         &pretty_print_rule ('', '', @objects, ':', '$(ANSI2KNR)');
5932     }
5935 sub lang_vala_finish_target ($$)
5937   my ($self, $name) = @_;
5939   my $derived = canonicalize ($name);
5940   my $varname = $derived . '_SOURCES';
5941   my $var = var ($varname);
5943   if ($var)
5944     {
5945       foreach my $file ($var->value_as_list_recursive)
5946         {
5947           $output_rules .= "$file: ${derived}_vala.stamp\n".
5948             "\t\@if test -f \$@; then :; else \\\n".
5949             "\t  rm -f ${derived}_vala.stamp; \\\n".
5950             "\t  \$(MAKE) \$(AM_MAKEFLAGS) ${derived}_vala.stamp; \\\n".
5951             "\tfi\n"
5952             if $file =~ s/(.*)\.vala$/$1.c/;
5953         }
5954     }
5956   my $compile = $self->compile;
5958   # Rewrite each occurrence of `AM_$flag' in the compile
5959   # rule into `${derived}_$flag' if it exists.
5960   for my $flag (@{$self->flags})
5961     {
5962       my $val = "${derived}_$flag";
5963       $compile =~ s/\(AM_$flag\)/\($val\)/
5964         if set_seen ($val);
5965     }
5967   my $dirname = dirname ($name);
5969   # Only generate C code, do not run C compiler
5970   $compile .= " -C";
5972   my $verbose = verbose_flag ('VALAC');
5973   my $silent = silent_flag ();
5975   $output_rules .=
5976     "${derived}_vala.stamp: \$(${derived}_SOURCES)\n".
5977     "\t${verbose}${compile} \$(${derived}_SOURCES)\n".
5978     "\t${silent}touch \$@\n";
5980   push_dist_common ("${derived}_vala.stamp");
5982   $clean_files{"${derived}_vala.stamp"} = MAINTAINER_CLEAN;
5985 # Add output rules to invoke valac and create stamp file as a witness
5986 # to handle multiple outputs. This function is called after all source
5987 # file processing is done.
5988 sub lang_vala_finish
5990   my ($self) = @_;
5992   foreach my $prog (keys %known_programs)
5993     {
5994       lang_vala_finish_target ($self, $prog);
5995     }
5997   while (my ($name) = each %known_libraries)
5998     {
5999       lang_vala_finish_target ($self, $name);
6000     }
6003 # The built .c files should be cleaned only on maintainer-clean
6004 # as the .c files are distributed. This function is called for each
6005 # .vala source file.
6006 sub lang_vala_target_hook
6008   my ($self, $aggregate, $output, $input, %transform) = @_;
6010   $clean_files{$output} = MAINTAINER_CLEAN;
6013 # This is a yacc helper which is called whenever we have decided to
6014 # compile a yacc file.
6015 sub lang_yacc_target_hook
6017     my ($self, $aggregate, $output, $input, %transform) = @_;
6019     my $flag = $aggregate . "_YFLAGS";
6020     my $flagvar = var $flag;
6021     my $YFLAGSvar = var 'YFLAGS';
6022     if (($flagvar && $flagvar->variable_value =~ /$DASH_D_PATTERN/o)
6023         || ($YFLAGSvar && $YFLAGSvar->variable_value =~ /$DASH_D_PATTERN/o))
6024     {
6025         (my $output_base = $output) =~ s/$KNOWN_EXTENSIONS_PATTERN$//;
6026         my $header = $output_base . '.h';
6028         # Found a `-d' that applies to the compilation of this file.
6029         # Add a dependency for the generated header file, and arrange
6030         # for that file to be included in the distribution.
6031         foreach my $cond (Automake::Rule::define (${header}, 'internal',
6032                                                   RULE_AUTOMAKE, TRUE,
6033                                                   INTERNAL))
6034           {
6035             my $condstr = $cond->subst_string;
6036             $output_rules .=
6037               "$condstr${header}: $output\n"
6038               # Recover from removal of $header
6039               . "$condstr\t\@if test ! -f \$@; then \\\n"
6040               . "$condstr\t  rm -f $output; \\\n"
6041               . "$condstr\t  \$(MAKE) \$(AM_MAKEFLAGS) $output; \\\n"
6042               . "$condstr\telse :; fi\n";
6043           }
6044         # Distribute the generated file, unless its .y source was
6045         # listed in a nodist_ variable.  (&handle_source_transform
6046         # will set DIST_SOURCE.)
6047         &push_dist_common ($header)
6048           if $transform{'DIST_SOURCE'};
6050         # If the files are built in the build directory, then we want
6051         # to remove them with `make clean'.  If they are in srcdir
6052         # they shouldn't be touched.  However, we can't determine this
6053         # statically, and the GNU rules say that yacc/lex output files
6054         # should be removed by maintainer-clean.  So that's what we
6055         # do.
6056         $clean_files{$header} = MAINTAINER_CLEAN;
6057     }
6058     # Erase $OUTPUT on `make maintainer-clean' (by GNU standards).
6059     # See the comment above for $HEADER.
6060     $clean_files{$output} = MAINTAINER_CLEAN;
6063 # This is a lex helper which is called whenever we have decided to
6064 # compile a lex file.
6065 sub lang_lex_target_hook
6067     my ($self, $aggregate, $output, $input) = @_;
6068     # If the files are built in the build directory, then we want to
6069     # remove them with `make clean'.  If they are in srcdir they
6070     # shouldn't be touched.  However, we can't determine this
6071     # statically, and the GNU rules say that yacc/lex output files
6072     # should be removed by maintainer-clean.  So that's what we do.
6073     $clean_files{$output} = MAINTAINER_CLEAN;
6076 # This is a helper for both lex and yacc.
6077 sub yacc_lex_finish_helper
6079   return if defined $language_scratch{'lex-yacc-done'};
6080   $language_scratch{'lex-yacc-done'} = 1;
6082   # FIXME: for now, no line number.
6083   require_conf_file ($configure_ac, FOREIGN, 'ylwrap');
6084   &define_variable ('YLWRAP', "$am_config_aux_dir/ylwrap", INTERNAL);
6087 sub lang_yacc_finish
6089   return if defined $language_scratch{'yacc-done'};
6090   $language_scratch{'yacc-done'} = 1;
6092   reject_var 'YACCFLAGS', "`YACCFLAGS' obsolete; use `YFLAGS' instead";
6094   yacc_lex_finish_helper;
6098 sub lang_lex_finish
6100   return if defined $language_scratch{'lex-done'};
6101   $language_scratch{'lex-done'} = 1;
6103   yacc_lex_finish_helper;
6107 # Given a hash table of linker names, pick the name that has the most
6108 # precedence.  This is lame, but something has to have global
6109 # knowledge in order to eliminate the conflict.  Add more linkers as
6110 # required.
6111 sub resolve_linker
6113     my (%linkers) = @_;
6115     foreach my $l (qw(GCJLINK CXXLINK F77LINK FCLINK OBJCLINK UPCLINK))
6116     {
6117         return $l if defined $linkers{$l};
6118     }
6119     return 'LINK';
6122 # Called to indicate that an extension was used.
6123 sub saw_extension
6125     my ($ext) = @_;
6126     if (! defined $extension_seen{$ext})
6127     {
6128         $extension_seen{$ext} = 1;
6129     }
6130     else
6131     {
6132         ++$extension_seen{$ext};
6133     }
6136 # Return the number of files seen for a given language.  Knows about
6137 # special cases we care about.  FIXME: this is hideous.  We need
6138 # something that involves real language objects.  For instance yacc
6139 # and yaccxx could both derive from a common yacc class which would
6140 # know about the strange ylwrap requirement.  (Or better yet we could
6141 # just not support legacy yacc!)
6142 sub count_files_for_language
6144     my ($name) = @_;
6146     my @names;
6147     if ($name eq 'yacc' || $name eq 'yaccxx')
6148     {
6149         @names = ('yacc', 'yaccxx');
6150     }
6151     elsif ($name eq 'lex' || $name eq 'lexxx')
6152     {
6153         @names = ('lex', 'lexxx');
6154     }
6155     else
6156     {
6157         @names = ($name);
6158     }
6160     my $r = 0;
6161     foreach $name (@names)
6162     {
6163         my $lang = $languages{$name};
6164         foreach my $ext (@{$lang->extensions})
6165         {
6166             $r += $extension_seen{$ext}
6167                 if defined $extension_seen{$ext};
6168         }
6169     }
6171     return $r
6174 # Called to ask whether source files have been seen . If HEADERS is 1,
6175 # headers can be included.
6176 sub saw_sources_p
6178     my ($headers) = @_;
6180     # count all the sources
6181     my $count = 0;
6182     foreach my $val (values %extension_seen)
6183     {
6184         $count += $val;
6185     }
6187     if (!$headers)
6188     {
6189         $count -= count_files_for_language ('header');
6190     }
6192     return $count > 0;
6196 # register_language (%ATTRIBUTE)
6197 # ------------------------------
6198 # Register a single language.
6199 # Each %ATTRIBUTE is of the form ATTRIBUTE => VALUE.
6200 sub register_language (%)
6202   my (%option) = @_;
6204   # Set the defaults.
6205   $option{'ansi'} = 0
6206     unless defined $option{'ansi'};
6207   $option{'autodep'} = 'no'
6208     unless defined $option{'autodep'};
6209   $option{'linker'} = ''
6210     unless defined $option{'linker'};
6211   $option{'flags'} = []
6212     unless defined $option{'flags'};
6213   $option{'output_extensions'} = sub { return ( '.$(OBJEXT)', '.lo' ) }
6214     unless defined $option{'output_extensions'};
6215   $option{'nodist_specific'} = 0
6216     unless defined $option{'nodist_specific'};
6218   my $lang = new Language (%option);
6220   # Fill indexes.
6221   $extension_map{$_} = $lang->name foreach @{$lang->extensions};
6222   $languages{$lang->name} = $lang;
6223   my $link = $lang->linker;
6224   if ($link)
6225     {
6226       if (exists $link_languages{$link})
6227         {
6228           prog_error ("`$link' has different definitions in "
6229                       . $lang->name . " and " . $link_languages{$link}->name)
6230             if $lang->link ne $link_languages{$link}->link;
6231         }
6232       else
6233         {
6234           $link_languages{$link} = $lang;
6235         }
6236     }
6238   # Update the pattern of known extensions.
6239   accept_extensions (@{$lang->extensions});
6241   # Upate the $suffix_rule map.
6242   foreach my $suffix (@{$lang->extensions})
6243     {
6244       foreach my $dest (&{$lang->output_extensions} ($suffix))
6245         {
6246           register_suffix_rule (INTERNAL, $suffix, $dest);
6247         }
6248     }
6251 # derive_suffix ($EXT, $OBJ)
6252 # --------------------------
6253 # This function is used to find a path from a user-specified suffix $EXT
6254 # to $OBJ or to some other suffix we recognize internally, e.g. `cc'.
6255 sub derive_suffix ($$)
6257   my ($source_ext, $obj) = @_;
6259   while (! $extension_map{$source_ext}
6260          && $source_ext ne $obj
6261          && exists $suffix_rules->{$source_ext}
6262          && exists $suffix_rules->{$source_ext}{$obj})
6263     {
6264       $source_ext = $suffix_rules->{$source_ext}{$obj}[0];
6265     }
6267   return $source_ext;
6271 ################################################################
6273 # Pretty-print something and append to output_rules.
6274 sub pretty_print_rule
6276     $output_rules .= &makefile_wrap (@_);
6280 ################################################################
6283 ## -------------------------------- ##
6284 ## Handling the conditional stack.  ##
6285 ## -------------------------------- ##
6288 # $STRING
6289 # make_conditional_string ($NEGATE, $COND)
6290 # ----------------------------------------
6291 sub make_conditional_string ($$)
6293   my ($negate, $cond) = @_;
6294   $cond = "${cond}_TRUE"
6295     unless $cond =~ /^TRUE|FALSE$/;
6296   $cond = Automake::Condition::conditional_negate ($cond)
6297     if $negate;
6298   return $cond;
6302 my %_am_macro_for_cond =
6303   (
6304   AMDEP => "one of the compiler tests\n"
6305            . "    AC_PROG_CC, AC_PROG_CXX, AC_PROG_CXX, AC_PROG_OBJC,\n"
6306            . "    AM_PROG_AS, AM_PROG_GCJ, AM_PROG_UPC",
6307   am__fastdepCC => 'AC_PROG_CC',
6308   am__fastdepCCAS => 'AM_PROG_AS',
6309   am__fastdepCXX => 'AC_PROG_CXX',
6310   am__fastdepGCJ => 'AM_PROG_GCJ',
6311   am__fastdepOBJC => 'AC_PROG_OBJC',
6312   am__fastdepUPC => 'AM_PROG_UPC'
6313   );
6315 # $COND
6316 # cond_stack_if ($NEGATE, $COND, $WHERE)
6317 # --------------------------------------
6318 sub cond_stack_if ($$$)
6320   my ($negate, $cond, $where) = @_;
6322   if (! $configure_cond{$cond} && $cond !~ /^TRUE|FALSE$/)
6323     {
6324       my $text = "$cond does not appear in AM_CONDITIONAL";
6325       my $scope = US_LOCAL;
6326       if (exists $_am_macro_for_cond{$cond})
6327         {
6328           my $mac = $_am_macro_for_cond{$cond};
6329           $text .= "\n  The usual way to define `$cond' is to add ";
6330           $text .= ($mac =~ / /) ? $mac : "`$mac'";
6331           $text .= "\n  to `$configure_ac' and run `aclocal' and `autoconf' again.";
6332           # These warnings appear in Automake files (depend2.am),
6333           # so there is no need to display them more than once:
6334           $scope = US_GLOBAL;
6335         }
6336       error $where, $text, uniq_scope => $scope;
6337     }
6339   push (@cond_stack, make_conditional_string ($negate, $cond));
6341   return new Automake::Condition (@cond_stack);
6345 # $COND
6346 # cond_stack_else ($NEGATE, $COND, $WHERE)
6347 # ----------------------------------------
6348 sub cond_stack_else ($$$)
6350   my ($negate, $cond, $where) = @_;
6352   if (! @cond_stack)
6353     {
6354       error $where, "else without if";
6355       return FALSE;
6356     }
6358   $cond_stack[$#cond_stack] =
6359     Automake::Condition::conditional_negate ($cond_stack[$#cond_stack]);
6361   # If $COND is given, check against it.
6362   if (defined $cond)
6363     {
6364       $cond = make_conditional_string ($negate, $cond);
6366       error ($where, "else reminder ($negate$cond) incompatible with "
6367              . "current conditional: $cond_stack[$#cond_stack]")
6368         if $cond_stack[$#cond_stack] ne $cond;
6369     }
6371   return new Automake::Condition (@cond_stack);
6375 # $COND
6376 # cond_stack_endif ($NEGATE, $COND, $WHERE)
6377 # -----------------------------------------
6378 sub cond_stack_endif ($$$)
6380   my ($negate, $cond, $where) = @_;
6381   my $old_cond;
6383   if (! @cond_stack)
6384     {
6385       error $where, "endif without if";
6386       return TRUE;
6387     }
6389   # If $COND is given, check against it.
6390   if (defined $cond)
6391     {
6392       $cond = make_conditional_string ($negate, $cond);
6394       error ($where, "endif reminder ($negate$cond) incompatible with "
6395              . "current conditional: $cond_stack[$#cond_stack]")
6396         if $cond_stack[$#cond_stack] ne $cond;
6397     }
6399   pop @cond_stack;
6401   return new Automake::Condition (@cond_stack);
6408 ## ------------------------ ##
6409 ## Handling the variables.  ##
6410 ## ------------------------ ##
6413 # &define_pretty_variable ($VAR, $COND, $WHERE, @VALUE)
6414 # -----------------------------------------------------
6415 # Like define_variable, but the value is a list, and the variable may
6416 # be defined conditionally.  The second argument is the condition
6417 # under which the value should be defined; this should be the empty
6418 # string to define the variable unconditionally.  The third argument
6419 # is a list holding the values to use for the variable.  The value is
6420 # pretty printed in the output file.
6421 sub define_pretty_variable ($$$@)
6423     my ($var, $cond, $where, @value) = @_;
6425     if (! vardef ($var, $cond))
6426     {
6427         Automake::Variable::define ($var, VAR_AUTOMAKE, '', $cond, "@value",
6428                                     '', $where, VAR_PRETTY);
6429         rvar ($var)->rdef ($cond)->set_seen;
6430     }
6434 # define_variable ($VAR, $VALUE, $WHERE)
6435 # --------------------------------------
6436 # Define a new Automake Makefile variable VAR to VALUE, but only if
6437 # not already defined.
6438 sub define_variable ($$$)
6440     my ($var, $value, $where) = @_;
6441     define_pretty_variable ($var, TRUE, $where, $value);
6445 # define_files_variable ($VAR, \@BASENAME, $EXTENSION, $WHERE)
6446 # -----------------------------------------------------------
6447 # Define the $VAR which content is the list of file names composed of
6448 # a @BASENAME and the $EXTENSION.
6449 sub define_files_variable ($\@$$)
6451   my ($var, $basename, $extension, $where) = @_;
6452   define_variable ($var,
6453                    join (' ', map { "$_.$extension" } @$basename),
6454                    $where);
6458 # Like define_variable, but define a variable to be the configure
6459 # substitution by the same name.
6460 sub define_configure_variable ($)
6462   my ($var) = @_;
6464   my $pretty = VAR_ASIS;
6465   my $owner = VAR_CONFIGURE;
6467   # Some variables we do not want to output.  For instance it
6468   # would be a bad idea to output `U = @U@` when `@U@` can be
6469   # substituted as `\`.
6470   $pretty = VAR_SILENT if exists $ignored_configure_vars{$var};
6472   # ANSI2KNR is a variable that Automake wants to redefine, so
6473   # it must be owned by Automake.  (It is also used as a proof
6474   # that AM_C_PROTOTYPES has been run, that's why we do not simply
6475   # omit the AC_SUBST.)
6476   $owner = VAR_AUTOMAKE if $var eq 'ANSI2KNR';
6478   Automake::Variable::define ($var, $owner, '', TRUE, subst $var,
6479                               '', $configure_vars{$var}, $pretty);
6483 # define_compiler_variable ($LANG)
6484 # --------------------------------
6485 # Define a compiler variable.  We also handle defining the `LT'
6486 # version of the command when using libtool.
6487 sub define_compiler_variable ($)
6489     my ($lang) = @_;
6491     my ($var, $value) = ($lang->compiler, $lang->compile);
6492     my $libtool_tag = '';
6493     $libtool_tag = '--tag=' . $lang->libtool_tag . ' '
6494       if $lang->libtool_tag && exists $libtool_tags{$lang->libtool_tag};
6495     &define_variable ($var, $value, INTERNAL);
6496     if (var ('LIBTOOL'))
6497       {
6498         my $verbose = define_verbose_libtool ();
6499         &define_variable ("LT$var",
6500                           "\$(LIBTOOL) $verbose $libtool_tag\$(AM_LIBTOOLFLAGS) "
6501                           . "\$(LIBTOOLFLAGS) --mode=compile $value",
6502                           INTERNAL);
6503       }
6504     define_verbose_tagvar ($lang->ccer || 'GEN');
6508 # define_linker_variable ($LANG)
6509 # ------------------------------
6510 # Define linker variables.
6511 sub define_linker_variable ($)
6513     my ($lang) = @_;
6515     my $libtool_tag = '';
6516     $libtool_tag = '--tag=' . $lang->libtool_tag . ' '
6517       if $lang->libtool_tag && exists $libtool_tags{$lang->libtool_tag};
6518     # CCLD = $(CC).
6519     &define_variable ($lang->lder, $lang->ld, INTERNAL);
6520     # CCLINK = $(CCLD) blah blah...
6521     my $link = '';
6522     if (var ('LIBTOOL'))
6523       {
6524         my $verbose = define_verbose_libtool ();
6525         $link = "\$(LIBTOOL) $verbose $libtool_tag\$(AM_LIBTOOLFLAGS) "
6526                 . "\$(LIBTOOLFLAGS) --mode=link ";
6527       }
6528     &define_variable ($lang->linker, $link . $lang->link, INTERNAL);
6529     &define_variable ($lang->compiler,  $lang);
6530     &define_verbose_tagvar ($lang->lder || 'GEN');
6533 sub define_per_target_linker_variable ($$)
6535   my ($linker, $target) = @_;
6537   # If the user wrote a custom link command, we don't define ours.
6538   return "${target}_LINK"
6539     if set_seen "${target}_LINK";
6541   my $xlink = $linker ? $linker : 'LINK';
6543   my $lang = $link_languages{$xlink};
6544   prog_error "Unknown language for linker variable `$xlink'"
6545     unless $lang;
6547   my $link_command = $lang->link;
6548   if (var 'LIBTOOL')
6549     {
6550       my $libtool_tag = '';
6551       $libtool_tag = '--tag=' . $lang->libtool_tag . ' '
6552         if $lang->libtool_tag && exists $libtool_tags{$lang->libtool_tag};
6554       my $verbose = define_verbose_libtool ();
6555       $link_command =
6556         "\$(LIBTOOL) $verbose $libtool_tag\$(AM_LIBTOOLFLAGS) \$(LIBTOOLFLAGS) "
6557         . "--mode=link " . $link_command;
6558     }
6560   # Rewrite each occurrence of `AM_$flag' in the link
6561   # command into `${derived}_$flag' if it exists.
6562   my $orig_command = $link_command;
6563   my @flags = (@{$lang->flags}, 'LDFLAGS');
6564   push @flags, 'LIBTOOLFLAGS' if var 'LIBTOOL';
6565   for my $flag (@flags)
6566     {
6567       my $val = "${target}_$flag";
6568       $link_command =~ s/\(AM_$flag\)/\($val\)/
6569         if set_seen ($val);
6570     }
6572   # If the computed command is the same as the generic command, use
6573   # the command linker variable.
6574   return ($lang->linker, $lang->lder)
6575     if $link_command eq $orig_command;
6577   &define_variable ("${target}_LINK", $link_command, INTERNAL);
6578   return ("${target}_LINK", $lang->lder);
6581 ################################################################
6583 # &check_trailing_slash ($WHERE, $LINE)
6584 # --------------------------------------
6585 # Return 1 iff $LINE ends with a slash.
6586 # Might modify $LINE.
6587 sub check_trailing_slash ($\$)
6589   my ($where, $line) = @_;
6591   # Ignore `##' lines.
6592   return 0 if $$line =~ /$IGNORE_PATTERN/o;
6594   # Catch and fix a common error.
6595   msg "syntax", $where, "whitespace following trailing backslash"
6596     if $$line =~ s/\\\s+\n$/\\\n/;
6598   return $$line =~ /\\$/;
6602 # &read_am_file ($AMFILE, $WHERE)
6603 # -------------------------------
6604 # Read Makefile.am and set up %contents.  Simultaneously copy lines
6605 # from Makefile.am into $output_trailer, or define variables as
6606 # appropriate.  NOTE we put rules in the trailer section.  We want
6607 # user rules to come after our generated stuff.
6608 sub read_am_file ($$)
6610     my ($amfile, $where) = @_;
6612     my $am_file = new Automake::XFile ("< $amfile");
6613     verb "reading $amfile";
6615     # Keep track of the youngest output dependency.
6616     my $mtime = mtime $amfile;
6617     $output_deps_greatest_timestamp = $mtime
6618       if $mtime > $output_deps_greatest_timestamp;
6620     my $spacing = '';
6621     my $comment = '';
6622     my $blank = 0;
6623     my $saw_bk = 0;
6624     my $var_look = VAR_ASIS;
6626     use constant IN_VAR_DEF => 0;
6627     use constant IN_RULE_DEF => 1;
6628     use constant IN_COMMENT => 2;
6629     my $prev_state = IN_RULE_DEF;
6631     while ($_ = $am_file->getline)
6632     {
6633         $where->set ("$amfile:$.");
6634         if (/$IGNORE_PATTERN/o)
6635         {
6636             # Merely delete comments beginning with two hashes.
6637         }
6638         elsif (/$WHITE_PATTERN/o)
6639         {
6640             error $where, "blank line following trailing backslash"
6641               if $saw_bk;
6642             # Stick a single white line before the incoming macro or rule.
6643             $spacing = "\n";
6644             $blank = 1;
6645             # Flush all comments seen so far.
6646             if ($comment ne '')
6647             {
6648                 $output_vars .= $comment;
6649                 $comment = '';
6650             }
6651         }
6652         elsif (/$COMMENT_PATTERN/o)
6653         {
6654             # Stick comments before the incoming macro or rule.  Make
6655             # sure a blank line precedes the first block of comments.
6656             $spacing = "\n" unless $blank;
6657             $blank = 1;
6658             $comment .= $spacing . $_;
6659             $spacing = '';
6660             $prev_state = IN_COMMENT;
6661         }
6662         else
6663         {
6664             last;
6665         }
6666         $saw_bk = check_trailing_slash ($where, $_);
6667     }
6669     # We save the conditional stack on entry, and then check to make
6670     # sure it is the same on exit.  This lets us conditionally include
6671     # other files.
6672     my @saved_cond_stack = @cond_stack;
6673     my $cond = new Automake::Condition (@cond_stack);
6675     my $last_var_name = '';
6676     my $last_var_type = '';
6677     my $last_var_value = '';
6678     my $last_where;
6679     # FIXME: shouldn't use $_ in this loop; it is too big.
6680     while ($_)
6681     {
6682         $where->set ("$amfile:$.");
6684         # Make sure the line is \n-terminated.
6685         chomp;
6686         $_ .= "\n";
6688         # Don't look at MAINTAINER_MODE_TRUE here.  That shouldn't be
6689         # used by users.  @MAINT@ is an anachronism now.
6690         $_ =~ s/\@MAINT\@//g
6691             unless $seen_maint_mode;
6693         my $new_saw_bk = check_trailing_slash ($where, $_);
6695         if (/$IGNORE_PATTERN/o)
6696         {
6697             # Merely delete comments beginning with two hashes.
6699             # Keep any backslash from the previous line.
6700             $new_saw_bk = $saw_bk;
6701         }
6702         elsif (/$WHITE_PATTERN/o)
6703         {
6704             # Stick a single white line before the incoming macro or rule.
6705             $spacing = "\n";
6706             error $where, "blank line following trailing backslash"
6707               if $saw_bk;
6708         }
6709         elsif (/$COMMENT_PATTERN/o)
6710         {
6711             error $where, "comment following trailing backslash"
6712               if $saw_bk && $comment eq '';
6714             # Stick comments before the incoming macro or rule.
6715             $comment .= $spacing . $_;
6716             $spacing = '';
6717             $prev_state = IN_COMMENT;
6718         }
6719         elsif ($saw_bk)
6720         {
6721             if ($prev_state == IN_RULE_DEF)
6722             {
6723               my $cond = new Automake::Condition @cond_stack;
6724               $output_trailer .= $cond->subst_string;
6725               $output_trailer .= $_;
6726             }
6727             elsif ($prev_state == IN_COMMENT)
6728             {
6729                 # If the line doesn't start with a `#', add it.
6730                 # We do this because a continued comment like
6731                 #   # A = foo \
6732                 #         bar \
6733                 #         baz
6734                 # is not portable.  BSD make doesn't honor
6735                 # escaped newlines in comments.
6736                 s/^#?/#/;
6737                 $comment .= $spacing . $_;
6738             }
6739             else # $prev_state == IN_VAR_DEF
6740             {
6741               $last_var_value .= ' '
6742                 unless $last_var_value =~ /\s$/;
6743               $last_var_value .= $_;
6745               if (!/\\$/)
6746                 {
6747                   Automake::Variable::define ($last_var_name, VAR_MAKEFILE,
6748                                               $last_var_type, $cond,
6749                                               $last_var_value, $comment,
6750                                               $last_where, VAR_ASIS)
6751                     if $cond != FALSE;
6752                   $comment = $spacing = '';
6753                 }
6754             }
6755         }
6757         elsif (/$IF_PATTERN/o)
6758           {
6759             $cond = cond_stack_if ($1, $2, $where);
6760           }
6761         elsif (/$ELSE_PATTERN/o)
6762           {
6763             $cond = cond_stack_else ($1, $2, $where);
6764           }
6765         elsif (/$ENDIF_PATTERN/o)
6766           {
6767             $cond = cond_stack_endif ($1, $2, $where);
6768           }
6770         elsif (/$RULE_PATTERN/o)
6771         {
6772             # Found a rule.
6773             $prev_state = IN_RULE_DEF;
6775             # For now we have to output all definitions of user rules
6776             # and can't diagnose duplicates (see the comment in
6777             # Automake::Rule::define). So we go on and ignore the return value.
6778             Automake::Rule::define ($1, $amfile, RULE_USER, $cond, $where);
6780             check_variable_expansions ($_, $where);
6782             $output_trailer .= $comment . $spacing;
6783             my $cond = new Automake::Condition @cond_stack;
6784             $output_trailer .= $cond->subst_string;
6785             $output_trailer .= $_;
6786             $comment = $spacing = '';
6787         }
6788         elsif (/$ASSIGNMENT_PATTERN/o)
6789         {
6790             # Found a macro definition.
6791             $prev_state = IN_VAR_DEF;
6792             $last_var_name = $1;
6793             $last_var_type = $2;
6794             $last_var_value = $3;
6795             $last_where = $where->clone;
6796             if ($3 ne '' && substr ($3, -1) eq "\\")
6797               {
6798                 # We preserve the `\' because otherwise the long lines
6799                 # that are generated will be truncated by broken
6800                 # `sed's.
6801                 $last_var_value = $3 . "\n";
6802               }
6803             # Normally we try to output variable definitions in the
6804             # same format they were input.  However, POSIX compliant
6805             # systems are not required to support lines longer than
6806             # 2048 bytes (most notably, some sed implementation are
6807             # limited to 4000 bytes, and sed is used by config.status
6808             # to rewrite Makefile.in into Makefile).  Moreover nobody
6809             # would really write such long lines by hand since it is
6810             # hardly maintainable.  So if a line is longer that 1000
6811             # bytes (an arbitrary limit), assume it has been
6812             # automatically generated by some tools, and flatten the
6813             # variable definition.  Otherwise, keep the variable as it
6814             # as been input.
6815             $var_look = VAR_PRETTY if length ($last_var_value) >= 1000;
6817             if (!/\\$/)
6818               {
6819                 Automake::Variable::define ($last_var_name, VAR_MAKEFILE,
6820                                             $last_var_type, $cond,
6821                                             $last_var_value, $comment,
6822                                             $last_where, $var_look)
6823                   if $cond != FALSE;
6824                 $comment = $spacing = '';
6825                 $var_look = VAR_ASIS;
6826               }
6827         }
6828         elsif (/$INCLUDE_PATTERN/o)
6829         {
6830             my $path = $1;
6832             if ($path =~ s/^\$\(top_srcdir\)\///)
6833               {
6834                 push (@include_stack, "\$\(top_srcdir\)/$path");
6835                 # Distribute any included file.
6837                 # Always use the $(top_srcdir) prefix in DIST_COMMON,
6838                 # otherwise OSF make will implicitly copy the included
6839                 # file in the build tree during `make distdir' to satisfy
6840                 # the dependency.
6841                 # (subdircond2.test and subdircond3.test will fail.)
6842                 push_dist_common ("\$\(top_srcdir\)/$path");
6843               }
6844             else
6845               {
6846                 $path =~ s/\$\(srcdir\)\///;
6847                 push (@include_stack, "\$\(srcdir\)/$path");
6848                 # Always use the $(srcdir) prefix in DIST_COMMON,
6849                 # otherwise OSF make will implicitly copy the included
6850                 # file in the build tree during `make distdir' to satisfy
6851                 # the dependency.
6852                 # (subdircond2.test and subdircond3.test will fail.)
6853                 push_dist_common ("\$\(srcdir\)/$path");
6854                 $path = $relative_dir . "/" . $path if $relative_dir ne '.';
6855               }
6856             $where->push_context ("`$path' included from here");
6857             &read_am_file ($path, $where);
6858             $where->pop_context;
6859         }
6860         else
6861         {
6862             # This isn't an error; it is probably a continued rule.
6863             # In fact, this is what we assume.
6864             $prev_state = IN_RULE_DEF;
6865             check_variable_expansions ($_, $where);
6866             $output_trailer .= $comment . $spacing;
6867             my $cond = new Automake::Condition @cond_stack;
6868             $output_trailer .= $cond->subst_string;
6869             $output_trailer .= $_;
6870             $comment = $spacing = '';
6871             error $where, "`#' comment at start of rule is unportable"
6872               if $_ =~ /^\t\s*\#/;
6873         }
6875         $saw_bk = $new_saw_bk;
6876         $_ = $am_file->getline;
6877     }
6879     $output_trailer .= $comment;
6881     error ($where, "trailing backslash on last line")
6882       if $saw_bk;
6884     error ($where, (@cond_stack ? "unterminated conditionals: @cond_stack"
6885                     : "too many conditionals closed in include file"))
6886       if "@saved_cond_stack" ne "@cond_stack";
6890 # define_standard_variables ()
6891 # ----------------------------
6892 # A helper for read_main_am_file which initializes configure variables
6893 # and variables from header-vars.am.
6894 sub define_standard_variables
6896   my $saved_output_vars = $output_vars;
6897   my ($comments, undef, $rules) =
6898     file_contents_internal (1, "$libdir/am/header-vars.am",
6899                             new Automake::Location);
6901   foreach my $var (sort keys %configure_vars)
6902     {
6903       &define_configure_variable ($var);
6904     }
6906   $output_vars .= $comments . $rules;
6909 # Read main am file.
6910 sub read_main_am_file
6912     my ($amfile) = @_;
6914     # This supports the strange variable tricks we are about to play.
6915     prog_error (macros_dump () . "variable defined before read_main_am_file")
6916       if (scalar (variables) > 0);
6918     # Generate copyright header for generated Makefile.in.
6919     # We do discard the output of predefined variables, handled below.
6920     $output_vars = ("# $in_file_name generated by automake "
6921                    . $VERSION . " from $am_file_name.\n");
6922     $output_vars .= '# ' . subst ('configure_input') . "\n";
6923     $output_vars .= $gen_copyright;
6925     # We want to predefine as many variables as possible.  This lets
6926     # the user set them with `+=' in Makefile.am.
6927     &define_standard_variables;
6929     # Read user file, which might override some of our values.
6930     &read_am_file ($amfile, new Automake::Location);
6935 ################################################################
6937 # $FLATTENED
6938 # &flatten ($STRING)
6939 # ------------------
6940 # Flatten the $STRING and return the result.
6941 sub flatten
6943   $_ = shift;
6945   s/\\\n//somg;
6946   s/\s+/ /g;
6947   s/^ //;
6948   s/ $//;
6950   return $_;
6954 # transform_token ($TOKEN, \%PAIRS, $KEY)
6955 # =======================================
6956 # Return the value associated to $KEY in %PAIRS, as used on $TOKEN
6957 # (which should be ?KEY? or any of the special %% requests)..
6958 sub transform_token ($$$)
6960   my ($token, $transform, $key) = @_;
6961   my $res = $transform->{$key};
6962   prog_error "Unknown key `$key' in `$token'" unless defined $res;
6963   return $res;
6967 # transform ($TOKEN, \%PAIRS)
6968 # ===========================
6969 # If ($TOKEN, $VAL) is in %PAIRS:
6970 #   - replaces %KEY% with $VAL,
6971 #   - enables/disables ?KEY? and ?!KEY?,
6972 #   - replaces %?KEY% with TRUE or FALSE.
6973 #   - replaces %KEY?IFTRUE%, %KEY:IFFALSE%, and %KEY?IFTRUE:IFFALSE% with
6974 #     IFTRUE / IFFALSE, as appropriate.
6975 sub transform ($$)
6977   my ($token, $transform) = @_;
6979   # %KEY%.
6980   # Must be before the following pattern to exclude the case
6981   # when there is neither IFTRUE nor IFFALSE.
6982   if ($token =~ /^%([\w\-]+)%$/)
6983     {
6984       return transform_token ($token, $transform, $1);
6985     }
6986   # %KEY?IFTRUE%, %KEY:IFFALSE%, and %KEY?IFTRUE:IFFALSE%.
6987   elsif ($token =~ /^%([\w\-]+)(?:\?([^?:%]+))?(?::([^?:%]+))?%$/)
6988     {
6989       return transform_token ($token, $transform, $1) ? ($2 || '') : ($3 || '');
6990     }
6991   # %?KEY%.
6992   elsif ($token =~ /^%\?([\w\-]+)%$/)
6993     {
6994       return transform_token ($token, $transform, $1) ? 'TRUE' : 'FALSE';
6995     }
6996   # ?KEY? and ?!KEY?.
6997   elsif ($token =~ /^ \? (!?) ([\w\-]+) \? $/x)
6998     {
6999       my $neg = ($1 eq '!') ? 1 : 0;
7000       my $val = transform_token ($token, $transform, $2);
7001       return (!!$val == $neg) ? '##%' : '';
7002     }
7003   else
7004     {
7005       prog_error "Unknown request format: $token";
7006     }
7010 # @PARAGRAPHS
7011 # &make_paragraphs ($MAKEFILE, [%TRANSFORM])
7012 # ------------------------------------------
7013 # Load a $MAKEFILE, apply the %TRANSFORM, and return it as a list of
7014 # paragraphs.
7015 sub make_paragraphs ($%)
7017   my ($file, %transform) = @_;
7019   # Complete %transform with global options.
7020   # Note that %transform goes last, so it overrides global options.
7021   %transform = ('CYGNUS'      => !! option 'cygnus',
7022                  'MAINTAINER-MODE'
7023                  => $seen_maint_mode ? subst ('MAINTAINER_MODE_TRUE') : '',
7025                  'XZ'          => !! option 'dist-xz',
7026                  'LZMA'        => !! option 'dist-lzma',
7027                  'BZIP2'       => !! option 'dist-bzip2',
7028                  'COMPRESS'    => !! option 'dist-tarZ',
7029                  'GZIP'        =>  ! option 'no-dist-gzip',
7030                  'SHAR'        => !! option 'dist-shar',
7031                  'ZIP'         => !! option 'dist-zip',
7033                  'INSTALL-INFO' =>  ! option 'no-installinfo',
7034                  'INSTALL-MAN'  =>  ! option 'no-installman',
7035                  'HAVE-MANS'    => !! var ('MANS'),
7036                  'CK-NEWS'      => !! option 'check-news',
7038                  'SUBDIRS'      => !! var ('SUBDIRS'),
7039                  'TOPDIR_P'     => $relative_dir eq '.',
7041                  'BUILD'    => ($seen_canonical >= AC_CANONICAL_BUILD),
7042                  'HOST'     => ($seen_canonical >= AC_CANONICAL_HOST),
7043                  'TARGET'   => ($seen_canonical >= AC_CANONICAL_TARGET),
7045                  'LIBTOOL'      => !! var ('LIBTOOL'),
7046                  'NONLIBTOOL'   => 1,
7047                  'FIRST'        => ! $transformed_files{$file},
7048                 %transform);
7050   $transformed_files{$file} = 1;
7051   $_ = $am_file_cache{$file};
7053   if (! defined $_)
7054     {
7055       verb "reading $file";
7056       # Swallow the whole file.
7057       my $fc_file = new Automake::XFile "< $file";
7058       my $saved_dollar_slash = $/;
7059       undef $/;
7060       $_ = $fc_file->getline;
7061       $/ = $saved_dollar_slash;
7062       $fc_file->close;
7064       # Remove ##-comments.
7065       # Besides we don't need more than two consecutive new-lines.
7066       s/(?:$IGNORE_PATTERN|(?<=\n\n)\n+)//gom;
7068       $am_file_cache{$file} = $_;
7069     }
7071   # Substitute Automake template tokens.
7072   s/(?: % \?? [\w\-]+ %
7073       | % [\w\-]+ (?:\?[^?:%]+)? (?::[^?:%]+)? %
7074       | \? !? [\w\-]+ \?
7075     )/transform($&, \%transform)/gex;
7076   # transform() may have added some ##%-comments to strip.
7077   # (we use `##%' instead of `##' so we can distinguish ##%##%##% from
7078   # ####### and do not remove the latter.)
7079   s/^[ \t]*(?:##%)+.*\n//gm;
7081   # Split at unescaped new lines.
7082   my @lines = split (/(?<!\\)\n/, $_);
7083   my @res;
7085   while (defined ($_ = shift @lines))
7086     {
7087       my $paragraph = $_;
7088       # If we are a rule, eat as long as we start with a tab.
7089       if (/$RULE_PATTERN/smo)
7090         {
7091           while (defined ($_ = shift @lines) && $_ =~ /^\t/)
7092             {
7093               $paragraph .= "\n$_";
7094             }
7095           unshift (@lines, $_);
7096         }
7098       # If we are a comments, eat as much comments as you can.
7099       elsif (/$COMMENT_PATTERN/smo)
7100         {
7101           while (defined ($_ = shift @lines)
7102                  && $_ =~ /$COMMENT_PATTERN/smo)
7103             {
7104               $paragraph .= "\n$_";
7105             }
7106           unshift (@lines, $_);
7107         }
7109       push @res, $paragraph;
7110     }
7112   return @res;
7117 # ($COMMENT, $VARIABLES, $RULES)
7118 # &file_contents_internal ($IS_AM, $FILE, $WHERE, [%TRANSFORM])
7119 # -------------------------------------------------------------
7120 # Return contents of a file from $libdir/am, automatically skipping
7121 # macros or rules which are already known. $IS_AM iff the caller is
7122 # reading an Automake file (as opposed to the user's Makefile.am).
7123 sub file_contents_internal ($$$%)
7125     my ($is_am, $file, $where, %transform) = @_;
7127     $where->set ($file);
7129     my $result_vars = '';
7130     my $result_rules = '';
7131     my $comment = '';
7132     my $spacing = '';
7134     # The following flags are used to track rules spanning across
7135     # multiple paragraphs.
7136     my $is_rule = 0;            # 1 if we are processing a rule.
7137     my $discard_rule = 0;       # 1 if the current rule should not be output.
7139     # We save the conditional stack on entry, and then check to make
7140     # sure it is the same on exit.  This lets us conditionally include
7141     # other files.
7142     my @saved_cond_stack = @cond_stack;
7143     my $cond = new Automake::Condition (@cond_stack);
7145     foreach (make_paragraphs ($file, %transform))
7146     {
7147         # FIXME: no line number available.
7148         $where->set ($file);
7150         # Sanity checks.
7151         error $where, "blank line following trailing backslash:\n$_"
7152           if /\\$/;
7153         error $where, "comment following trailing backslash:\n$_"
7154           if /\\#/;
7156         if (/^$/)
7157         {
7158             $is_rule = 0;
7159             # Stick empty line before the incoming macro or rule.
7160             $spacing = "\n";
7161         }
7162         elsif (/$COMMENT_PATTERN/mso)
7163         {
7164             $is_rule = 0;
7165             # Stick comments before the incoming macro or rule.
7166             $comment = "$_\n";
7167         }
7169         # Handle inclusion of other files.
7170         elsif (/$INCLUDE_PATTERN/o)
7171         {
7172             if ($cond != FALSE)
7173               {
7174                 my $file = ($is_am ? "$libdir/am/" : '') . $1;
7175                 $where->push_context ("`$file' included from here");
7176                 # N-ary `.=' fails.
7177                 my ($com, $vars, $rules)
7178                   = file_contents_internal ($is_am, $file, $where, %transform);
7179                 $where->pop_context;
7180                 $comment .= $com;
7181                 $result_vars .= $vars;
7182                 $result_rules .= $rules;
7183               }
7184         }
7186         # Handling the conditionals.
7187         elsif (/$IF_PATTERN/o)
7188           {
7189             $cond = cond_stack_if ($1, $2, $file);
7190           }
7191         elsif (/$ELSE_PATTERN/o)
7192           {
7193             $cond = cond_stack_else ($1, $2, $file);
7194           }
7195         elsif (/$ENDIF_PATTERN/o)
7196           {
7197             $cond = cond_stack_endif ($1, $2, $file);
7198           }
7200         # Handling rules.
7201         elsif (/$RULE_PATTERN/mso)
7202         {
7203           $is_rule = 1;
7204           $discard_rule = 0;
7205           # Separate relationship from optional actions: the first
7206           # `new-line tab" not preceded by backslash (continuation
7207           # line).
7208           my $paragraph = $_;
7209           /^(.*?)(?:(?<!\\)\n(\t.*))?$/s;
7210           my ($relationship, $actions) = ($1, $2 || '');
7212           # Separate targets from dependencies: the first colon.
7213           $relationship =~ /^([^:]+\S+) *: *(.*)$/som;
7214           my ($targets, $dependencies) = ($1, $2);
7215           # Remove the escaped new lines.
7216           # I don't know why, but I have to use a tmp $flat_deps.
7217           my $flat_deps = &flatten ($dependencies);
7218           my @deps = split (' ', $flat_deps);
7220           foreach (split (' ', $targets))
7221             {
7222               # FIXME: 1. We are not robust to people defining several targets
7223               # at once, only some of them being in %dependencies.  The
7224               # actions from the targets in %dependencies are usually generated
7225               # from the content of %actions, but if some targets in $targets
7226               # are not in %dependencies the ELSE branch will output
7227               # a rule for all $targets (i.e. the targets which are both
7228               # in %dependencies and $targets will have two rules).
7230               # FIXME: 2. The logic here is not able to output a
7231               # multi-paragraph rule several time (e.g. for each condition
7232               # it is defined for) because it only knows the first paragraph.
7234               # FIXME: 3. We are not robust to people defining a subset
7235               # of a previously defined "multiple-target" rule.  E.g.
7236               # `foo:' after `foo bar:'.
7238               # Output only if not in FALSE.
7239               if (defined $dependencies{$_} && $cond != FALSE)
7240                 {
7241                   &depend ($_, @deps);
7242                   register_action ($_, $actions);
7243                 }
7244               else
7245                 {
7246                   # Free-lance dependency.  Output the rule for all the
7247                   # targets instead of one by one.
7248                   my @undefined_conds =
7249                     Automake::Rule::define ($targets, $file,
7250                                             $is_am ? RULE_AUTOMAKE : RULE_USER,
7251                                             $cond, $where);
7252                   for my $undefined_cond (@undefined_conds)
7253                     {
7254                       my $condparagraph = $paragraph;
7255                       $condparagraph =~ s/^/$undefined_cond->subst_string/gme;
7256                       $result_rules .= "$spacing$comment$condparagraph\n";
7257                     }
7258                   if (scalar @undefined_conds == 0)
7259                     {
7260                       # Remember to discard next paragraphs
7261                       # if they belong to this rule.
7262                       # (but see also FIXME: #2 above.)
7263                       $discard_rule = 1;
7264                     }
7265                   $comment = $spacing = '';
7266                   last;
7267                 }
7268             }
7269         }
7271         elsif (/$ASSIGNMENT_PATTERN/mso)
7272         {
7273             my ($var, $type, $val) = ($1, $2, $3);
7274             error $where, "variable `$var' with trailing backslash"
7275               if /\\$/;
7277             $is_rule = 0;
7279             Automake::Variable::define ($var,
7280                                         $is_am ? VAR_AUTOMAKE : VAR_MAKEFILE,
7281                                         $type, $cond, $val, $comment, $where,
7282                                         VAR_ASIS)
7283               if $cond != FALSE;
7285             $comment = $spacing = '';
7286         }
7287         else
7288         {
7289             # This isn't an error; it is probably some tokens which
7290             # configure is supposed to replace, such as `@SET-MAKE@',
7291             # or some part of a rule cut by an if/endif.
7292             if (! $cond->false && ! ($is_rule && $discard_rule))
7293               {
7294                 s/^/$cond->subst_string/gme;
7295                 $result_rules .= "$spacing$comment$_\n";
7296               }
7297             $comment = $spacing = '';
7298         }
7299     }
7301     error ($where, @cond_stack ?
7302            "unterminated conditionals: @cond_stack" :
7303            "too many conditionals closed in include file")
7304       if "@saved_cond_stack" ne "@cond_stack";
7306     return ($comment, $result_vars, $result_rules);
7310 # $CONTENTS
7311 # &file_contents ($BASENAME, $WHERE, [%TRANSFORM])
7312 # ------------------------------------------------
7313 # Return contents of a file from $libdir/am, automatically skipping
7314 # macros or rules which are already known.
7315 sub file_contents ($$%)
7317     my ($basename, $where, %transform) = @_;
7318     my ($comments, $variables, $rules) =
7319       file_contents_internal (1, "$libdir/am/$basename.am", $where,
7320                               %transform);
7321     return "$comments$variables$rules";
7325 # @PREFIX
7326 # &am_primary_prefixes ($PRIMARY, $CAN_DIST, @PREFIXES)
7327 # -----------------------------------------------------
7328 # Find all variable prefixes that are used for install directories.  A
7329 # prefix `zar' qualifies iff:
7331 # * `zardir' is a variable.
7332 # * `zar_PRIMARY' is a variable.
7334 # As a side effect, it looks for misspellings.  It is an error to have
7335 # a variable ending in a "reserved" suffix whose prefix is unknown, e.g.
7336 # "bni_PROGRAMS".  However, unusual prefixes are allowed if a variable
7337 # of the same name (with "dir" appended) exists.  For instance, if the
7338 # variable "zardir" is defined, then "zar_PROGRAMS" becomes valid.
7339 # This is to provide a little extra flexibility in those cases which
7340 # need it.
7341 sub am_primary_prefixes ($$@)
7343   my ($primary, $can_dist, @prefixes) = @_;
7345   local $_;
7346   my %valid = map { $_ => 0 } @prefixes;
7347   $valid{'EXTRA'} = 0;
7348   foreach my $var (variables $primary)
7349     {
7350       # Automake is allowed to define variables that look like primaries
7351       # but which aren't.  E.g. INSTALL_sh_DATA.
7352       # Autoconf can also define variables like INSTALL_DATA, so
7353       # ignore all configure variables (at least those which are not
7354       # redefined in Makefile.am).
7355       # FIXME: We should make sure that these variables are not
7356       # conditionally defined (or else adjust the condition below).
7357       my $def = $var->def (TRUE);
7358       next if $def && $def->owner != VAR_MAKEFILE;
7360       my $varname = $var->name;
7362       if ($varname =~ /^(nobase_)?(dist_|nodist_)?(.*)_[[:alnum:]]+$/)
7363         {
7364           my ($base, $dist, $X) = ($1 || '', $2 || '', $3 || '');
7365           if ($dist ne '' && ! $can_dist)
7366             {
7367               err_var ($var,
7368                        "invalid variable `$varname': `dist' is forbidden");
7369             }
7370           # Standard directories must be explicitly allowed.
7371           elsif (! defined $valid{$X} && exists $standard_prefix{$X})
7372             {
7373               err_var ($var,
7374                        "`${X}dir' is not a legitimate directory " .
7375                        "for `$primary'");
7376             }
7377           # A not explicitly valid directory is allowed if Xdir is defined.
7378           elsif (! defined $valid{$X} &&
7379                  $var->requires_variables ("`$varname' is used", "${X}dir"))
7380             {
7381               # Nothing to do.  Any error message has been output
7382               # by $var->requires_variables.
7383             }
7384           else
7385             {
7386               # Ensure all extended prefixes are actually used.
7387               $valid{"$base$dist$X"} = 1;
7388             }
7389         }
7390       else
7391         {
7392           prog_error "unexpected variable name: $varname";
7393         }
7394     }
7396   # Return only those which are actually defined.
7397   return sort grep { var ($_ . '_' . $primary) } keys %valid;
7401 # Handle `where_HOW' variable magic.  Does all lookups, generates
7402 # install code, and possibly generates code to define the primary
7403 # variable.  The first argument is the name of the .am file to munge,
7404 # the second argument is the primary variable (e.g. HEADERS), and all
7405 # subsequent arguments are possible installation locations.
7407 # Returns list of [$location, $value] pairs, where
7408 # $value's are the values in all where_HOW variable, and $location
7409 # there associated location (the place here their parent variables were
7410 # defined).
7412 # FIXME: this should be rewritten to be cleaner.  It should be broken
7413 # up into multiple functions.
7415 # Usage is: am_install_var (OPTION..., file, HOW, where...)
7416 sub am_install_var
7418   my (@args) = @_;
7420   my $do_require = 1;
7421   my $can_dist = 0;
7422   my $default_dist = 0;
7423   while (@args)
7424     {
7425       if ($args[0] eq '-noextra')
7426         {
7427           $do_require = 0;
7428         }
7429       elsif ($args[0] eq '-candist')
7430         {
7431           $can_dist = 1;
7432         }
7433       elsif ($args[0] eq '-defaultdist')
7434         {
7435           $default_dist = 1;
7436           $can_dist = 1;
7437         }
7438       elsif ($args[0] !~ /^-/)
7439         {
7440           last;
7441         }
7442       shift (@args);
7443     }
7445   my ($file, $primary, @prefix) = @args;
7447   # Now that configure substitutions are allowed in where_HOW
7448   # variables, it is an error to actually define the primary.  We
7449   # allow `JAVA', as it is customarily used to mean the Java
7450   # interpreter.  This is but one of several Java hacks.  Similarly,
7451   # `PYTHON' is customarily used to mean the Python interpreter.
7452   reject_var $primary, "`$primary' is an anachronism"
7453     unless $primary eq 'JAVA' || $primary eq 'PYTHON';
7455   # Get the prefixes which are valid and actually used.
7456   @prefix = am_primary_prefixes ($primary, $can_dist, @prefix);
7458   # If a primary includes a configure substitution, then the EXTRA_
7459   # form is required.  Otherwise we can't properly do our job.
7460   my $require_extra;
7462   my @used = ();
7463   my @result = ();
7465   foreach my $X (@prefix)
7466     {
7467       my $nodir_name = $X;
7468       my $one_name = $X . '_' . $primary;
7469       my $one_var = var $one_name;
7471       my $strip_subdir = 1;
7472       # If subdir prefix should be preserved, do so.
7473       if ($nodir_name =~ /^nobase_/)
7474         {
7475           $strip_subdir = 0;
7476           $nodir_name =~ s/^nobase_//;
7477         }
7479       # If files should be distributed, do so.
7480       my $dist_p = 0;
7481       if ($can_dist)
7482         {
7483           $dist_p = (($default_dist && $nodir_name !~ /^nodist_/)
7484                      || (! $default_dist && $nodir_name =~ /^dist_/));
7485           $nodir_name =~ s/^(dist|nodist)_//;
7486         }
7489       # Use the location of the currently processed variable.
7490       # We are not processing a particular condition, so pick the first
7491       # available.
7492       my $tmpcond = $one_var->conditions->one_cond;
7493       my $where = $one_var->rdef ($tmpcond)->location->clone;
7495       # Append actual contents of where_PRIMARY variable to
7496       # @result, skipping @substitutions@.
7497       foreach my $locvals ($one_var->value_as_list_recursive (location => 1))
7498         {
7499           my ($loc, $value) = @$locvals;
7500           # Skip configure substitutions.
7501           if ($value =~ /^\@.*\@$/)
7502             {
7503               if ($nodir_name eq 'EXTRA')
7504                 {
7505                   error ($where,
7506                          "`$one_name' contains configure substitution, "
7507                          . "but shouldn't");
7508                 }
7509               # Check here to make sure variables defined in
7510               # configure.ac do not imply that EXTRA_PRIMARY
7511               # must be defined.
7512               elsif (! defined $configure_vars{$one_name})
7513                 {
7514                   $require_extra = $one_name
7515                     if $do_require;
7516                 }
7517             }
7518           else
7519             {
7520               push (@result, $locvals);
7521             }
7522         }
7523       # A blatant hack: we rewrite each _PROGRAMS primary to include
7524       # EXEEXT.
7525       append_exeext { 1 } $one_name
7526         if $primary eq 'PROGRAMS';
7527       # "EXTRA" shouldn't be used when generating clean targets,
7528       # all, or install targets.  We used to warn if EXTRA_FOO was
7529       # defined uselessly, but this was annoying.
7530       next
7531         if $nodir_name eq 'EXTRA';
7533       if ($nodir_name eq 'check')
7534         {
7535           push (@check, '$(' . $one_name . ')');
7536         }
7537       else
7538         {
7539           push (@used, '$(' . $one_name . ')');
7540         }
7542       # Is this to be installed?
7543       my $install_p = $nodir_name ne 'noinst' && $nodir_name ne 'check';
7545       # If so, with install-exec? (or install-data?).
7546       my $exec_p = ($nodir_name =~ /$EXEC_DIR_PATTERN/o);
7548       my $check_options_p = $install_p && !! option 'std-options';
7550       # Use the location of the currently processed variable as context.
7551       $where->push_context ("while processing `$one_name'");
7553       # The variable containing all files to distribute.
7554       my $distvar = "\$($one_name)";
7555       $distvar = shadow_unconditionally ($one_name, $where)
7556         if ($dist_p && $one_var->has_conditional_contents);
7558       # Singular form of $PRIMARY.
7559       (my $one_primary = $primary) =~ s/S$//;
7560       $output_rules .= &file_contents ($file, $where,
7561                                        PRIMARY     => $primary,
7562                                        ONE_PRIMARY => $one_primary,
7563                                        DIR         => $X,
7564                                        NDIR        => $nodir_name,
7565                                        BASE        => $strip_subdir,
7567                                        EXEC      => $exec_p,
7568                                        INSTALL   => $install_p,
7569                                        DIST      => $dist_p,
7570                                        DISTVAR   => $distvar,
7571                                        'CK-OPTS' => $check_options_p);
7572     }
7574   # The JAVA variable is used as the name of the Java interpreter.
7575   # The PYTHON variable is used as the name of the Python interpreter.
7576   if (@used && $primary ne 'JAVA' && $primary ne 'PYTHON')
7577     {
7578       # Define it.
7579       define_pretty_variable ($primary, TRUE, INTERNAL, @used);
7580       $output_vars .= "\n";
7581     }
7583   err_var ($require_extra,
7584            "`$require_extra' contains configure substitution,\n"
7585            . "but `EXTRA_$primary' not defined")
7586     if ($require_extra && ! var ('EXTRA_' . $primary));
7588   # Push here because PRIMARY might be configure time determined.
7589   push (@all, '$(' . $primary . ')')
7590     if @used && $primary ne 'JAVA' && $primary ne 'PYTHON';
7592   # Make the result unique.  This lets the user use conditionals in
7593   # a natural way, but still lets us program lazily -- we don't have
7594   # to worry about handling a particular object more than once.
7595   # We will keep only one location per object.
7596   my %result = ();
7597   for my $pair (@result)
7598     {
7599       my ($loc, $val) = @$pair;
7600       $result{$val} = $loc;
7601     }
7602   my @l = sort keys %result;
7603   return map { [$result{$_}->clone, $_] } @l;
7607 ################################################################
7609 # Each key in this hash is the name of a directory holding a
7610 # Makefile.in.  These variables are local to `is_make_dir'.
7611 my %make_dirs = ();
7612 my $make_dirs_set = 0;
7614 sub is_make_dir
7616     my ($dir) = @_;
7617     if (! $make_dirs_set)
7618     {
7619         foreach my $iter (@configure_input_files)
7620         {
7621             $make_dirs{dirname ($iter)} = 1;
7622         }
7623         # We also want to notice Makefile.in's.
7624         foreach my $iter (@other_input_files)
7625         {
7626             if ($iter =~ /Makefile\.in$/)
7627             {
7628                 $make_dirs{dirname ($iter)} = 1;
7629             }
7630         }
7631         $make_dirs_set = 1;
7632     }
7633     return defined $make_dirs{$dir};
7636 ################################################################
7638 # Find the aux dir.  This should match the algorithm used by
7639 # ./configure. (See the Autoconf documentation for for
7640 # AC_CONFIG_AUX_DIR.)
7641 sub locate_aux_dir ()
7643   if (! $config_aux_dir_set_in_configure_ac)
7644     {
7645       # The default auxiliary directory is the first
7646       # of ., .., or ../.. that contains install-sh.
7647       # Assume . if install-sh doesn't exist yet.
7648       for my $dir (qw (. .. ../..))
7649         {
7650           if (-f "$dir/install-sh")
7651             {
7652               $config_aux_dir = $dir;
7653               last;
7654             }
7655         }
7656       $config_aux_dir = '.' unless $config_aux_dir;
7657     }
7658   # Avoid unsightly '/.'s.
7659   $am_config_aux_dir =
7660     '$(top_srcdir)' . ($config_aux_dir eq '.' ? "" : "/$config_aux_dir");
7661   $am_config_aux_dir =~ s,/*$,,;
7665 # &maybe_push_required_file ($DIR, $FILE, $FULLFILE)
7666 # --------------------------------------------------
7667 # See if we want to push this file onto dist_common.  This function
7668 # encodes the rules for deciding when to do so.
7669 sub maybe_push_required_file
7671   my ($dir, $file, $fullfile) = @_;
7673   if ($dir eq $relative_dir)
7674     {
7675       push_dist_common ($file);
7676       return 1;
7677     }
7678   elsif ($relative_dir eq '.' && ! &is_make_dir ($dir))
7679     {
7680       # If we are doing the topmost directory, and the file is in a
7681       # subdir which does not have a Makefile, then we distribute it
7682       # here.
7684       # If a required file is above the source tree, it is important
7685       # to prefix it with `$(srcdir)' so that no VPATH search is
7686       # performed.  Otherwise problems occur with Make implementations
7687       # that rewrite and simplify rules whose dependencies are found in a
7688       # VPATH location.  Here is an example with OSF1/Tru64 Make.
7689       #
7690       #   % cat Makefile
7691       #   VPATH = sub
7692       #   distdir: ../a
7693       #           echo ../a
7694       #   % ls
7695       #   Makefile a
7696       #   % make
7697       #   echo a
7698       #   a
7699       #
7700       # Dependency `../a' was found in `sub/../a', but this make
7701       # implementation simplified it as `a'.  (Note that the sub/
7702       # directory does not even exist.)
7703       #
7704       # This kind of VPATH rewriting seems hard to cancel.  The
7705       # distdir.am hack against VPATH rewriting works only when no
7706       # simplification is done, i.e., for dependencies which are in
7707       # subdirectories, not in enclosing directories.  Hence, in
7708       # the latter case we use a full path to make sure no VPATH
7709       # search occurs.
7710       $fullfile = '$(srcdir)/' . $fullfile
7711         if $dir =~ m,^\.\.(?:$|/),;
7713       push_dist_common ($fullfile);
7714       return 1;
7715     }
7716   return 0;
7720 # If a file name appears as a key in this hash, then it has already
7721 # been checked for.  This allows us not to report the same error more
7722 # than once.
7723 my %required_file_not_found = ();
7725 # &require_file_internal ($WHERE, $MYSTRICT, $DIRECTORY, @FILES)
7726 # --------------------------------------------------------------
7727 # Verify that the file must exist in $DIRECTORY, or install it.
7728 # $MYSTRICT is the strictness level at which this file becomes required.
7729 sub require_file_internal ($$$@)
7731   my ($where, $mystrict, $dir, @files) = @_;
7733   foreach my $file (@files)
7734     {
7735       my $fullfile = "$dir/$file";
7736       my $found_it = 0;
7737       my $dangling_sym = 0;
7739       if (-l $fullfile && ! -f $fullfile)
7740         {
7741           $dangling_sym = 1;
7742         }
7743       elsif (dir_has_case_matching_file ($dir, $file))
7744         {
7745           $found_it = 1;
7746           maybe_push_required_file ($dir, $file, $fullfile);
7747         }
7749       # `--force-missing' only has an effect if `--add-missing' is
7750       # specified.
7751       if ($found_it && (! $add_missing || ! $force_missing))
7752         {
7753           next;
7754         }
7755       else
7756         {
7757           # If we've already looked for it, we're done.  You might
7758           # wonder why we don't do this before searching for the
7759           # file.  If we do that, then something like
7760           # AC_OUTPUT(subdir/foo foo) will fail to put foo.in into
7761           # DIST_COMMON.
7762           if (! $found_it)
7763             {
7764               next if defined $required_file_not_found{$fullfile};
7765               $required_file_not_found{$fullfile} = 1;
7766             }
7768           if ($strictness >= $mystrict)
7769             {
7770               if ($dangling_sym && $add_missing)
7771                 {
7772                   unlink ($fullfile);
7773                 }
7775               my $trailer = '';
7776               my $trailer2 = '';
7777               my $suppress = 0;
7779               # Only install missing files according to our desired
7780               # strictness level.
7781               my $message = "required file `$fullfile' not found";
7782               if ($add_missing)
7783                 {
7784                   if (-f "$libdir/$file")
7785                     {
7786                       $suppress = 1;
7788                       # Install the missing file.  Symlink if we
7789                       # can, copy if we must.  Note: delete the file
7790                       # first, in case it is a dangling symlink.
7791                       $message = "installing `$fullfile'";
7793                       # The license file should not be volatile.
7794                       if ($file eq "COPYING")
7795                         {
7796                           $message .= " using GNU General Public License v3 file";
7797                           $trailer2 = "\n    Consider adding the COPYING file"
7798                                     . " to the version control system"
7799                                     . "\n    for your code, to avoid questions"
7800                                     . " about which license your project uses.";
7801                         }
7803                       # Windows Perl will hang if we try to delete a
7804                       # file that doesn't exist.
7805                       unlink ($fullfile) if -f $fullfile;
7806                       if ($symlink_exists && ! $copy_missing)
7807                         {
7808                           if (! symlink ("$libdir/$file", $fullfile))
7809                             {
7810                               $suppress = 0;
7811                               $trailer = "; error while making link: $!";
7812                             }
7813                         }
7814                       elsif (system ('cp', "$libdir/$file", $fullfile))
7815                         {
7816                           $suppress = 0;
7817                           $trailer = "\n    error while copying";
7818                         }
7819                       set_dir_cache_file ($dir, $file);
7820                     }
7822                   if (! maybe_push_required_file (dirname ($fullfile),
7823                                                   $file, $fullfile))
7824                     {
7825                       if (! $found_it && ! $automake_will_process_aux_dir)
7826                         {
7827                           # We have added the file but could not push it
7828                           # into DIST_COMMON, probably because this is
7829                           # an auxiliary file and we are not processing
7830                           # the top level Makefile.  Furthermore Automake
7831                           # hasn't been asked to create the Makefile.in
7832                           # that distributes the aux dir files.
7833                           error ($where, 'Please make a full run of automake'
7834                                  . " so $fullfile gets distributed.");
7835                         }
7836                     }
7837                 }
7838               else
7839                 {
7840                   $trailer = "\n  `automake --add-missing' can install `$file'"
7841                     if -f "$libdir/$file";
7842                 }
7844               # If --force-missing was specified, and we have
7845               # actually found the file, then do nothing.
7846               next
7847                 if $found_it && $force_missing;
7849               # If we couldn't install the file, but it is a target in
7850               # the Makefile, don't print anything.  This allows files
7851               # like README, AUTHORS, or THANKS to be generated.
7852               next
7853                 if !$suppress && rule $file;
7855               msg ($suppress ? 'note' : 'error', $where, "$message$trailer$trailer2");
7856             }
7857         }
7858     }
7861 # &require_file ($WHERE, $MYSTRICT, @FILES)
7862 # -----------------------------------------
7863 sub require_file ($$@)
7865     my ($where, $mystrict, @files) = @_;
7866     require_file_internal ($where, $mystrict, $relative_dir, @files);
7869 # &require_file_with_macro ($COND, $MACRO, $MYSTRICT, @FILES)
7870 # -----------------------------------------------------------
7871 sub require_file_with_macro ($$$@)
7873     my ($cond, $macro, $mystrict, @files) = @_;
7874     $macro = rvar ($macro) unless ref $macro;
7875     require_file ($macro->rdef ($cond)->location, $mystrict, @files);
7878 # &require_libsource_with_macro ($COND, $MACRO, $MYSTRICT, @FILES)
7879 # ----------------------------------------------------------------
7880 # Require an AC_LIBSOURCEd file.  If AC_CONFIG_LIBOBJ_DIR was called, it
7881 # must be in that directory.  Otherwise expect it in the current directory.
7882 sub require_libsource_with_macro ($$$@)
7884     my ($cond, $macro, $mystrict, @files) = @_;
7885     $macro = rvar ($macro) unless ref $macro;
7886     if ($config_libobj_dir)
7887       {
7888         require_file_internal ($macro->rdef ($cond)->location, $mystrict,
7889                                $config_libobj_dir, @files);
7890       }
7891     else
7892       {
7893         require_file ($macro->rdef ($cond)->location, $mystrict, @files);
7894       }
7897 # Queue to push require_conf_file requirements to.
7898 my $required_conf_file_queue;
7900 # &queue_required_conf_file ($QUEUE, $KEY, $DIR, $WHERE, $MYSTRICT, @FILES)
7901 # -------------------------------------------------------------------------
7902 sub queue_required_conf_file ($$$$@)
7904     my ($queue, $key, $dir, $where, $mystrict, @files) = @_;
7905     my @serial_loc;
7906     if (ref $where)
7907       {
7908         @serial_loc = (QUEUE_LOCATION, $where->serialize ());
7909       }
7910     else
7911       {
7912         @serial_loc = (QUEUE_STRING, $where);
7913       }
7914     $queue->enqueue ($key, $dir, @serial_loc, $mystrict, 0 + @files, @files);
7917 # &require_queued_conf_file ($QUEUE)
7918 # ----------------------------------
7919 sub require_queued_conf_file ($)
7921     my ($queue) = @_;
7922     my $where;
7923     my $dir = $queue->dequeue ();
7924     my $loc_key = $queue->dequeue ();
7925     if ($loc_key eq QUEUE_LOCATION)
7926       {
7927         $where = Automake::Location::deserialize ($queue);
7928       }
7929     elsif ($loc_key eq QUEUE_STRING)
7930       {
7931         $where = $queue->dequeue ();
7932       }
7933     else
7934       {
7935         prog_error "unexpected key $loc_key";
7936       }
7937     my $mystrict = $queue->dequeue ();
7938     my $nfiles = $queue->dequeue ();
7939     my @files;
7940     push @files, $queue->dequeue ()
7941       foreach (1 .. $nfiles);
7943     # Dequeuing happens outside of per-makefile context, so we have to
7944     # set the variables used by require_file_internal and the functions
7945     # it calls.  Gross!
7946     $relative_dir = $dir;
7947     require_file_internal ($where, $mystrict, $config_aux_dir, @files);
7950 # &require_conf_file ($WHERE, $MYSTRICT, @FILES)
7951 # ----------------------------------------------
7952 # Looks in configuration path, as specified by AC_CONFIG_AUX_DIR;
7953 # worker threads may queue up the action to be serialized by the master.
7955 # FIXME: this seriously relies on the semantics of require_file_internal
7956 # and maybe_push_required_file, in that we exploit the fact that only the
7957 # contents of the last handled output file may be impacted (which in turn
7958 # is dealt with by the master thread).
7959 sub require_conf_file ($$@)
7961     my ($where, $mystrict, @files) = @_;
7962     if (defined $required_conf_file_queue)
7963       {
7964         queue_required_conf_file ($required_conf_file_queue, QUEUE_CONF_FILE,
7965                                   $relative_dir, $where, $mystrict, @files);
7966       }
7967     else
7968       {
7969         require_file_internal ($where, $mystrict, $config_aux_dir, @files);
7970       }
7974 # &require_conf_file_with_macro ($COND, $MACRO, $MYSTRICT, @FILES)
7975 # ----------------------------------------------------------------
7976 sub require_conf_file_with_macro ($$$@)
7978     my ($cond, $macro, $mystrict, @files) = @_;
7979     require_conf_file (rvar ($macro)->rdef ($cond)->location,
7980                        $mystrict, @files);
7983 ################################################################
7985 # &require_build_directory ($DIRECTORY)
7986 # ------------------------------------
7987 # Emit rules to create $DIRECTORY if needed, and return
7988 # the file that any target requiring this directory should be made
7989 # dependent upon.
7990 # We don't want to emit the rule twice, and want to reuse it
7991 # for directories with equivalent names (e.g., `foo/bar' and `./foo//bar').
7992 sub require_build_directory ($)
7994   my $directory = shift;
7996   return $directory_map{$directory} if exists $directory_map{$directory};
7998   my $cdir = File::Spec->canonpath ($directory);
8000   if (exists $directory_map{$cdir})
8001     {
8002       my $stamp = $directory_map{$cdir};
8003       $directory_map{$directory} = $stamp;
8004       return $stamp;
8005     }
8007   my $dirstamp = "$cdir/\$(am__dirstamp)";
8009   $directory_map{$directory} = $dirstamp;
8010   $directory_map{$cdir} = $dirstamp;
8012   # Set a variable for the dirstamp basename.
8013   define_pretty_variable ('am__dirstamp', TRUE, INTERNAL,
8014                           '$(am__leading_dot)dirstamp');
8016   # Directory must be removed by `make distclean'.
8017   $clean_files{$dirstamp} = DIST_CLEAN;
8019   $output_rules .= ("$dirstamp:\n"
8020                     . "\t\@\$(MKDIR_P) $directory\n"
8021                     . "\t\@: > $dirstamp\n");
8023   return $dirstamp;
8026 # &require_build_directory_maybe ($FILE)
8027 # --------------------------------------
8028 # If $FILE lies in a subdirectory, emit a rule to create this
8029 # directory and return the file that $FILE should be made
8030 # dependent upon.  Otherwise, just return the empty string.
8031 sub require_build_directory_maybe ($)
8033     my $file = shift;
8034     my $directory = dirname ($file);
8036     if ($directory ne '.')
8037     {
8038         return require_build_directory ($directory);
8039     }
8040     else
8041     {
8042         return '';
8043     }
8046 ################################################################
8048 # Push a list of files onto dist_common.
8049 sub push_dist_common
8051   prog_error "push_dist_common run after handle_dist"
8052     if $handle_dist_run;
8053   Automake::Variable::define ('DIST_COMMON', VAR_AUTOMAKE, '+', TRUE, "@_",
8054                               '', INTERNAL, VAR_PRETTY);
8058 ################################################################
8060 # generate_makefile ($MAKEFILE_AM, $MAKEFILE_IN)
8061 # ----------------------------------------------
8062 # Generate a Makefile.in given the name of the corresponding Makefile and
8063 # the name of the file output by config.status.
8064 sub generate_makefile ($$)
8066   my ($makefile_am, $makefile_in) = @_;
8068   # Reset all the Makefile.am related variables.
8069   initialize_per_input;
8071   # AUTOMAKE_OPTIONS can contains -W flags to disable or enable
8072   # warnings for this file.  So hold any warning issued before
8073   # we have processed AUTOMAKE_OPTIONS.
8074   buffer_messages ('warning');
8076   # Name of input file ("Makefile.am") and output file
8077   # ("Makefile.in").  These have no directory components.
8078   $am_file_name = basename ($makefile_am);
8079   $in_file_name = basename ($makefile_in);
8081   # $OUTPUT is encoded.  If it contains a ":" then the first element
8082   # is the real output file, and all remaining elements are input
8083   # files.  We don't scan or otherwise deal with these input files,
8084   # other than to mark them as dependencies.  See
8085   # &scan_autoconf_files for details.
8086   my ($makefile, @inputs) = split (/:/, $output_files{$makefile_in});
8088   $relative_dir = dirname ($makefile);
8089   $am_relative_dir = dirname ($makefile_am);
8090   $topsrcdir = backname ($relative_dir);
8092   read_main_am_file ($makefile_am);
8093   if (handle_options)
8094     {
8095       # Process buffered warnings.
8096       flush_messages;
8097       # Fatal error.  Just return, so we can continue with next file.
8098       return;
8099     }
8100   # Process buffered warnings.
8101   flush_messages;
8103   # There are a few install-related variables that you should not define.
8104   foreach my $var ('PRE_INSTALL', 'POST_INSTALL', 'NORMAL_INSTALL')
8105     {
8106       my $v = var $var;
8107       if ($v)
8108         {
8109           my $def = $v->def (TRUE);
8110           prog_error "$var not defined in condition TRUE"
8111             unless $def;
8112           reject_var $var, "`$var' should not be defined"
8113             if $def->owner != VAR_AUTOMAKE;
8114         }
8115     }
8117   # Catch some obsolete variables.
8118   msg_var ('obsolete', 'INCLUDES',
8119            "`INCLUDES' is the old name for `AM_CPPFLAGS' (or `*_CPPFLAGS')")
8120     if var ('INCLUDES');
8122   # Must do this after reading .am file.
8123   define_variable ('subdir', $relative_dir, INTERNAL);
8125   # If DIST_SUBDIRS is defined, make sure SUBDIRS is, so that
8126   # recursive rules are enabled.
8127   define_pretty_variable ('SUBDIRS', TRUE, INTERNAL, '')
8128     if var 'DIST_SUBDIRS' && ! var 'SUBDIRS';
8130   # Check first, because we might modify some state.
8131   check_cygnus;
8132   check_gnu_standards;
8133   check_gnits_standards;
8135   handle_configure ($makefile_am, $makefile_in, $makefile, @inputs);
8136   handle_gettext;
8137   handle_libraries;
8138   handle_ltlibraries;
8139   handle_programs;
8140   handle_scripts;
8142   # These must be run after all the sources are scanned.  They
8143   # use variables defined by &handle_libraries, &handle_ltlibraries,
8144   # or &handle_programs.
8145   handle_compile;
8146   handle_languages;
8147   handle_libtool;
8149   # Variables used by distdir.am and tags.am.
8150   define_pretty_variable ('SOURCES', TRUE, INTERNAL, @sources);
8151   if (! option 'no-dist')
8152     {
8153       define_pretty_variable ('DIST_SOURCES', TRUE, INTERNAL, @dist_sources);
8154     }
8156   handle_multilib;
8157   handle_texinfo;
8158   handle_emacs_lisp;
8159   handle_python;
8160   handle_java;
8161   handle_man_pages;
8162   handle_data;
8163   handle_headers;
8164   handle_subdirs;
8165   handle_tags;
8166   handle_minor_options;
8167   # Must come after handle_programs so that %known_programs is up-to-date.
8168   handle_tests;
8170   # This must come after most other rules.
8171   handle_dist;
8173   handle_footer;
8174   do_check_merge_target;
8175   handle_all ($makefile);
8177   # FIXME: Gross!
8178   if (var ('lib_LTLIBRARIES') && var ('bin_PROGRAMS'))
8179     {
8180       $output_rules .= "install-binPROGRAMS: install-libLTLIBRARIES\n\n";
8181     }
8182   if (var ('nobase_lib_LTLIBRARIES') && var ('bin_PROGRAMS'))
8183     {
8184       $output_rules .= "install-binPROGRAMS: install-nobase_libLTLIBRARIES\n\n";
8185     }
8187   handle_install;
8188   handle_clean ($makefile);
8189   handle_factored_dependencies;
8191   # Comes last, because all the above procedures may have
8192   # defined or overridden variables.
8193   $output_vars .= output_variables;
8195   check_typos;
8197   my ($out_file) = $output_directory . '/' . $makefile_in;
8199   if ($exit_code != 0)
8200     {
8201       verb "not writing $out_file because of earlier errors";
8202       return;
8203     }
8205   if (! -d ($output_directory . '/' . $am_relative_dir))
8206     {
8207       mkdir ($output_directory . '/' . $am_relative_dir, 0755);
8208     }
8210   # We make sure that `all:' is the first target.
8211   my $output =
8212     "$output_vars$output_all$output_header$output_rules$output_trailer";
8214   # Decide whether we must update the output file or not.
8215   # We have to update in the following situations.
8216   #  * $force_generation is set.
8217   #  * any of the output dependencies is younger than the output
8218   #  * the contents of the output is different (this can happen
8219   #    if the project has been populated with a file listed in
8220   #    @common_files since the last run).
8221   # Output's dependencies are split in two sets:
8222   #  * dependencies which are also configure dependencies
8223   #    These do not change between each Makefile.am
8224   #  * other dependencies, specific to the Makefile.am being processed
8225   #    (such as the Makefile.am itself, or any Makefile fragment
8226   #    it includes).
8227   my $timestamp = mtime $out_file;
8228   if (! $force_generation
8229       && $configure_deps_greatest_timestamp < $timestamp
8230       && $output_deps_greatest_timestamp < $timestamp
8231       && $output eq contents ($out_file))
8232     {
8233       verb "$out_file unchanged";
8234       # No need to update.
8235       return;
8236     }
8238   if (-e $out_file)
8239     {
8240       unlink ($out_file)
8241         or fatal "cannot remove $out_file: $!\n";
8242     }
8244   my $gm_file = new Automake::XFile "> $out_file";
8245   verb "creating $out_file";
8246   print $gm_file $output;
8249 ################################################################
8254 ################################################################
8256 # Print usage information.
8257 sub usage ()
8259     print "Usage: $0 [OPTION] ... [Makefile]...
8261 Generate Makefile.in for configure from Makefile.am.
8263 Operation modes:
8264       --help               print this help, then exit
8265       --version            print version number, then exit
8266   -v, --verbose            verbosely list files processed
8267       --no-force           only update Makefile.in's that are out of date
8268   -W, --warnings=CATEGORY  report the warnings falling in CATEGORY
8270 Dependency tracking:
8271   -i, --ignore-deps      disable dependency tracking code
8272       --include-deps     enable dependency tracking code
8274 Flavors:
8275       --cygnus           assume program is part of Cygnus-style tree
8276       --foreign          set strictness to foreign
8277       --gnits            set strictness to gnits
8278       --gnu              set strictness to gnu
8280 Library files:
8281   -a, --add-missing      add missing standard files to package
8282       --libdir=DIR       directory storing library files
8283   -c, --copy             with -a, copy missing files (default is symlink)
8284   -f, --force-missing    force update of standard files
8287     Automake::ChannelDefs::usage;
8289     my ($last, @lcomm);
8290     $last = '';
8291     foreach my $iter (sort ((@common_files, @common_sometimes)))
8292     {
8293         push (@lcomm, $iter) unless $iter eq $last;
8294         $last = $iter;
8295     }
8297     my @four;
8298     print "\nFiles which are automatically distributed, if found:\n";
8299     format USAGE_FORMAT =
8300   @<<<<<<<<<<<<<<<<   @<<<<<<<<<<<<<<<<   @<<<<<<<<<<<<<<<<   @<<<<<<<<<<<<<<<<
8301   $four[0],           $four[1],           $four[2],           $four[3]
8303     $~ = "USAGE_FORMAT";
8305     my $cols = 4;
8306     my $rows = int(@lcomm / $cols);
8307     my $rest = @lcomm % $cols;
8309     if ($rest)
8310     {
8311         $rows++;
8312     }
8313     else
8314     {
8315         $rest = $cols;
8316     }
8318     for (my $y = 0; $y < $rows; $y++)
8319     {
8320         @four = ("", "", "", "");
8321         for (my $x = 0; $x < $cols; $x++)
8322         {
8323             last if $y + 1 == $rows && $x == $rest;
8325             my $idx = (($x > $rest)
8326                        ?  ($rows * $rest + ($rows - 1) * ($x - $rest))
8327                        : ($rows * $x));
8329             $idx += $y;
8330             $four[$x] = $lcomm[$idx];
8331         }
8332         write;
8333     }
8335     print "\nReport bugs to <bug-automake\@gnu.org>.\n";
8337     # --help always returns 0 per GNU standards.
8338     exit 0;
8342 # &version ()
8343 # -----------
8344 # Print version information
8345 sub version ()
8347   print <<EOF;
8348 automake (GNU $PACKAGE) $VERSION
8349 Copyright (C) 2009 Free Software Foundation, Inc.
8350 License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
8351 This is free software: you are free to change and redistribute it.
8352 There is NO WARRANTY, to the extent permitted by law.
8354 Written by Tom Tromey <tromey\@redhat.com>
8355        and Alexandre Duret-Lutz <adl\@gnu.org>.
8357   # --version always returns 0 per GNU standards.
8358   exit 0;
8361 ################################################################
8363 # Parse command line.
8364 sub parse_arguments ()
8366   # Start off as gnu.
8367   set_strictness ('gnu');
8369   my $cli_where = new Automake::Location;
8370   my %cli_options =
8371     (
8372      'libdir=s' => \$libdir,
8373      'gnu'              => sub { set_strictness ('gnu'); },
8374      'gnits'            => sub { set_strictness ('gnits'); },
8375      'cygnus'           => sub { set_global_option ('cygnus', $cli_where); },
8376      'foreign'          => sub { set_strictness ('foreign'); },
8377      'include-deps'     => sub { unset_global_option ('no-dependencies'); },
8378      'i|ignore-deps'    => sub { set_global_option ('no-dependencies',
8379                                                     $cli_where); },
8380      'no-force' => sub { $force_generation = 0; },
8381      'f|force-missing'  => \$force_missing,
8382      'o|output-dir=s'   => \$output_directory,
8383      'a|add-missing'    => \$add_missing,
8384      'c|copy'           => \$copy_missing,
8385      'v|verbose'        => sub { setup_channel 'verb', silent => 0; },
8386      'W|warnings=s'     => \&parse_warnings,
8387      # These long options (--Werror and --Wno-error) for backward
8388      # compatibility.  Use -Werror and -Wno-error today.
8389      'Werror'           => sub { parse_warnings 'W', 'error'; },
8390      'Wno-error'        => sub { parse_warnings 'W', 'no-error'; },
8391      );
8392   use Getopt::Long;
8393   Getopt::Long::config ("bundling", "pass_through");
8395   # See if --version or --help is used.  We want to process these before
8396   # anything else because the GNU Coding Standards require us to
8397   # `exit 0' after processing these options, and we can't guarantee this
8398   # if we treat other options first.  (Handling other options first
8399   # could produce error diagnostics, and in this condition it is
8400   # confusing if Automake does `exit 0'.)
8401   my %cli_options_1st_pass =
8402     (
8403      'version' => \&version,
8404      'help'    => \&usage,
8405      # Recognize all other options (and their arguments) but do nothing.
8406      map { $_ => sub {} } (keys %cli_options)
8407      );
8408   my @ARGV_backup = @ARGV;
8409   Getopt::Long::GetOptions %cli_options_1st_pass
8410     or exit 1;
8411   @ARGV = @ARGV_backup;
8413   # Now *really* process the options.  This time we know that --help
8414   # and --version are not present, but we specify them nonetheless so
8415   # that ambiguous abbreviation are diagnosed.
8416   Getopt::Long::GetOptions %cli_options, 'version' => sub {}, 'help' => sub {}
8417     or exit 1;
8419   if (defined $output_directory)
8420     {
8421       msg 'obsolete', "`--output-dir' is deprecated\n";
8422     }
8423   else
8424     {
8425       # In the next release we'll remove this entirely.
8426       $output_directory = '.';
8427     }
8429   return unless @ARGV;
8431   if ($ARGV[0] =~ /^-./)
8432     {
8433       my %argopts;
8434       for my $k (keys %cli_options)
8435         {
8436           if ($k =~ /(.*)=s$/)
8437             {
8438               map { $argopts{(length ($_) == 1)
8439                              ? "-$_" : "--$_" } = 1; } (split (/\|/, $1));
8440             }
8441         }
8442       if ($ARGV[0] eq '--')
8443         {
8444           shift @ARGV;
8445         }
8446       elsif (exists $argopts{$ARGV[0]})
8447         {
8448           fatal ("option `$ARGV[0]' requires an argument\n"
8449                  . "Try `$0 --help' for more information.");
8450         }
8451       else
8452         {
8453           fatal ("unrecognized option `$ARGV[0]'.\n"
8454                  . "Try `$0 --help' for more information.");
8455         }
8456     }
8458   my $errspec = 0;
8459   foreach my $arg (@ARGV)
8460     {
8461       fatal ("empty argument\nTry `$0 --help' for more information.")
8462         if ($arg eq '');
8464       # Handle $local:$input syntax.
8465       my ($local, @rest) = split (/:/, $arg);
8466       @rest = ("$local.in",) unless @rest;
8467       my $input = locate_am @rest;
8468       if ($input)
8469         {
8470           push @input_files, $input;
8471           $output_files{$input} = join (':', ($local, @rest));
8472         }
8473       else
8474         {
8475           error "no Automake input file found for `$arg'";
8476           $errspec = 1;
8477         }
8478     }
8479   fatal "no input file found among supplied arguments"
8480     if $errspec && ! @input_files;
8484 # handle_makefile ($MAKEFILE_IN)
8485 # ------------------------------
8486 # Deal with $MAKEFILE_IN.
8487 sub handle_makefile ($)
8489   my ($file) =  @_;
8490   ($am_file = $file) =~ s/\.in$//;
8491   if (! -f ($am_file . '.am'))
8492     {
8493       error "`$am_file.am' does not exist";
8494     }
8495   else
8496     {
8497       # Any warning setting now local to this Makefile.am.
8498       dup_channel_setup;
8500       generate_makefile ($am_file . '.am', $file);
8502       # Back out any warning setting.
8503       drop_channel_setup;
8504     }
8507 # handle_makefiles_serial ()
8508 # --------------------------
8509 # Deal with all makefiles, without threads.
8510 sub handle_makefiles_serial ()
8512   foreach my $file (@input_files)
8513     {
8514       handle_makefile ($file);
8515     }
8518 # get_number_of_threads ()
8519 # ------------------------
8520 # Logic for deciding how many worker threads to use.
8521 sub get_number_of_threads
8523   my $nthreads = $ENV{'AUTOMAKE_JOBS'} || 0;
8525   $nthreads = 0
8526     unless $nthreads =~ /^[0-9]+$/;
8528   # It doesn't make sense to use more threads than makefiles,
8529   my $max_threads = @input_files;
8531   # but a single worker thread is helpful for exposing bugs.
8532   if ($automake_will_process_aux_dir && $max_threads > 1)
8533     {
8534       $max_threads--;
8535     }
8536   if ($nthreads > $max_threads)
8537     {
8538       $nthreads = $max_threads;
8539     }
8540   return $nthreads;
8543 # handle_makefiles_threaded ($NTHREADS)
8544 # -------------------------------------
8545 # Deal with all makefiles, using threads.  The general strategy is to
8546 # spawn NTHREADS worker threads, dispatch makefiles to them, and let the
8547 # worker threads push back everything that needs serialization:
8548 # * warning and (normal) error messages, for stable stderr output
8549 #   order and content (avoiding duplicates, for example),
8550 # * races when installing aux files (and respective messages),
8551 # * races when collecting aux files for distribution.
8553 # The latter requires that the makefile that deals with the aux dir
8554 # files be handled last, done by the master thread.
8555 sub handle_makefiles_threaded ($)
8557   my ($nthreads) = @_;
8559   my @queued_input_files = @input_files;
8560   my $last_input_file = undef;
8561   if ($automake_will_process_aux_dir)
8562     {
8563       $last_input_file = pop @queued_input_files;
8564     }
8566   # The file queue distributes all makefiles, the message queues
8567   # collect all serializations needed for respective files.
8568   my $file_queue = Thread::Queue->new;
8569   my %msg_queues;
8570   foreach my $file (@queued_input_files)
8571     {
8572       $msg_queues{$file} = Thread::Queue->new;
8573     }
8575   verb "spawning $nthreads worker threads";
8576   my @threads = (1 .. $nthreads);
8577   foreach my $t (@threads)
8578     {
8579       $t = threads->new (sub
8580         {
8581           while (my $file = $file_queue->dequeue)
8582             {
8583               verb "handling $file";
8584               my $queue = $msg_queues{$file};
8585               setup_channel_queue ($queue, QUEUE_MESSAGE);
8586               $required_conf_file_queue = $queue;
8587               handle_makefile ($file);
8588               $queue->enqueue (undef);
8589               setup_channel_queue (undef, undef);
8590               $required_conf_file_queue = undef;
8591             }
8592           return $exit_code;
8593         });
8594     }
8596   # Queue all normal makefiles.
8597   verb "queuing " . @queued_input_files . " input files";
8598   $file_queue->enqueue (@queued_input_files, (undef) x @threads);
8600   # Collect and process serializations.
8601   foreach my $file (@queued_input_files)
8602     {
8603       verb "dequeuing messages for " . $file;
8604       reset_local_duplicates ();
8605       my $queue = $msg_queues{$file};
8606       while (my $key = $queue->dequeue)
8607         {
8608           if ($key eq QUEUE_MESSAGE)
8609             {
8610               pop_channel_queue ($queue);
8611             }
8612           elsif ($key eq QUEUE_CONF_FILE)
8613             {
8614               require_queued_conf_file ($queue);
8615             }
8616           else
8617             {
8618               prog_error "unexpected key $key";
8619             }
8620         }
8621     }
8623   foreach my $t (@threads)
8624     {
8625       my @exit_thread = $t->join;
8626       $exit_code = $exit_thread[0]
8627         if ($exit_thread[0] > $exit_code);
8628     }
8630   # The master processes the last file.
8631   if ($automake_will_process_aux_dir)
8632     {
8633       verb "processing last input file";
8634       handle_makefile ($last_input_file);
8635     }
8638 ################################################################
8640 # Parse the WARNINGS environment variable.
8641 parse_WARNINGS;
8643 # Parse command line.
8644 parse_arguments;
8646 $configure_ac = require_configure_ac;
8648 # Do configure.ac scan only once.
8649 scan_autoconf_files;
8651 if (! @input_files)
8652   {
8653     my $msg = '';
8654     $msg = "\nDid you forget AC_CONFIG_FILES([Makefile]) in $configure_ac?"
8655       if -f 'Makefile.am';
8656     fatal ("no `Makefile.am' found for any configure output$msg");
8657   }
8659 my $nthreads = get_number_of_threads ();
8661 if ($perl_threads && $nthreads >= 1)
8662   {
8663     handle_makefiles_threaded ($nthreads);
8664   }
8665 else
8666   {
8667     handle_makefiles_serial ();
8668   }
8670 exit $exit_code;
8673 ### Setup "GNU" style for perl-mode and cperl-mode.
8674 ## Local Variables:
8675 ## perl-indent-level: 2
8676 ## perl-continued-statement-offset: 2
8677 ## perl-continued-brace-offset: 0
8678 ## perl-brace-offset: 0
8679 ## perl-brace-imaginary-offset: 0
8680 ## perl-label-offset: -2
8681 ## cperl-indent-level: 2
8682 ## cperl-brace-offset: 0
8683 ## cperl-continued-brace-offset: 0
8684 ## cperl-label-offset: -2
8685 ## cperl-extra-newline-before-brace: t
8686 ## cperl-merge-trailing-else: nil
8687 ## cperl-continued-statement-offset: 2
8688 ## End: