* tests/java.test: `configure' uses a trap, so use `(exit 77);
[automake/plouj.git] / automake.in
blob8c2269240700b5f7ad0127eb6bb4e5911ac8b3bb
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  Free Software Foundation, Inc.
12 # This program is free software; you can redistribute it and/or modify
13 # it under the terms of the GNU General Public License as published by
14 # the Free Software Foundation; either version 2, or (at your option)
15 # any later version.
17 # This program is distributed in the hope that it will be useful,
18 # but WITHOUT ANY WARRANTY; without even the implied warranty of
19 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20 # GNU General Public License for more details.
22 # You should have received a copy of the GNU General Public License
23 # along with this program; if not, write to the Free Software
24 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
25 # 02110-1301, USA.
27 # Originally written by David Mackenzie <djm@gnu.ai.mit.edu>.
28 # Perl reimplementation by Tom Tromey <tromey@redhat.com>, and
29 # Alexandre Duret-Lutz <adl@gnu.org>.
31 package Language;
33 BEGIN
35   my $perllibdir = $ENV{'perllibdir'} || '@datadir@/@PACKAGE@-@APIVERSION@';
36   unshift @INC, (split '@PATH_SEPARATOR@', $perllibdir);
38   # Override SHELL.  This is required on DJGPP so that system() uses
39   # bash, not COMMAND.COM which doesn't quote arguments properly.
40   # Other systems aren't expected to use $SHELL when Automake
41   # runs, but it should be safe to drop the `if DJGPP' guard if
42   # it turns up other systems need the same thing.  After all,
43   # if SHELL is used, ./configure's SHELL is always better than
44   # the user's SHELL (which may be something like tcsh).
45   $ENV{'SHELL'} = '@SHELL@' if exists $ENV{'DJGPP'};
48 use Automake::Struct;
49 struct (# Short name of the language (c, f77...).
50         'name' => "\$",
51         # Nice name of the language (C, Fortran 77...).
52         'Name' => "\$",
54         # List of configure variables which must be defined.
55         'config_vars' => '@',
57         'ansi'    => "\$",
58         # `pure' is `1' or `'.  A `pure' language is one where, if
59         # all the files in a directory are of that language, then we
60         # do not require the C compiler or any code to call it.
61         'pure'   => "\$",
63         'autodep' => "\$",
65         # Name of the compiling variable (COMPILE).
66         'compiler'  => "\$",
67         # Content of the compiling variable.
68         'compile'  => "\$",
69         # Flag to require compilation without linking (-c).
70         'compile_flag' => "\$",
71         'extensions' => '@',
72         # A subroutine to compute a list of possible extensions of
73         # the product given the input extensions.
74         # (defaults to a subroutine which returns ('.$(OBJEXT)', '.lo'))
75         'output_extensions' => "\$",
76         # A list of flag variables used in 'compile'.
77         # (defaults to [])
78         'flags' => "@",
80         # Any tag to pass to libtool while compiling.
81         'libtool_tag' => "\$",
83         # The file to use when generating rules for this language.
84         # The default is 'depend2'.
85         'rule_file' => "\$",
87         # Name of the linking variable (LINK).
88         'linker' => "\$",
89         # Content of the linking variable.
90         'link' => "\$",
92         # Name of the linker variable (LD).
93         'lder' => "\$",
94         # Content of the linker variable ($(CC)).
95         'ld' => "\$",
97         # Flag to specify the output file (-o).
98         'output_flag' => "\$",
99         '_finish' => "\$",
101         # This is a subroutine which is called whenever we finally
102         # determine the context in which a source file will be
103         # compiled.
104         '_target_hook' => "\$",
106         # If TRUE, nodist_ sources will be compiled using specific rules
107         # (i.e. not inference rules).  The default is FALSE.
108         'nodist_specific' => "\$");
111 sub finish ($)
113   my ($self) = @_;
114   if (defined $self->_finish)
115     {
116       &{$self->_finish} ();
117     }
120 sub target_hook ($$$$%)
122     my ($self) = @_;
123     if (defined $self->_target_hook)
124     {
125         &{$self->_target_hook} (@_);
126     }
129 package Automake;
131 use strict;
132 use Automake::Config;
133 use Automake::General;
134 use Automake::XFile;
135 use Automake::Channels;
136 use Automake::ChannelDefs;
137 use Automake::Configure_ac;
138 use Automake::FileUtils;
139 use Automake::Location;
140 use Automake::Condition qw/TRUE FALSE/;
141 use Automake::DisjConditions;
142 use Automake::Options;
143 use Automake::Version;
144 use Automake::Variable;
145 use Automake::VarDef;
146 use Automake::Rule;
147 use Automake::RuleDef;
148 use Automake::Wrap 'makefile_wrap';
149 use File::Basename;
150 use File::Spec;
151 use Carp;
153 ## ----------- ##
154 ## Constants.  ##
155 ## ----------- ##
157 # Some regular expressions.  One reason to put them here is that it
158 # makes indentation work better in Emacs.
160 # Writing singled-quoted-$-terminated regexes is a pain because
161 # perl-mode thinks of $' as the ${'} variable (instead of a $ followed
162 # by a closing quote.  Letting perl-mode think the quote is not closed
163 # leads to all sort of misindentations.  On the other hand, defining
164 # regexes as double-quoted strings is far less readable.  So usually
165 # we will write:
167 #  $REGEX = '^regex_value' . "\$";
169 my $IGNORE_PATTERN = '^\s*##([^#\n].*)?\n';
170 my $WHITE_PATTERN = '^\s*' . "\$";
171 my $COMMENT_PATTERN = '^#';
172 my $TARGET_PATTERN='[$a-zA-Z_.@%][-.a-zA-Z0-9_(){}/$+@%]*';
173 # A rule has three parts: a list of targets, a list of dependencies,
174 # and optionally actions.
175 my $RULE_PATTERN =
176   "^($TARGET_PATTERN(?:(?:\\\\\n|\\s)+$TARGET_PATTERN)*) *:([^=].*|)\$";
178 # Only recognize leading spaces, not leading tabs.  If we recognize
179 # leading tabs here then we need to make the reader smarter, because
180 # otherwise it will think rules like `foo=bar; \' are errors.
181 my $ASSIGNMENT_PATTERN = '^ *([^ \t=:+]*)\s*([:+]?)=\s*(.*)' . "\$";
182 # This pattern recognizes a Gnits version id and sets $1 if the
183 # release is an alpha release.  We also allow a suffix which can be
184 # used to extend the version number with a "fork" identifier.
185 my $GNITS_VERSION_PATTERN = '\d+\.\d+([a-z]|\.\d+)?(-[A-Za-z0-9]+)?';
187 my $IF_PATTERN = '^if\s+(!?)\s*([A-Za-z][A-Za-z0-9_]*)\s*(?:#.*)?' . "\$";
188 my $ELSE_PATTERN =
189   '^else(?:\s+(!?)\s*([A-Za-z][A-Za-z0-9_]*))?\s*(?:#.*)?' . "\$";
190 my $ENDIF_PATTERN =
191   '^endif(?:\s+(!?)\s*([A-Za-z][A-Za-z0-9_]*))?\s*(?:#.*)?' . "\$";
192 my $PATH_PATTERN = '(\w|[+/.-])+';
193 # This will pass through anything not of the prescribed form.
194 my $INCLUDE_PATTERN = ('^include\s+'
195                        . '((\$\(top_srcdir\)/' . $PATH_PATTERN . ')'
196                        . '|(\$\(srcdir\)/' . $PATH_PATTERN . ')'
197                        . '|([^/\$]' . $PATH_PATTERN . '))\s*(#.*)?' . "\$");
199 # Match `-d' as a command-line argument in a string.
200 my $DASH_D_PATTERN = "(^|\\s)-d(\\s|\$)";
201 # Directories installed during 'install-exec' phase.
202 my $EXEC_DIR_PATTERN =
203   '^(?:bin|sbin|libexec|sysconf|localstate|lib|pkglib|.*exec.*)' . "\$";
205 # Values for AC_CANONICAL_*
206 use constant AC_CANONICAL_BUILD  => 1;
207 use constant AC_CANONICAL_HOST   => 2;
208 use constant AC_CANONICAL_TARGET => 3;
210 # Values indicating when something should be cleaned.
211 use constant MOSTLY_CLEAN     => 0;
212 use constant CLEAN            => 1;
213 use constant DIST_CLEAN       => 2;
214 use constant MAINTAINER_CLEAN => 3;
216 # Libtool files.
217 my @libtool_files = qw(ltmain.sh config.guess config.sub);
218 # ltconfig appears here for compatibility with old versions of libtool.
219 my @libtool_sometimes = qw(ltconfig ltcf-c.sh ltcf-cxx.sh ltcf-gcj.sh);
221 # Commonly found files we look for and automatically include in
222 # DISTFILES.
223 my @common_files =
224     (qw(ABOUT-GNU ABOUT-NLS AUTHORS BACKLOG COPYING COPYING.DOC COPYING.LIB
225         COPYING.LESSER ChangeLog INSTALL NEWS README THANKS TODO
226         ansi2knr.1 ansi2knr.c compile config.guess config.rpath config.sub
227         depcomp elisp-comp install-sh libversion.in mdate-sh missing
228         mkinstalldirs py-compile texinfo.tex ylwrap),
229      @libtool_files, @libtool_sometimes);
231 # Commonly used files we auto-include, but only sometimes.  This list
232 # is used for the --help output only.
233 my @common_sometimes =
234   qw(aclocal.m4 acconfig.h config.h.top config.h.bot configure
235      configure.ac configure.in stamp-vti);
237 # Standard directories from the GNU Coding Standards, and additional
238 # pkg* directories from Automake.  Stored in a hash for fast member check.
239 my %standard_prefix =
240     map { $_ => 1 } (qw(bin data dataroot dvi exec html include info
241                         lib libexec lisp localstate man man1 man2 man3
242                         man4 man5 man6 man7 man8 man9 oldinclude pdf
243                         pkgdatadir pkgincludedir pkglibdir ps sbin
244                         sharedstate sysconf));
246 # Copyright on generated Makefile.ins.
247 my $gen_copyright = "\
248 # Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002,
249 # 2003, 2004, 2005, 2006  Free Software Foundation, Inc.
250 # This Makefile.in is free software; the Free Software Foundation
251 # gives unlimited permission to copy and/or distribute it,
252 # with or without modifications, as long as this notice is preserved.
254 # This program is distributed in the hope that it will be useful,
255 # but WITHOUT ANY WARRANTY, to the extent permitted by law; without
256 # even the implied warranty of MERCHANTABILITY or FITNESS FOR A
257 # PARTICULAR PURPOSE.
260 # These constants are returned by lang_*_rewrite functions.
261 # LANG_SUBDIR means that the resulting object file should be in a
262 # subdir if the source file is.  In this case the file name cannot
263 # have `..' components.
264 use constant LANG_IGNORE  => 0;
265 use constant LANG_PROCESS => 1;
266 use constant LANG_SUBDIR  => 2;
268 # These are used when keeping track of whether an object can be built
269 # by two different paths.
270 use constant COMPILE_LIBTOOL  => 1;
271 use constant COMPILE_ORDINARY => 2;
273 # We can't always associate a location to a variable or a rule,
274 # when its defined by Automake.  We use INTERNAL in this case.
275 use constant INTERNAL => new Automake::Location;
278 ## ---------------------------------- ##
279 ## Variables related to the options.  ##
280 ## ---------------------------------- ##
282 # TRUE if we should always generate Makefile.in.
283 my $force_generation = 1;
285 # From the Perl manual.
286 my $symlink_exists = (eval 'symlink ("", "");', $@ eq '');
288 # TRUE if missing standard files should be installed.
289 my $add_missing = 0;
291 # TRUE if we should copy missing files; otherwise symlink if possible.
292 my $copy_missing = 0;
294 # TRUE if we should always update files that we know about.
295 my $force_missing = 0;
298 ## ---------------------------------------- ##
299 ## Variables filled during files scanning.  ##
300 ## ---------------------------------------- ##
302 # Name of the configure.ac file.
303 my $configure_ac;
305 # Files found by scanning configure.ac for LIBOBJS.
306 my %libsources = ();
308 # Names used in AC_CONFIG_HEADER call.
309 my @config_headers = ();
311 # Names used in AC_CONFIG_LINKS call.
312 my @config_links = ();
314 # Directory where output files go.  Actually, output files are
315 # relative to this directory.
316 my $output_directory;
318 # List of Makefile.am's to process, and their corresponding outputs.
319 my @input_files = ();
320 my %output_files = ();
322 # Complete list of Makefile.am's that exist.
323 my @configure_input_files = ();
325 # List of files in AC_CONFIG_FILES/AC_OUTPUT without Makefile.am's,
326 # and their outputs.
327 my @other_input_files = ();
328 # Where each AC_CONFIG_FILES/AC_OUTPUT/AC_CONFIG_LINK/AC_CONFIG_HEADER appears.
329 # The keys are the files created by these macros.
330 my %ac_config_files_location = ();
332 # Directory to search for configure-required files.  This
333 # will be computed by &locate_aux_dir and can be set using
334 # AC_CONFIG_AUX_DIR in configure.ac.
335 # $CONFIG_AUX_DIR is the `raw' directory, valid only in the source-tree.
336 my $config_aux_dir = '';
337 my $config_aux_dir_set_in_configure_ac = 0;
338 # $AM_CONFIG_AUX_DIR is prefixed with $(top_srcdir), so it can be used
339 # in Makefiles.
340 my $am_config_aux_dir = '';
342 # Directory to search for AC_LIBSOURCE files, as set by AC_CONFIG_LIBOBJ_DIR
343 # in configure.ac.
344 my $config_libobj_dir = '';
346 # Whether AM_GNU_GETTEXT has been seen in configure.ac.
347 my $seen_gettext = 0;
348 # Whether AM_GNU_GETTEXT([external]) is used.
349 my $seen_gettext_external = 0;
350 # Where AM_GNU_GETTEXT appears.
351 my $ac_gettext_location;
353 # Lists of tags supported by Libtool.
354 my %libtool_tags = ();
355 # 1 if Libtool uses LT_SUPPORTED_TAG.  If it does, then it also
356 # uses AC_REQUIRE_AUX_FILE.
357 my $libtool_new_api = 0;
359 # Most important AC_CANONICAL_* macro seen so far.
360 my $seen_canonical = 0;
361 # Location of that macro.
362 my $canonical_location;
364 # Where AM_MAINTAINER_MODE appears.
365 my $seen_maint_mode;
367 # Actual version we've seen.
368 my $package_version = '';
370 # Where version is defined.
371 my $package_version_location;
373 # TRUE if we've seen AC_ENABLE_MULTILIB.
374 my $seen_multilib = 0;
376 # TRUE if we've seen AM_PROG_CC_C_O
377 my $seen_cc_c_o = 0;
379 # Location of AC_REQUIRE_AUX_FILE calls, indexed by their argument.
380 my %required_aux_file = ();
382 # Where AM_INIT_AUTOMAKE is called;
383 my $seen_init_automake = 0;
385 # TRUE if we've seen AM_AUTOMAKE_VERSION.
386 my $seen_automake_version = 0;
388 # Hash table of discovered configure substitutions.  Keys are names,
389 # values are `FILE:LINE' strings which are used by error message
390 # generation.
391 my %configure_vars = ();
393 # Ignored configure substitutions (i.e., variables not to be output in
394 # Makefile.in)
395 my %ignored_configure_vars = ();
397 # Files included by $configure_ac.
398 my @configure_deps = ();
400 # Greatest timestamp of configure's dependencies.
401 my $configure_deps_greatest_timestamp = 0;
403 # Hash table of AM_CONDITIONAL variables seen in configure.
404 my %configure_cond = ();
406 # This maps extensions onto language names.
407 my %extension_map = ();
409 # List of the DIST_COMMON files we discovered while reading
410 # configure.in
411 my $configure_dist_common = '';
413 # This maps languages names onto objects.
414 my %languages = ();
415 # Maps each linker variable onto a language object.
416 my %link_languages = ();
418 # List of targets we must always output.
419 # FIXME: Complete, and remove falsely required targets.
420 my %required_targets =
421   (
422    'all'          => 1,
423    'dvi'          => 1,
424    'pdf'          => 1,
425    'ps'           => 1,
426    'info'         => 1,
427    'install-info' => 1,
428    'install'      => 1,
429    'install-data' => 1,
430    'install-exec' => 1,
431    'uninstall'    => 1,
433    # FIXME: Not required, temporary hacks.
434    # Well, actually they are sort of required: the -recursive
435    # targets will run them anyway...
436    'dvi-am'          => 1,
437    'pdf-am'          => 1,
438    'ps-am'           => 1,
439    'info-am'         => 1,
440    'install-data-am' => 1,
441    'install-exec-am' => 1,
442    'installcheck-am' => 1,
443    'uninstall-am' => 1,
445    'install-man' => 1,
446   );
448 # Set to 1 if this run will create the Makefile.in that distribute
449 # the files in config_aux_dir.
450 my $automake_will_process_aux_dir = 0;
452 # The name of the Makefile currently being processed.
453 my $am_file = 'BUG';
456 ################################################################
458 ## ------------------------------------------ ##
459 ## Variables reset by &initialize_per_input.  ##
460 ## ------------------------------------------ ##
462 # Basename and relative dir of the input file.
463 my $am_file_name;
464 my $am_relative_dir;
466 # Same but wrt Makefile.in.
467 my $in_file_name;
468 my $relative_dir;
470 # Relative path to the top directory.
471 my $topsrcdir;
473 # Greatest timestamp of the output's dependencies (excluding
474 # configure's dependencies).
475 my $output_deps_greatest_timestamp;
477 # These two variables are used when generating each Makefile.in.
478 # They hold the Makefile.in until it is ready to be printed.
479 my $output_rules;
480 my $output_vars;
481 my $output_trailer;
482 my $output_all;
483 my $output_header;
485 # This is the conditional stack, updated on if/else/endif, and
486 # used to build Condition objects.
487 my @cond_stack;
489 # This holds the set of included files.
490 my @include_stack;
492 # This holds a list of directories which we must create at `dist'
493 # time.  This is used in some strange scenarios involving weird
494 # AC_OUTPUT commands.
495 my %dist_dirs;
497 # List of dependencies for the obvious targets.
498 my @all;
499 my @check;
500 my @check_tests;
502 # Keys in this hash table are files to delete.  The associated
503 # value tells when this should happen (MOSTLY_CLEAN, DIST_CLEAN, etc.)
504 my %clean_files;
506 # Keys in this hash table are object files or other files in
507 # subdirectories which need to be removed.  This only holds files
508 # which are created by compilations.  The value in the hash indicates
509 # when the file should be removed.
510 my %compile_clean_files;
512 # Keys in this hash table are directories where we expect to build a
513 # libtool object.  We use this information to decide what directories
514 # to delete.
515 my %libtool_clean_directories;
517 # Value of `$(SOURCES)', used by tags.am.
518 my @sources;
519 # Sources which go in the distribution.
520 my @dist_sources;
522 # This hash maps object file names onto their corresponding source
523 # file names.  This is used to ensure that each object is created
524 # by a single source file.
525 my %object_map;
527 # This hash maps object file names onto an integer value representing
528 # whether this object has been built via ordinary compilation or
529 # libtool compilation (the COMPILE_* constants).
530 my %object_compilation_map;
533 # This keeps track of the directories for which we've already
534 # created dirstamp code.  Keys are directories, values are stamp files.
535 # Several keys can share the same stamp files if they are equivalent
536 # (as are `.//foo' and `foo').
537 my %directory_map;
539 # All .P files.
540 my %dep_files;
542 # This is a list of all targets to run during "make dist".
543 my @dist_targets;
545 # Keep track of all programs declared in this Makefile, without
546 # $(EXEEXT).  @substitution@ are not listed.
547 my %known_programs;
549 # Keys in this hash are the basenames of files which must depend on
550 # ansi2knr.  Values are either the empty string, or the directory in
551 # which the ANSI source file appears; the directory must have a
552 # trailing `/'.
553 my %de_ansi_files;
555 # This is the name of the redirect `all' target to use.
556 my $all_target;
558 # This keeps track of which extensions we've seen (that we care
559 # about).
560 my %extension_seen;
562 # This is random scratch space for the language finish functions.
563 # Don't randomly overwrite it; examine other uses of keys first.
564 my %language_scratch;
566 # We keep track of which objects need special (per-executable)
567 # handling on a per-language basis.
568 my %lang_specific_files;
570 # This is set when `handle_dist' has finished.  Once this happens,
571 # we should no longer push on dist_common.
572 my $handle_dist_run;
574 # Used to store a set of linkers needed to generate the sources currently
575 # under consideration.
576 my %linkers_used;
578 # True if we need `LINK' defined.  This is a hack.
579 my $need_link;
581 # Was get_object_extension run?
582 # FIXME: This is a hack. a better switch should be found.
583 my $get_object_extension_was_run;
585 # Record each file processed by make_paragraphs.
586 my %transformed_files;
588 # Cache each file processed by make_paragraphs.
589 # (This is different from %transformed_files because
590 # %transformed_files is reset for each file while %am_file_cache
591 # it global to the run.)
592 my %am_file_cache;
594 ################################################################
596 # var_SUFFIXES_trigger ($TYPE, $VALUE)
597 # ------------------------------------
598 # This is called by Automake::Variable::define() when SUFFIXES
599 # is defined ($TYPE eq '') or appended ($TYPE eq '+').
600 # The work here needs to be performed as a side-effect of the
601 # macro_define() call because SUFFIXES definitions impact
602 # on $KNOWN_EXTENSIONS_PATTERN which is used used when parsing
603 # the input am file.
604 sub var_SUFFIXES_trigger ($$)
606     my ($type, $value) = @_;
607     accept_extensions (split (' ', $value));
609 Automake::Variable::hook ('SUFFIXES', \&var_SUFFIXES_trigger);
611 ################################################################
613 ## --------------------------------- ##
614 ## Forward subroutine declarations.  ##
615 ## --------------------------------- ##
616 sub register_language (%);
617 sub file_contents_internal ($$$%);
618 sub define_files_variable ($\@$$);
621 # &initialize_per_input ()
622 # ------------------------
623 # (Re)-Initialize per-Makefile.am variables.
624 sub initialize_per_input ()
626     reset_local_duplicates ();
628     $am_file_name = '';
629     $am_relative_dir = '';
631     $in_file_name = '';
632     $relative_dir = '';
634     $output_deps_greatest_timestamp = 0;
636     $output_rules = '';
637     $output_vars = '';
638     $output_trailer = '';
639     $output_all = '';
640     $output_header = '';
642     Automake::Options::reset;
643     Automake::Variable::reset;
644     Automake::Rule::reset;
646     @cond_stack = ();
648     @include_stack = ();
650     %dist_dirs = ();
652     @all = ();
653     @check = ();
654     @check_tests = ();
656     %clean_files = ();
658     @sources = ();
659     @dist_sources = ();
661     %object_map = ();
662     %object_compilation_map = ();
664     %directory_map = ();
666     %dep_files = ();
668     @dist_targets = ();
670     %known_programs = ();
672     %de_ansi_files = ();
674     $all_target = '';
676     %extension_seen = ();
678     %language_scratch = ();
680     %lang_specific_files = ();
682     $handle_dist_run = 0;
684     $need_link = 0;
686     $get_object_extension_was_run = 0;
688     %compile_clean_files = ();
690     # We always include `.'.  This isn't strictly correct.
691     %libtool_clean_directories = ('.' => 1);
693     %transformed_files = ();
697 ################################################################
699 # Initialize our list of languages that are internally supported.
701 # C.
702 register_language ('name' => 'c',
703                    'Name' => 'C',
704                    'config_vars' => ['CC'],
705                    'ansi' => 1,
706                    'autodep' => '',
707                    'flags' => ['CFLAGS', 'CPPFLAGS'],
708                    'compiler' => 'COMPILE',
709                    'compile' => '$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS)',
710                    'lder' => 'CCLD',
711                    'ld' => '$(CC)',
712                    'linker' => 'LINK',
713                    'link' => '$(CCLD) $(AM_CFLAGS) $(CFLAGS) $(AM_LDFLAGS) $(LDFLAGS) -o $@',
714                    'compile_flag' => '-c',
715                    'libtool_tag' => 'CC',
716                    'extensions' => ['.c'],
717                    '_finish' => \&lang_c_finish);
719 # C++.
720 register_language ('name' => 'cxx',
721                    'Name' => 'C++',
722                    'config_vars' => ['CXX'],
723                    'linker' => 'CXXLINK',
724                    'link' => '$(CXXLD) $(AM_CXXFLAGS) $(CXXFLAGS) $(AM_LDFLAGS) $(LDFLAGS) -o $@',
725                    'autodep' => 'CXX',
726                    'flags' => ['CXXFLAGS', 'CPPFLAGS'],
727                    'compile' => '$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS)',
728                    'compiler' => 'CXXCOMPILE',
729                    'compile_flag' => '-c',
730                    'output_flag' => '-o',
731                    'libtool_tag' => 'CXX',
732                    'lder' => 'CXXLD',
733                    'ld' => '$(CXX)',
734                    'pure' => 1,
735                    'extensions' => ['.c++', '.cc', '.cpp', '.cxx', '.C']);
737 # Objective C.
738 register_language ('name' => 'objc',
739                    'Name' => 'Objective C',
740                    'config_vars' => ['OBJC'],
741                    'linker' => 'OBJCLINK',,
742                    'link' => '$(OBJCLD) $(AM_OBJCFLAGS) $(OBJCFLAGS) $(AM_LDFLAGS) $(LDFLAGS) -o $@',
743                    'autodep' => 'OBJC',
744                    'flags' => ['OBJCFLAGS', 'CPPFLAGS'],
745                    'compile' => '$(OBJC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_OBJCFLAGS) $(OBJCFLAGS)',
746                    'compiler' => 'OBJCCOMPILE',
747                    'compile_flag' => '-c',
748                    'output_flag' => '-o',
749                    'lder' => 'OBJCLD',
750                    'ld' => '$(OBJC)',
751                    'pure' => 1,
752                    'extensions' => ['.m']);
754 # Headers.
755 register_language ('name' => 'header',
756                    'Name' => 'Header',
757                    'extensions' => ['.h', '.H', '.hxx', '.h++', '.hh',
758                                     '.hpp', '.inc'],
759                    # No output.
760                    'output_extensions' => sub { return () },
761                    # Nothing to do.
762                    '_finish' => sub { });
764 # Yacc (C & C++).
765 register_language ('name' => 'yacc',
766                    'Name' => 'Yacc',
767                    'config_vars' => ['YACC'],
768                    'flags' => ['YFLAGS'],
769                    'compile' => '$(YACC) $(YFLAGS) $(AM_YFLAGS)',
770                    'compiler' => 'YACCCOMPILE',
771                    'extensions' => ['.y'],
772                    'output_extensions' => sub { (my $ext = $_[0]) =~ tr/y/c/;
773                                                 return ($ext,) },
774                    'rule_file' => 'yacc',
775                    '_finish' => \&lang_yacc_finish,
776                    '_target_hook' => \&lang_yacc_target_hook,
777                    'nodist_specific' => 1);
778 register_language ('name' => 'yaccxx',
779                    'Name' => 'Yacc (C++)',
780                    'config_vars' => ['YACC'],
781                    'rule_file' => 'yacc',
782                    'flags' => ['YFLAGS'],
783                    'compiler' => 'YACCCOMPILE',
784                    'compile' => '$(YACC) $(YFLAGS) $(AM_YFLAGS)',
785                    'extensions' => ['.y++', '.yy', '.yxx', '.ypp'],
786                    'output_extensions' => sub { (my $ext = $_[0]) =~ tr/y/c/;
787                                                 return ($ext,) },
788                    '_finish' => \&lang_yacc_finish,
789                    '_target_hook' => \&lang_yacc_target_hook,
790                    'nodist_specific' => 1);
792 # Lex (C & C++).
793 register_language ('name' => 'lex',
794                    'Name' => 'Lex',
795                    'config_vars' => ['LEX'],
796                    'rule_file' => 'lex',
797                    'flags' => ['LFLAGS'],
798                    'compile' => '$(LEX) $(LFLAGS) $(AM_LFLAGS)',
799                    'compiler' => 'LEXCOMPILE',
800                    'extensions' => ['.l'],
801                    'output_extensions' => sub { (my $ext = $_[0]) =~ tr/l/c/;
802                                                 return ($ext,) },
803                    '_finish' => \&lang_lex_finish,
804                    '_target_hook' => \&lang_lex_target_hook,
805                    'nodist_specific' => 1);
806 register_language ('name' => 'lexxx',
807                    'Name' => 'Lex (C++)',
808                    'config_vars' => ['LEX'],
809                    'rule_file' => 'lex',
810                    'flags' => ['LFLAGS'],
811                    'compile' => '$(LEX) $(LFLAGS) $(AM_LFLAGS)',
812                    'compiler' => 'LEXCOMPILE',
813                    'extensions' => ['.l++', '.ll', '.lxx', '.lpp'],
814                    'output_extensions' => sub { (my $ext = $_[0]) =~ tr/l/c/;
815                                                 return ($ext,) },
816                    '_finish' => \&lang_lex_finish,
817                    '_target_hook' => \&lang_lex_target_hook,
818                    'nodist_specific' => 1);
820 # Assembler.
821 register_language ('name' => 'asm',
822                    'Name' => 'Assembler',
823                    'config_vars' => ['CCAS', 'CCASFLAGS'],
825                    'flags' => ['CCASFLAGS'],
826                    # Users can set AM_CCASFLAGS to include DEFS, INCLUDES,
827                    # or anything else required.  They can also set CCAS.
828                    'compile' => '$(CCAS) $(AM_CCASFLAGS) $(CCASFLAGS)',
829                    'compiler' => 'CCASCOMPILE',
830                    'compile_flag' => '-c',
831                    'extensions' => ['.s'],
833                    # With assembly we still use the C linker.
834                    '_finish' => \&lang_c_finish);
836 # Preprocessed Assembler.
837 register_language ('name' => 'cppasm',
838                    'Name' => 'Preprocessed Assembler',
839                    'config_vars' => ['CCAS', 'CCASFLAGS'],
841                    'autodep' => 'CCAS',
842                    'flags' => ['CCASFLAGS', 'CPPFLAGS'],
843                    # Users can set AM_CCASFLAGS to include DEFS, INCLUDES,
844                    # or anything else required beyond AM_CPPFLAGS.  They
845                    # can also set CCAS.
846                    'compile' => '$(CCAS) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CCASFLAGS) $(CCASFLAGS)',
847                    'compiler' => 'CPPASCOMPILE',
848                    'compile_flag' => '-c',
849                    'extensions' => ['.S'],
851                    # With assembly we still use the C linker.
852                    '_finish' => \&lang_c_finish);
854 # Fortran 77
855 register_language ('name' => 'f77',
856                    'Name' => 'Fortran 77',
857                    'linker' => 'F77LINK',
858                    'link' => '$(F77LD) $(AM_FFLAGS) $(FFLAGS) $(AM_LDFLAGS) $(LDFLAGS) -o $@',
859                    'flags' => ['FFLAGS'],
860                    'compile' => '$(F77) $(AM_FFLAGS) $(FFLAGS)',
861                    'compiler' => 'F77COMPILE',
862                    'compile_flag' => '-c',
863                    'output_flag' => '-o',
864                    'libtool_tag' => 'F77',
865                    'lder' => 'F77LD',
866                    'ld' => '$(F77)',
867                    'pure' => 1,
868                    'extensions' => ['.f', '.for']);
870 # Fortran
871 register_language ('name' => 'fc',
872                    'Name' => 'Fortran',
873                    'linker' => 'FCLINK',
874                    'link' => '$(FCLD) $(AM_FCFLAGS) $(FCFLAGS) $(AM_LDFLAGS) $(LDFLAGS) -o $@',
875                    'flags' => ['FCFLAGS'],
876                    'compile' => '$(FC) $(AM_FCFLAGS) $(FCFLAGS)',
877                    'compiler' => 'FCCOMPILE',
878                    'compile_flag' => '-c',
879                    'output_flag' => '-o',
880                    'lder' => 'FCLD',
881                    'ld' => '$(FC)',
882                    'pure' => 1,
883                    'extensions' => ['.f90', '.f95']);
885 # Preprocessed Fortran
886 register_language ('name' => 'ppfc',
887                    'Name' => 'Preprocessed Fortran',
888                    'config_vars' => ['FC'],
889                    'linker' => 'FCLINK',
890                    'link' => '$(FCLD) $(AM_FCFLAGS) $(FCFLAGS) $(AM_LDFLAGS) $(LDFLAGS) -o $@',
891                    'lder' => 'FCLD',
892                    'ld' => '$(FC)',
893                    'flags' => ['FCFLAGS', 'CPPFLAGS'],
894                    'compiler' => 'PPFCCOMPILE',
895                    'compile' => '$(FC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_FCFLAGS) $(FCFLAGS)',
896                    'compile_flag' => '-c',
897                    'output_flag' => '-o',
898                    'libtool_tag' => 'FC',
899                    'pure' => 1,
900                    'extensions' => ['.F90','.F95']);
902 # Preprocessed Fortran 77
904 # The current support for preprocessing Fortran 77 just involves
905 # passing `$(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS)
906 # $(CPPFLAGS)' as additional flags to the Fortran 77 compiler, since
907 # this is how GNU Make does it; see the `GNU Make Manual, Edition 0.51
908 # for `make' Version 3.76 Beta' (specifically, from info file
909 # `(make)Catalogue of Rules').
911 # A better approach would be to write an Autoconf test
912 # (i.e. AC_PROG_FPP) for a Fortran 77 preprocessor, because not all
913 # Fortran 77 compilers know how to do preprocessing.  The Autoconf
914 # macro AC_PROG_FPP should test the Fortran 77 compiler first for
915 # preprocessing capabilities, and then fall back on cpp (if cpp were
916 # available).
917 register_language ('name' => 'ppf77',
918                    'Name' => 'Preprocessed Fortran 77',
919                    'config_vars' => ['F77'],
920                    'linker' => 'F77LINK',
921                    'link' => '$(F77LD) $(AM_FFLAGS) $(FFLAGS) $(AM_LDFLAGS) $(LDFLAGS) -o $@',
922                    'lder' => 'F77LD',
923                    'ld' => '$(F77)',
924                    'flags' => ['FFLAGS', 'CPPFLAGS'],
925                    'compiler' => 'PPF77COMPILE',
926                    'compile' => '$(F77) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_FFLAGS) $(FFLAGS)',
927                    'compile_flag' => '-c',
928                    'output_flag' => '-o',
929                    'libtool_tag' => 'F77',
930                    'pure' => 1,
931                    'extensions' => ['.F']);
933 # Ratfor.
934 register_language ('name' => 'ratfor',
935                    'Name' => 'Ratfor',
936                    'config_vars' => ['F77'],
937                    'linker' => 'F77LINK',
938                    'link' => '$(F77LD) $(AM_FFLAGS) $(FFLAGS) $(AM_LDFLAGS) $(LDFLAGS) -o $@',
939                    'lder' => 'F77LD',
940                    'ld' => '$(F77)',
941                    'flags' => ['RFLAGS', 'FFLAGS'],
942                    # FIXME also FFLAGS.
943                    'compile' => '$(F77) $(AM_FFLAGS) $(FFLAGS) $(AM_RFLAGS) $(RFLAGS)',
944                    'compiler' => 'RCOMPILE',
945                    'compile_flag' => '-c',
946                    'output_flag' => '-o',
947                    'libtool_tag' => 'F77',
948                    'pure' => 1,
949                    'extensions' => ['.r']);
951 # Java via gcj.
952 register_language ('name' => 'java',
953                    'Name' => 'Java',
954                    'config_vars' => ['GCJ'],
955                    'linker' => 'GCJLINK',
956                    'link' => '$(GCJLD) $(AM_GCJFLAGS) $(GCJFLAGS) $(AM_LDFLAGS) $(LDFLAGS) -o $@',
957                    'autodep' => 'GCJ',
958                    'flags' => ['GCJFLAGS'],
959                    'compile' => '$(GCJ) $(AM_GCJFLAGS) $(GCJFLAGS)',
960                    'compiler' => 'GCJCOMPILE',
961                    'compile_flag' => '-c',
962                    'output_flag' => '-o',
963                    'libtool_tag' => 'GCJ',
964                    'lder' => 'GCJLD',
965                    'ld' => '$(GCJ)',
966                    'pure' => 1,
967                    'extensions' => ['.java', '.class', '.zip', '.jar']);
969 ################################################################
971 # Error reporting functions.
973 # err_am ($MESSAGE, [%OPTIONS])
974 # -----------------------------
975 # Uncategorized errors about the current Makefile.am.
976 sub err_am ($;%)
978   msg_am ('error', @_);
981 # err_ac ($MESSAGE, [%OPTIONS])
982 # -----------------------------
983 # Uncategorized errors about configure.ac.
984 sub err_ac ($;%)
986   msg_ac ('error', @_);
989 # msg_am ($CHANNEL, $MESSAGE, [%OPTIONS])
990 # ---------------------------------------
991 # Messages about about the current Makefile.am.
992 sub msg_am ($$;%)
994   my ($channel, $msg, %opts) = @_;
995   msg $channel, "${am_file}.am", $msg, %opts;
998 # msg_ac ($CHANNEL, $MESSAGE, [%OPTIONS])
999 # ---------------------------------------
1000 # Messages about about configure.ac.
1001 sub msg_ac ($$;%)
1003   my ($channel, $msg, %opts) = @_;
1004   msg $channel, $configure_ac, $msg, %opts;
1007 ################################################################
1009 # subst ($TEXT)
1010 # -------------
1011 # Return a configure-style substitution using the indicated text.
1012 # We do this to avoid having the substitutions directly in automake.in;
1013 # when we do that they are sometimes removed and this causes confusion
1014 # and bugs.
1015 sub subst ($)
1017     my ($text) = @_;
1018     return '@' . $text . '@';
1021 ################################################################
1024 # $BACKPATH
1025 # &backname ($REL-DIR)
1026 # --------------------
1027 # If I `cd $REL-DIR', then to come back, I should `cd $BACKPATH'.
1028 # For instance `src/foo' => `../..'.
1029 # Works with non strictly increasing paths, i.e., `src/../lib' => `..'.
1030 sub backname ($)
1032     my ($file) = @_;
1033     my @res;
1034     foreach (split (/\//, $file))
1035     {
1036         next if $_ eq '.' || $_ eq '';
1037         if ($_ eq '..')
1038         {
1039             pop @res;
1040         }
1041         else
1042         {
1043             push (@res, '..');
1044         }
1045     }
1046     return join ('/', @res) || '.';
1049 ################################################################
1052 # Handle AUTOMAKE_OPTIONS variable.  Return 1 on error, 0 otherwise.
1053 sub handle_options
1055   my $var = var ('AUTOMAKE_OPTIONS');
1056   if ($var)
1057     {
1058       # FIXME: We should disallow conditional definitions of AUTOMAKE_OPTIONS.
1059       if (process_option_list ($var->rdef (TRUE)->location,
1060                                $var->value_as_list_recursive (cond_filter =>
1061                                                               TRUE)))
1062         {
1063           return 1;
1064         }
1065     }
1067   if ($strictness == GNITS)
1068     {
1069       set_option ('readme-alpha', INTERNAL);
1070       set_option ('std-options', INTERNAL);
1071       set_option ('check-news', INTERNAL);
1072     }
1074   return 0;
1077 # shadow_unconditionally ($varname, $where)
1078 # -----------------------------------------
1079 # Return a $(variable) that contains all possible values
1080 # $varname can take.
1081 # If the VAR wasn't defined conditionally, return $(VAR).
1082 # Otherwise we create a am__VAR_DIST variable which contains
1083 # all possible values, and return $(am__VAR_DIST).
1084 sub shadow_unconditionally ($$)
1086   my ($varname, $where) = @_;
1087   my $var = var $varname;
1088   if ($var->has_conditional_contents)
1089     {
1090       $varname = "am__${varname}_DIST";
1091       my @files = uniq ($var->value_as_list_recursive);
1092       define_pretty_variable ($varname, TRUE, $where, @files);
1093     }
1094   return "\$($varname)"
1097 # get_object_extension ($EXTENSION)
1098 # ---------------------------------
1099 # Prefix $EXTENSION with $U if ansi2knr is in use.
1100 sub get_object_extension ($)
1102     my ($extension) = @_;
1104     # Check for automatic de-ANSI-fication.
1105     $extension = '$U' . $extension
1106       if option 'ansi2knr';
1108     $get_object_extension_was_run = 1;
1110     return $extension;
1113 # check_user_variables (@LIST)
1114 # ----------------------------
1115 # Make sure each variable VAR in @LIST do not exist, suggest using AM_VAR
1116 # otherwise.
1117 sub check_user_variables (@)
1119   my @dont_override = @_;
1120   foreach my $flag (@dont_override)
1121     {
1122       my $var = var $flag;
1123       if ($var)
1124         {
1125           for my $cond ($var->conditions->conds)
1126             {
1127               if ($var->rdef ($cond)->owner == VAR_MAKEFILE)
1128                 {
1129                   msg_cond_var ('gnu', $cond, $flag,
1130                                 "`$flag' is a user variable, "
1131                                 . "you should not override it;\n"
1132                                 . "use `AM_$flag' instead.");
1133                 }
1134             }
1135         }
1136     }
1139 # Call finish function for each language that was used.
1140 sub handle_languages
1142     if (! option 'no-dependencies')
1143     {
1144         # Include auto-dep code.  Don't include it if DEP_FILES would
1145         # be empty.
1146         if (&saw_sources_p (0) && keys %dep_files)
1147         {
1148             # Set location of depcomp.
1149             &define_variable ('depcomp',
1150                               "\$(SHELL) $am_config_aux_dir/depcomp",
1151                               INTERNAL);
1152             &define_variable ('am__depfiles_maybe', 'depfiles', INTERNAL);
1154             require_conf_file ("$am_file.am", FOREIGN, 'depcomp');
1156             my @deplist = sort keys %dep_files;
1157             # Generate each `include' individually.  Irix 6 make will
1158             # not properly include several files resulting from a
1159             # variable expansion; generating many separate includes
1160             # seems safest.
1161             $output_rules .= "\n";
1162             foreach my $iter (@deplist)
1163             {
1164                 $output_rules .= (subst ('AMDEP_TRUE')
1165                                   . subst ('am__include')
1166                                   . ' '
1167                                   . subst ('am__quote')
1168                                   . $iter
1169                                   . subst ('am__quote')
1170                                   . "\n");
1171             }
1173             # Compute the set of directories to remove in distclean-depend.
1174             my @depdirs = uniq (map { dirname ($_) } @deplist);
1175             $output_rules .= &file_contents ('depend',
1176                                              new Automake::Location,
1177                                              DEPDIRS => "@depdirs");
1178         }
1179     }
1180     else
1181     {
1182         &define_variable ('depcomp', '', INTERNAL);
1183         &define_variable ('am__depfiles_maybe', '', INTERNAL);
1184     }
1186     my %done;
1188     # Is the c linker needed?
1189     my $needs_c = 0;
1190     foreach my $ext (sort keys %extension_seen)
1191     {
1192         next unless $extension_map{$ext};
1194         my $lang = $languages{$extension_map{$ext}};
1196         my $rule_file = $lang->rule_file || 'depend2';
1198         # Get information on $LANG.
1199         my $pfx = $lang->autodep;
1200         my $fpfx = ($pfx eq '') ? 'CC' : $pfx;
1202         my ($AMDEP, $FASTDEP) =
1203           (option 'no-dependencies' || $lang->autodep eq 'no')
1204           ? ('FALSE', 'FALSE') : ('AMDEP', "am__fastdep$fpfx");
1206         my %transform = ('EXT'     => $ext,
1207                          'PFX'     => $pfx,
1208                          'FPFX'    => $fpfx,
1209                          'AMDEP'   => $AMDEP,
1210                          'FASTDEP' => $FASTDEP,
1211                          '-c'      => $lang->compile_flag || '',
1212                          'MORE-THAN-ONE'
1213                                    => (count_files_for_language ($lang->name) > 1),
1214                          # These are not used, but they need to be defined
1215                          # so &transform do not complain.
1216                          SUBDIROBJ     => 0,
1217                          'DERIVED-EXT' => 'BUG',
1218                          DIST_SOURCE   => 1,
1219                         );
1221         # Generate the appropriate rules for this extension.
1222         if (((! option 'no-dependencies') && $lang->autodep ne 'no')
1223             || defined $lang->compile)
1224         {
1225             # Some C compilers don't support -c -o.  Use it only if really
1226             # needed.
1227             my $output_flag = $lang->output_flag || '';
1228             $output_flag = '-o'
1229               if (! $output_flag
1230                   && $lang->name eq 'c'
1231                   && option 'subdir-objects');
1233             # Compute a possible derived extension.
1234             # This is not used by depend2.am.
1235             my $der_ext = (&{$lang->output_extensions} ($ext))[0];
1237             # When we output an inference rule like `.c.o:' we
1238             # have two cases to consider: either subdir-objects
1239             # is used, or it is not.
1240             #
1241             # In the latter case the rule is used to build objects
1242             # in the current directory, and dependencies always
1243             # go into `./$(DEPDIR)/'.  We can hard-code this value.
1244             #
1245             # In the former case the rule can be used to build
1246             # objects in sub-directories too.  Dependencies should
1247             # go into the appropriate sub-directories, e.g.,
1248             # `sub/$(DEPDIR)/'.  The value of this directory
1249             # need the be computed on-the-fly.
1250             #
1251             # DEPBASE holds the name of this directory, plus the
1252             # basename part of the object file (extensions Po, TPo,
1253             # Plo, TPlo will be added later as appropriate).  It is
1254             # either hardcoded, or a shell variable (`$depbase') that
1255             # will be computed by the rule.
1256             my $depbase =
1257               option ('subdir-objects') ? '$$depbase' : '$(DEPDIR)/$*';
1258             $output_rules .=
1259               file_contents ($rule_file,
1260                              new Automake::Location,
1261                              %transform,
1262                              GENERIC   => 1,
1264                              'DERIVED-EXT' => $der_ext,
1266                              DEPBASE   => $depbase,
1267                              BASE      => '$*',
1268                              SOURCE    => '$<',
1269                              OBJ       => '$@',
1270                              OBJOBJ    => '$@',
1271                              LTOBJ     => '$@',
1273                              COMPILE   => '$(' . $lang->compiler . ')',
1274                              LTCOMPILE => '$(LT' . $lang->compiler . ')',
1275                              -o        => $output_flag,
1276                              SUBDIROBJ => !! option 'subdir-objects');
1277         }
1279         # Now include code for each specially handled object with this
1280         # language.
1281         my %seen_files = ();
1282         foreach my $file (@{$lang_specific_files{$lang->name}})
1283         {
1284             my ($derived, $source, $obj, $myext, %file_transform) = @$file;
1286             # We might see a given object twice, for instance if it is
1287             # used under different conditions.
1288             next if defined $seen_files{$obj};
1289             $seen_files{$obj} = 1;
1291             prog_error ("found " . $lang->name .
1292                         " in handle_languages, but compiler not defined")
1293               unless defined $lang->compile;
1295             my $obj_compile = $lang->compile;
1297             # Rewrite each occurrence of `AM_$flag' in the compile
1298             # rule into `${derived}_$flag' if it exists.
1299             for my $flag (@{$lang->flags})
1300               {
1301                 my $val = "${derived}_$flag";
1302                 $obj_compile =~ s/\(AM_$flag\)/\($val\)/
1303                   if set_seen ($val);
1304               }
1306             my $libtool_tag = '';
1307             if ($lang->libtool_tag && exists $libtool_tags{$lang->libtool_tag})
1308               {
1309                 $libtool_tag = '--tag=' . $lang->libtool_tag . ' '
1310               }
1312             my $ptltflags = "${derived}_LIBTOOLFLAGS";
1313             $ptltflags = 'AM_LIBTOOLFLAGS' unless set_seen $ptltflags;
1315             my $obj_ltcompile =
1316               "\$(LIBTOOL) $libtool_tag\$($ptltflags) \$(LIBTOOLFLAGS) "
1317               . "--mode=compile $obj_compile";
1319             # We _need_ `-o' for per object rules.
1320             my $output_flag = $lang->output_flag || '-o';
1322             my $depbase = dirname ($obj);
1323             $depbase = ''
1324                 if $depbase eq '.';
1325             $depbase .= '/'
1326                 unless $depbase eq '';
1327             $depbase .= '$(DEPDIR)/' . basename ($obj);
1329             # Support for deansified files in subdirectories is ugly
1330             # enough to deserve an explanation.
1331             #
1332             # A Note about normal ansi2knr processing first.  On
1333             #
1334             #   AUTOMAKE_OPTIONS = ansi2knr
1335             #   bin_PROGRAMS = foo
1336             #   foo_SOURCES = foo.c
1337             #
1338             # we generate rules similar to:
1339             #
1340             #   foo: foo$U.o; link ...
1341             #   foo$U.o: foo$U.c; compile ...
1342             #   foo_.c: foo.c; ansi2knr ...
1343             #
1344             # this is fairly compact, and will call ansi2knr depending
1345             # on the value of $U (`' or `_').
1346             #
1347             # It's harder with subdir sources. On
1348             #
1349             #   AUTOMAKE_OPTIONS = ansi2knr
1350             #   bin_PROGRAMS = foo
1351             #   foo_SOURCES = sub/foo.c
1352             #
1353             # we have to create foo_.c in the current directory.
1354             # (Unless the user asks 'subdir-objects'.)  This is important
1355             # in case the same file (`foo.c') is compiled from other
1356             # directories with different cpp options: foo_.c would
1357             # be preprocessed for only one set of options if it were
1358             # put in the subdirectory.
1359             #
1360             # Because foo$U.o must be built from either foo_.c or
1361             # sub/foo.c we can't be as concise as in the first example.
1362             # Instead we output
1363             #
1364             #   foo: foo$U.o; link ...
1365             #   foo_.o: foo_.c; compile ...
1366             #   foo.o: sub/foo.c; compile ...
1367             #   foo_.c: foo.c; ansi2knr ...
1368             #
1369             # This is why we'll now transform $rule_file twice
1370             # if we detect this case.
1371             # A first time we output the compile rule with `$U'
1372             # replaced by `_' and the source directory removed,
1373             # and another time we simply remove `$U'.
1374             #
1375             # Note that at this point $source (as computed by
1376             # &handle_single_transform) is `sub/foo$U.c'.
1377             # This can be confusing: it can be used as-is when
1378             # subdir-objects is set, otherwise you have to know
1379             # it really means `foo_.c' or `sub/foo.c'.
1380             my $objdir = dirname ($obj);
1381             my $srcdir = dirname ($source);
1382             if ($lang->ansi && $obj =~ /\$U/)
1383               {
1384                 prog_error "`$obj' contains \$U, but `$source' doesn't."
1385                   if $source !~ /\$U/;
1387                 (my $source_ = $source) =~ s/\$U/_/g;
1388                 # Output an additional rule if _.c and .c are not in
1389                 # the same directory.  (_.c is always in $objdir.)
1390                 if ($objdir ne $srcdir)
1391                   {
1392                     (my $obj_ = $obj) =~ s/\$U/_/g;
1393                     (my $depbase_ = $depbase) =~ s/\$U/_/g;
1394                     $source_ = basename ($source_);
1396                     $output_rules .=
1397                       file_contents ($rule_file,
1398                                      new Automake::Location,
1399                                      %transform,
1400                                      GENERIC   => 0,
1402                                      DEPBASE   => $depbase_,
1403                                      BASE      => $obj_,
1404                                      SOURCE    => $source_,
1405                                      OBJ       => "$obj_$myext",
1406                                      OBJOBJ    => "$obj_.obj",
1407                                      LTOBJ     => "$obj_.lo",
1409                                      COMPILE   => $obj_compile,
1410                                      LTCOMPILE => $obj_ltcompile,
1411                                      -o        => $output_flag,
1412                                      %file_transform);
1413                     $obj =~ s/\$U//g;
1414                     $depbase =~ s/\$U//g;
1415                     $source =~ s/\$U//g;
1416                   }
1417               }
1419             $output_rules .=
1420               file_contents ($rule_file,
1421                              new Automake::Location,
1422                              %transform,
1423                              GENERIC   => 0,
1425                              DEPBASE   => $depbase,
1426                              BASE      => $obj,
1427                              SOURCE    => $source,
1428                              # Use $myext and not `.o' here, in case
1429                              # we are actually building a new source
1430                              # file -- e.g. via yacc.
1431                              OBJ       => "$obj$myext",
1432                              OBJOBJ    => "$obj.obj",
1433                              LTOBJ     => "$obj.lo",
1435                              COMPILE   => $obj_compile,
1436                              LTCOMPILE => $obj_ltcompile,
1437                              -o        => $output_flag,
1438                              %file_transform);
1439         }
1441         # The rest of the loop is done once per language.
1442         next if defined $done{$lang};
1443         $done{$lang} = 1;
1445         # Load the language dependent Makefile chunks.
1446         my %lang = map { uc ($_) => 0 } keys %languages;
1447         $lang{uc ($lang->name)} = 1;
1448         $output_rules .= file_contents ('lang-compile',
1449                                         new Automake::Location,
1450                                         %transform, %lang);
1452         # If the source to a program consists entirely of code from a
1453         # `pure' language, for instance C++ or Fortran 77, then we
1454         # don't need the C compiler code.  However if we run into
1455         # something unusual then we do generate the C code.  There are
1456         # probably corner cases here that do not work properly.
1457         # People linking Java code to Fortran code deserve pain.
1458         $needs_c ||= ! $lang->pure;
1460         define_compiler_variable ($lang)
1461           if ($lang->compile);
1463         define_linker_variable ($lang)
1464           if ($lang->link);
1466         require_variables ("$am_file.am", $lang->Name . " source seen",
1467                            TRUE, @{$lang->config_vars});
1469         # Call the finisher.
1470         $lang->finish;
1472         # Flags listed in `->flags' are user variables (per GNU Standards),
1473         # they should not be overridden in the Makefile...
1474         my @dont_override = @{$lang->flags};
1475         # ... and so is LDFLAGS.
1476         push @dont_override, 'LDFLAGS' if $lang->link;
1478         check_user_variables @dont_override;
1479     }
1481     # If the project is entirely C++ or entirely Fortran 77 (i.e., 1
1482     # suffix rule was learned), don't bother with the C stuff.  But if
1483     # anything else creeps in, then use it.
1484     $needs_c = 1
1485       if $need_link || suffix_rules_count > 1;
1487     if ($needs_c)
1488       {
1489         &define_compiler_variable ($languages{'c'})
1490           unless defined $done{$languages{'c'}};
1491         define_linker_variable ($languages{'c'});
1492       }
1496 # append_exeext { PREDICATE } $MACRO
1497 # ----------------------------------
1498 # Append $(EXEEXT) to each filename in $F appearing in the Makefile
1499 # variable $MACRO if &PREDICATE($F) is true.  @substitutions@ are
1500 # ignored.
1502 # This is typically used on all filenames of *_PROGRAMS, and filenames
1503 # of TESTS that are programs.
1504 sub append_exeext (&$)
1506   my ($pred, $macro) = @_;
1508   transform_variable_recursively
1509     ($macro, $macro, 'am__EXEEXT', 0, INTERNAL,
1510      sub {
1511        my ($subvar, $val, $cond, $full_cond) = @_;
1512        # Append $(EXEEXT) unless the user did it already, or it's a
1513        # @substitution@.
1514        $val .= '$(EXEEXT)'
1515          if $val !~ /(?:\$\(EXEEXT\)$|^[@]\w+[@]$)/ && &$pred ($val);
1516        return $val;
1517      });
1521 # Check to make sure a source defined in LIBOBJS is not explicitly
1522 # mentioned.  This is a separate function (as opposed to being inlined
1523 # in handle_source_transform) because it isn't always appropriate to
1524 # do this check.
1525 sub check_libobjs_sources
1527   my ($one_file, $unxformed) = @_;
1529   foreach my $prefix ('', 'EXTRA_', 'dist_', 'nodist_',
1530                       'dist_EXTRA_', 'nodist_EXTRA_')
1531     {
1532       my @files;
1533       my $varname = $prefix . $one_file . '_SOURCES';
1534       my $var = var ($varname);
1535       if ($var)
1536         {
1537           @files = $var->value_as_list_recursive;
1538         }
1539       elsif ($prefix eq '')
1540         {
1541           @files = ($unxformed . '.c');
1542         }
1543       else
1544         {
1545           next;
1546         }
1548       foreach my $file (@files)
1549         {
1550           err_var ($prefix . $one_file . '_SOURCES',
1551                    "automatically discovered file `$file' should not" .
1552                    " be explicitly mentioned")
1553             if defined $libsources{$file};
1554         }
1555     }
1559 # @OBJECTS
1560 # handle_single_transform ($VAR, $TOPPARENT, $DERIVED, $OBJ, $FILE, %TRANSFORM)
1561 # -----------------------------------------------------------------------------
1562 # Does much of the actual work for handle_source_transform.
1563 # Arguments are:
1564 #   $VAR is the name of the variable that the source filenames come from
1565 #   $TOPPARENT is the name of the _SOURCES variable which is being processed
1566 #   $DERIVED is the name of resulting executable or library
1567 #   $OBJ is the object extension (e.g., `$U.lo')
1568 #   $FILE the source file to transform
1569 #   %TRANSFORM contains extras arguments to pass to file_contents
1570 #     when producing explicit rules
1571 # Result is a list of the names of objects
1572 # %linkers_used will be updated with any linkers needed
1573 sub handle_single_transform ($$$$$%)
1575     my ($var, $topparent, $derived, $obj, $_file, %transform) = @_;
1576     my @files = ($_file);
1577     my @result = ();
1578     my $nonansi_obj = $obj;
1579     $nonansi_obj =~ s/\$U//g;
1581     # Turn sources into objects.  We use a while loop like this
1582     # because we might add to @files in the loop.
1583     while (scalar @files > 0)
1584     {
1585         $_ = shift @files;
1587         # Configure substitutions in _SOURCES variables are errors.
1588         if (/^\@.*\@$/)
1589         {
1590           my $parent_msg = '';
1591           $parent_msg = "\nand is referred to from `$topparent'"
1592             if $topparent ne $var->name;
1593           err_var ($var,
1594                    "`" . $var->name . "' includes configure substitution `$_'"
1595                    . $parent_msg . ";\nconfigure " .
1596                    "substitutions are not allowed in _SOURCES variables");
1597           next;
1598         }
1600         # If the source file is in a subdirectory then the `.o' is put
1601         # into the current directory, unless the subdir-objects option
1602         # is in effect.
1604         # Split file name into base and extension.
1605         next if ! /^(?:(.*)\/)?([^\/]*)($KNOWN_EXTENSIONS_PATTERN)$/;
1606         my $full = $_;
1607         my $directory = $1 || '';
1608         my $base = $2;
1609         my $extension = $3;
1611         # We must generate a rule for the object if it requires its own flags.
1612         my $renamed = 0;
1613         my ($linker, $object);
1615         # This records whether we've seen a derived source file (e.g.
1616         # yacc output).
1617         my $derived_source = 0;
1619         # This holds the `aggregate context' of the file we are
1620         # currently examining.  If the file is compiled with
1621         # per-object flags, then it will be the name of the object.
1622         # Otherwise it will be `AM'.  This is used by the target hook
1623         # language function.
1624         my $aggregate = 'AM';
1626         $extension = &derive_suffix ($extension, $nonansi_obj);
1627         my $lang;
1628         if ($extension_map{$extension} &&
1629             ($lang = $languages{$extension_map{$extension}}))
1630         {
1631             # Found the language, so see what it says.
1632             &saw_extension ($extension);
1634             # Do we have per-executable flags for this executable?
1635             my $have_per_exec_flags = 0;
1636             my @peflags = @{$lang->flags};
1637             push @peflags, 'LIBTOOLFLAGS' if $nonansi_obj eq '.lo';
1638             foreach my $flag (@peflags)
1639               {
1640                 if (set_seen ("${derived}_$flag"))
1641                   {
1642                     $have_per_exec_flags = 1;
1643                     last;
1644                   }
1645               }
1647             # Note: computed subr call.  The language rewrite function
1648             # should return one of the LANG_* constants.  It could
1649             # also return a list whose first value is such a constant
1650             # and whose second value is a new source extension which
1651             # should be applied.  This means this particular language
1652             # generates another source file which we must then process
1653             # further.
1654             my $subr = \&{'lang_' . $lang->name . '_rewrite'};
1655             my ($r, $source_extension)
1656                 = &$subr ($directory, $base, $extension,
1657                           $nonansi_obj, $have_per_exec_flags, $var);
1658             # Skip this entry if we were asked not to process it.
1659             next if $r == LANG_IGNORE;
1661             # Now extract linker and other info.
1662             $linker = $lang->linker;
1664             my $this_obj_ext;
1665             if (defined $source_extension)
1666             {
1667                 $this_obj_ext = $source_extension;
1668                 $derived_source = 1;
1669             }
1670             elsif ($lang->ansi)
1671             {
1672                 $this_obj_ext = $obj;
1673             }
1674             else
1675             {
1676                 $this_obj_ext = $nonansi_obj;
1677             }
1678             $object = $base . $this_obj_ext;
1680             if ($have_per_exec_flags)
1681             {
1682                 # We have a per-executable flag in effect for this
1683                 # object.  In this case we rewrite the object's
1684                 # name to ensure it is unique.
1686                 # We choose the name `DERIVED_OBJECT' to ensure
1687                 # (1) uniqueness, and (2) continuity between
1688                 # invocations.  However, this will result in a
1689                 # name that is too long for losing systems, in
1690                 # some situations.  So we provide _SHORTNAME to
1691                 # override.
1693                 my $dname = $derived;
1694                 my $var = var ($derived . '_SHORTNAME');
1695                 if ($var)
1696                 {
1697                     # FIXME: should use the same Condition as
1698                     # the _SOURCES variable.  But this is really
1699                     # silly overkill -- nobody should have
1700                     # conditional shortnames.
1701                     $dname = $var->variable_value;
1702                 }
1703                 $object = $dname . '-' . $object;
1705                 prog_error ($lang->name . " flags defined without compiler")
1706                   if ! defined $lang->compile;
1708                 $renamed = 1;
1709             }
1711             # If rewrite said it was ok, put the object into a
1712             # subdir.
1713             if ($r == LANG_SUBDIR && $directory ne '')
1714             {
1715                 $object = $directory . '/' . $object;
1716             }
1718             # If the object file has been renamed (because per-target
1719             # flags are used) we cannot compile the file with an
1720             # inference rule: we need an explicit rule.
1721             #
1722             # If the source is in a subdirectory and the object is in
1723             # the current directory, we also need an explicit rule.
1724             #
1725             # If both source and object files are in a subdirectory
1726             # (this happens when the subdir-objects option is used),
1727             # then the inference will work.
1728             #
1729             # The latter case deserves a historical note.  When the
1730             # subdir-objects option was added on 1999-04-11 it was
1731             # thought that inferences rules would work for
1732             # subdirectory objects too.  Later, on 1999-11-22,
1733             # automake was changed to output explicit rules even for
1734             # subdir-objects.  Nobody remembers why, but this occured
1735             # soon after the merge of the user-dep-gen-branch so it
1736             # might be related.  In late 2003 people complained about
1737             # the size of the generated Makefile.ins (libgcj, with
1738             # 2200+ subdir objects was reported to have a 9MB
1739             # Makefile), so we now rely on inference rules again.
1740             # Maybe we'll run across the same issue as in the past,
1741             # but at least this time we can document it.  However since
1742             # dependency tracking has evolved it is possible that
1743             # our old problem no longer exists.
1744             # Using inference rules for subdir-objects has been tested
1745             # with GNU make, Solaris make, Ultrix make, BSD make,
1746             # HP-UX make, and OSF1 make successfully.
1747             if ($renamed
1748                 || ($directory ne '' && ! option 'subdir-objects')
1749                 # We must also use specific rules for a nodist_ source
1750                 # if its language requests it.
1751                 || ($lang->nodist_specific && ! $transform{'DIST_SOURCE'}))
1752             {
1753                 my $obj_sans_ext = substr ($object, 0,
1754                                            - length ($this_obj_ext));
1755                 my $full_ansi = $full;
1756                 if ($lang->ansi && option 'ansi2knr')
1757                   {
1758                     $full_ansi =~ s/$KNOWN_EXTENSIONS_PATTERN$/\$U$&/;
1759                     $obj_sans_ext .= '$U';
1760                   }
1762                 my @specifics = ($full_ansi, $obj_sans_ext,
1763                                  # Only use $this_obj_ext in the derived
1764                                  # source case because in the other case we
1765                                  # *don't* want $(OBJEXT) to appear here.
1766                                  ($derived_source ? $this_obj_ext : '.o'));
1768                 # If we renamed the object then we want to use the
1769                 # per-executable flag name.  But if this is simply a
1770                 # subdir build then we still want to use the AM_ flag
1771                 # name.
1772                 if ($renamed)
1773                   {
1774                     unshift @specifics, $derived;
1775                     $aggregate = $derived;
1776                   }
1777                 else
1778                   {
1779                     unshift @specifics, 'AM';
1780                   }
1782                 # Each item on this list is a reference to a list consisting
1783                 # of four values followed by additional transform flags for
1784                 # file_contents.   The four values are the derived flag prefix
1785                 # (e.g. for `foo_CFLAGS', it is `foo'), the name of the
1786                 # source file, the base name of the output file, and
1787                 # the extension for the object file.
1788                 push (@{$lang_specific_files{$lang->name}},
1789                       [@specifics, %transform]);
1790             }
1791         }
1792         elsif ($extension eq $nonansi_obj)
1793         {
1794             # This is probably the result of a direct suffix rule.
1795             # In this case we just accept the rewrite.
1796             $object = "$base$extension";
1797             $object = "$directory/$object" if $directory ne '';
1798             $linker = '';
1799         }
1800         else
1801         {
1802             # No error message here.  Used to have one, but it was
1803             # very unpopular.
1804             # FIXME: we could potentially do more processing here,
1805             # perhaps treating the new extension as though it were a
1806             # new source extension (as above).  This would require
1807             # more restructuring than is appropriate right now.
1808             next;
1809         }
1811         err_am "object `$object' created by `$full' and `$object_map{$object}'"
1812           if (defined $object_map{$object}
1813               && $object_map{$object} ne $full);
1815         my $comp_val = (($object =~ /\.lo$/)
1816                         ? COMPILE_LIBTOOL : COMPILE_ORDINARY);
1817         (my $comp_obj = $object) =~ s/\.lo$/.\$(OBJEXT)/;
1818         if (defined $object_compilation_map{$comp_obj}
1819             && $object_compilation_map{$comp_obj} != 0
1820             # Only see the error once.
1821             && ($object_compilation_map{$comp_obj}
1822                 != (COMPILE_LIBTOOL | COMPILE_ORDINARY))
1823             && $object_compilation_map{$comp_obj} != $comp_val)
1824           {
1825             err_am "object `$comp_obj' created both with libtool and without";
1826           }
1827         $object_compilation_map{$comp_obj} |= $comp_val;
1829         if (defined $lang)
1830         {
1831             # Let the language do some special magic if required.
1832             $lang->target_hook ($aggregate, $object, $full, %transform);
1833         }
1835         if ($derived_source)
1836           {
1837             prog_error ($lang->name . " has automatic dependency tracking")
1838               if $lang->autodep ne 'no';
1839             # Make sure this new source file is handled next.  That will
1840             # make it appear to be at the right place in the list.
1841             unshift (@files, $object);
1842             # Distribute derived sources unless the source they are
1843             # derived from is not.
1844             &push_dist_common ($object)
1845               unless ($topparent =~ /^(?:nobase_)?nodist_/);
1846             next;
1847           }
1849         $linkers_used{$linker} = 1;
1851         push (@result, $object);
1853         if (! defined $object_map{$object})
1854         {
1855             my @dep_list = ();
1856             $object_map{$object} = $full;
1858             # If resulting object is in subdir, we need to make
1859             # sure the subdir exists at build time.
1860             if ($object =~ /\//)
1861             {
1862                 # FIXME: check that $DIRECTORY is somewhere in the
1863                 # project
1865                 # For Java, the way we're handling it right now, a
1866                 # `..' component doesn't make sense.
1867                 if ($lang && $lang->name eq 'java' && $object =~ /(\/|^)\.\.\//)
1868                   {
1869                     err_am "`$full' should not contain a `..' component";
1870                   }
1872                 # Make sure object is removed by `make mostlyclean'.
1873                 $compile_clean_files{$object} = MOSTLY_CLEAN;
1874                 # If we have a libtool object then we also must remove
1875                 # the ordinary .o.
1876                 if ($object =~ /\.lo$/)
1877                 {
1878                     (my $xobj = $object) =~ s,lo$,\$(OBJEXT),;
1879                     $compile_clean_files{$xobj} = MOSTLY_CLEAN;
1881                     # Remove any libtool object in this directory.
1882                     $libtool_clean_directories{$directory} = 1;
1883                 }
1885                 push (@dep_list, require_build_directory ($directory));
1887                 # If we're generating dependencies, we also want
1888                 # to make sure that the appropriate subdir of the
1889                 # .deps directory is created.
1890                 push (@dep_list,
1891                       require_build_directory ($directory . '/$(DEPDIR)'))
1892                   unless option 'no-dependencies';
1893             }
1895             &pretty_print_rule ($object . ':', "\t", @dep_list)
1896                 if scalar @dep_list > 0;
1897         }
1899         # Transform .o or $o file into .P file (for automatic
1900         # dependency code).
1901         if ($lang && $lang->autodep ne 'no')
1902         {
1903             my $depfile = $object;
1904             $depfile =~ s/\.([^.]*)$/.P$1/;
1905             $depfile =~ s/\$\(OBJEXT\)$/o/;
1906             $dep_files{dirname ($depfile) . '/$(DEPDIR)/'
1907                          . basename ($depfile)} = 1;
1908         }
1909     }
1911     return @result;
1915 # $LINKER
1916 # define_objects_from_sources ($VAR, $OBJVAR, $NODEFINE, $ONE_FILE,
1917 #                              $OBJ, $PARENT, $TOPPARENT, $WHERE, %TRANSFORM)
1918 # ---------------------------------------------------------------------------
1919 # Define an _OBJECTS variable for a _SOURCES variable (or subvariable)
1921 # Arguments are:
1922 #   $VAR is the name of the _SOURCES variable
1923 #   $OBJVAR is the name of the _OBJECTS variable if known (otherwise
1924 #     it will be generated and returned).
1925 #   $NODEFINE is a boolean: if true, $OBJVAR will not be defined (but
1926 #     work done to determine the linker will be).
1927 #   $ONE_FILE is the canonical (transformed) name of object to build
1928 #   $OBJ is the object extension (i.e. either `.o' or `.lo').
1929 #   $TOPPARENT is the _SOURCES variable being processed.
1930 #   $WHERE context into which this definition is done
1931 #   %TRANSFORM extra arguments to pass to file_contents when producing
1932 #     rules
1934 # Result is a pair ($LINKER, $OBJVAR):
1935 #    $LINKER is a boolean, true if a linker is needed to deal with the objects
1936 sub define_objects_from_sources ($$$$$$$%)
1938   my ($var, $objvar, $nodefine, $one_file,
1939       $obj, $topparent, $where, %transform) = @_;
1941   my $needlinker = "";
1943   transform_variable_recursively
1944     ($var, $objvar, 'am__objects', $nodefine, $where,
1945      # The transform code to run on each filename.
1946      sub {
1947        my ($subvar, $val, $cond, $full_cond) = @_;
1948        my @trans = handle_single_transform ($subvar, $topparent,
1949                                             $one_file, $obj, $val,
1950                                             %transform);
1951        $needlinker = "true" if @trans;
1952        return @trans;
1953      });
1955   return $needlinker;
1959 # handle_source_transform ($CANON_TARGET, $TARGET, $OBJEXT, $WHERE, %TRANSFORM)
1960 # -----------------------------------------------------------------------------
1961 # Handle SOURCE->OBJECT transform for one program or library.
1962 # Arguments are:
1963 #   canonical (transformed) name of target to build
1964 #   actual target of object to build
1965 #   object extension (i.e., either `.o' or `$o')
1966 #   location of the source variable
1967 #   extra arguments to pass to file_contents when producing rules
1968 # Return the name of the linker variable that must be used.
1969 # Empty return means just use `LINK'.
1970 sub handle_source_transform ($$$$%)
1972     # one_file is canonical name.  unxformed is given name.  obj is
1973     # object extension.
1974     my ($one_file, $unxformed, $obj, $where, %transform) = @_;
1976     my $linker = '';
1978     # No point in continuing if _OBJECTS is defined.
1979     return if reject_var ($one_file . '_OBJECTS',
1980                           $one_file . '_OBJECTS should not be defined');
1982     my %used_pfx = ();
1983     my $needlinker;
1984     %linkers_used = ();
1985     foreach my $prefix ('', 'EXTRA_', 'dist_', 'nodist_',
1986                         'dist_EXTRA_', 'nodist_EXTRA_')
1987     {
1988         my $varname = $prefix . $one_file . "_SOURCES";
1989         my $var = var $varname;
1990         next unless $var;
1992         # We are going to define _OBJECTS variables using the prefix.
1993         # Then we glom them all together.  So we can't use the null
1994         # prefix here as we need it later.
1995         my $xpfx = ($prefix eq '') ? 'am_' : $prefix;
1997         # Keep track of which prefixes we saw.
1998         $used_pfx{$xpfx} = 1
1999           unless $prefix =~ /EXTRA_/;
2001         push @sources, "\$($varname)";
2002         push @dist_sources, shadow_unconditionally ($varname, $where)
2003           unless (option ('no-dist') || $prefix =~ /^nodist_/);
2005         $needlinker |=
2006             define_objects_from_sources ($varname,
2007                                          $xpfx . $one_file . '_OBJECTS',
2008                                          $prefix =~ /EXTRA_/,
2009                                          $one_file, $obj, $varname, $where,
2010                                          DIST_SOURCE => ($prefix !~ /^nodist_/),
2011                                          %transform);
2012     }
2013     if ($needlinker)
2014     {
2015         $linker ||= &resolve_linker (%linkers_used);
2016     }
2018     my @keys = sort keys %used_pfx;
2019     if (scalar @keys == 0)
2020     {
2021         # The default source for libfoo.la is libfoo.c, but for
2022         # backward compatibility we first look at libfoo_la.c
2023         my $old_default_source = "$one_file.c";
2024         (my $default_source = $unxformed) =~ s,(\.[^./\\]*)?$,.c,;
2025         if ($old_default_source ne $default_source
2026             && (rule $old_default_source
2027                 || rule '$(srcdir)/' . $old_default_source
2028                 || rule '${srcdir}/' . $old_default_source
2029                 || -f $old_default_source))
2030           {
2031             my $loc = $where->clone;
2032             $loc->pop_context;
2033             msg ('obsolete', $loc,
2034                  "the default source for `$unxformed' has been changed "
2035                  . "to `$default_source'.\n(Using `$old_default_source' for "
2036                  . "backward compatibility.)");
2037             $default_source = $old_default_source;
2038           }
2039         # If a rule exists to build this source with a $(srcdir)
2040         # prefix, use that prefix in our variables too.  This is for
2041         # the sake of BSD Make.
2042         if (rule '$(srcdir)/' . $default_source
2043             || rule '${srcdir}/' . $default_source)
2044           {
2045             $default_source = '$(srcdir)/' . $default_source;
2046           }
2048         &define_variable ($one_file . "_SOURCES", $default_source, $where);
2049         push (@sources, $default_source);
2050         push (@dist_sources, $default_source);
2052         %linkers_used = ();
2053         my (@result) =
2054           handle_single_transform ($one_file . '_SOURCES',
2055                                    $one_file . '_SOURCES',
2056                                    $one_file, $obj,
2057                                    $default_source, %transform);
2058         $linker ||= &resolve_linker (%linkers_used);
2059         define_pretty_variable ($one_file . '_OBJECTS', TRUE, $where, @result);
2060     }
2061     else
2062     {
2063         @keys = map { '$(' . $_ . $one_file . '_OBJECTS)' } @keys;
2064         define_pretty_variable ($one_file . '_OBJECTS', TRUE, $where, @keys);
2065     }
2067     # If we want to use `LINK' we must make sure it is defined.
2068     if ($linker eq '')
2069     {
2070         $need_link = 1;
2071     }
2073     return $linker;
2077 # handle_lib_objects ($XNAME, $VAR)
2078 # ---------------------------------
2079 # Special-case ALLOCA and LIBOBJS substitutions in _LDADD or _LIBADD variables.
2080 # Also, generate _DEPENDENCIES variable if appropriate.
2081 # Arguments are:
2082 #   transformed name of object being built, or empty string if no object
2083 #   name of _LDADD/_LIBADD-type variable to examine
2084 # Returns 1 if LIBOBJS seen, 0 otherwise.
2085 sub handle_lib_objects
2087   my ($xname, $varname) = @_;
2089   my $var = var ($varname);
2090   prog_error "handle_lib_objects: `$varname' undefined"
2091     unless $var;
2092   prog_error "handle_lib_objects: unexpected variable name `$varname'"
2093     unless $varname =~ /^(.*)(?:LIB|LD)ADD$/;
2094   my $prefix = $1 || 'AM_';
2096   my $seen_libobjs = 0;
2097   my $flagvar = 0;
2099   transform_variable_recursively
2100     ($varname, $xname . '_DEPENDENCIES', 'am__DEPENDENCIES',
2101      ! $xname, INTERNAL,
2102      # Transformation function, run on each filename.
2103      sub {
2104        my ($subvar, $val, $cond, $full_cond) = @_;
2106        if ($val =~ /^-/)
2107          {
2108            # Skip -lfoo and -Ldir silently; these are explicitly allowed.
2109            if ($val !~ /^-[lL]/ &&
2110                # Skip -dlopen and -dlpreopen; these are explicitly allowed
2111                # for Libtool libraries or programs.  (Actually we are a bit
2112                # laxest here since this code also applies to non-libtool
2113                # libraries or programs, for which -dlopen and -dlopreopen
2114                # are pure non-sence.  Diagnosting this doesn't seems very
2115                # important: the developer will quickly get complaints from
2116                # the linker.)
2117                $val !~ /^-dl(?:pre)?open$/ &&
2118                # Only get this error once.
2119                ! $flagvar)
2120              {
2121                $flagvar = 1;
2122                # FIXME: should display a stack of nested variables
2123                # as context when $var != $subvar.
2124                err_var ($var, "linker flags such as `$val' belong in "
2125                         . "`${prefix}LDFLAGS");
2126              }
2127            return ();
2128          }
2129        elsif ($val !~ /^\@.*\@$/)
2130          {
2131            # Assume we have a file of some sort, and output it into the
2132            # dependency variable.  Autoconf substitutions are not output;
2133            # rarely is a new dependency substituted into e.g. foo_LDADD
2134            # -- but bad things (e.g. -lX11) are routinely substituted.
2135            # Note that LIBOBJS and ALLOCA are exceptions to this rule,
2136            # and handled specially below.
2137            return $val;
2138          }
2139        elsif ($val =~ /^\@(LT)?LIBOBJS\@$/)
2140          {
2141            handle_LIBOBJS ($subvar, $cond, $1);
2142            $seen_libobjs = 1;
2143            return $val;
2144          }
2145        elsif ($val =~ /^\@(LT)?ALLOCA\@$/)
2146          {
2147            handle_ALLOCA ($subvar, $cond, $1);
2148            return $val;
2149          }
2150        else
2151          {
2152            return ();
2153          }
2154      });
2156   return $seen_libobjs;
2159 # handle_LIBOBJS_or_ALLOCA ($VAR)
2160 # -------------------------------
2161 # Definitions common to LIBOBJS and ALLOCA.
2162 # VAR should be one of LIBOBJS, LTLIBOBJS, ALLOCA, or LTALLOCA.
2163 sub handle_LIBOBJS_or_ALLOCA ($)
2165   my ($var) = @_;
2167   my $dir = $config_libobj_dir ? "$config_libobj_dir/" : '';
2169   # If LIBOBJS files must be built in another directory we have
2170   # to define LIBOBJDIR and ensure the files get cleaned.
2171   # Otherwise LIBOBJDIR can be left undefined, and the cleaning
2172   # is achieved by `rm -f *.($OBJEXT)' in compile.am.
2173   if ($config_libobj_dir
2174       && $relative_dir ne $config_libobj_dir)
2175     {
2176       if (option 'subdir-objects')
2177         {
2178           define_variable ('LIBOBJDIR', "\$(top_builddir)/$dir", INTERNAL);
2179           $clean_files{"\$($var)"} = MOSTLY_CLEAN;
2180           # If LTLIBOBJS is used, we must also clear LIBOBJS (which might
2181           # be created by libtool as a side-effect of creating LTLIBOBJS).
2182           $clean_files{"\$($var)"} = MOSTLY_CLEAN if $var =~ s/^LT//;
2184         }
2185       else
2186         {
2187           error ("`\$($var)' cannot be used outside `$dir' if"
2188                  . " `subdir-objects' is not set");
2189         }
2190     }
2192   return $dir;
2195 sub handle_LIBOBJS ($$$)
2197   my ($var, $cond, $lt) = @_;
2198   $lt ||= '';
2199   my $myobjext = ($1 ? 'l' : '') . 'o';
2201   $var->requires_variables ("\@${lt}LIBOBJS\@ used", $lt . 'LIBOBJS')
2202     if ! keys %libsources;
2204   my $dir = handle_LIBOBJS_or_ALLOCA "${lt}LIBOBJS";
2206   foreach my $iter (keys %libsources)
2207     {
2208       if ($iter =~ /\.[cly]$/)
2209         {
2210           &saw_extension ($&);
2211           &saw_extension ('.c');
2212         }
2214       if ($iter =~ /\.h$/)
2215         {
2216           require_libsource_with_macro ($cond, $var, FOREIGN, $iter);
2217         }
2218       elsif ($iter ne 'alloca.c')
2219         {
2220           my $rewrite = $iter;
2221           $rewrite =~ s/\.c$/.P$myobjext/;
2222           $dep_files{$dir . '$(DEPDIR)/' . $rewrite} = 1;
2223           $rewrite = "^" . quotemeta ($iter) . "\$";
2224           # Only require the file if it is not a built source.
2225           my $bs = var ('BUILT_SOURCES');
2226           if (! $bs || ! grep (/$rewrite/, $bs->value_as_list_recursive))
2227             {
2228               require_libsource_with_macro ($cond, $var, FOREIGN, $iter);
2229             }
2230         }
2231     }
2234 sub handle_ALLOCA ($$$)
2236   my ($var, $cond, $lt) = @_;
2237   my $myobjext = ($lt ? 'l' : '') . 'o';
2238   $lt ||= '';
2239   my $dir = handle_LIBOBJS_or_ALLOCA "${lt}ALLOCA";
2241   $var->requires_variables ("\@${lt}ALLOCA\@ used", $lt . 'ALLOCA');
2242   $dep_files{$dir . '$(DEPDIR)/alloca.P' . $myobjext} = 1;
2243   require_libsource_with_macro ($cond, $var, FOREIGN, 'alloca.c');
2244   &saw_extension ('.c');
2247 # Canonicalize the input parameter
2248 sub canonicalize
2250     my ($string) = @_;
2251     $string =~ tr/A-Za-z0-9_\@/_/c;
2252     return $string;
2255 # Canonicalize a name, and check to make sure the non-canonical name
2256 # is never used.  Returns canonical name.  Arguments are name and a
2257 # list of suffixes to check for.
2258 sub check_canonical_spelling
2260   my ($name, @suffixes) = @_;
2262   my $xname = &canonicalize ($name);
2263   if ($xname ne $name)
2264     {
2265       foreach my $xt (@suffixes)
2266         {
2267           reject_var ("$name$xt", "use `$xname$xt', not `$name$xt'");
2268         }
2269     }
2271   return $xname;
2275 # handle_compile ()
2276 # -----------------
2277 # Set up the compile suite.
2278 sub handle_compile ()
2280     return
2281       unless $get_object_extension_was_run;
2283     # Boilerplate.
2284     my $default_includes = '';
2285     if (! option 'nostdinc')
2286       {
2287         $default_includes = ' -I. -I$(srcdir)';
2289         my $var = var 'CONFIG_HEADER';
2290         if ($var)
2291           {
2292             foreach my $hdr (split (' ', $var->variable_value))
2293               {
2294                 $default_includes .= ' -I' . dirname ($hdr);
2295               }
2296           }
2297       }
2299     my (@mostly_rms, @dist_rms);
2300     foreach my $item (sort keys %compile_clean_files)
2301     {
2302         if ($compile_clean_files{$item} == MOSTLY_CLEAN)
2303         {
2304             push (@mostly_rms, "\t-rm -f $item");
2305         }
2306         elsif ($compile_clean_files{$item} == DIST_CLEAN)
2307         {
2308             push (@dist_rms, "\t-rm -f $item");
2309         }
2310         else
2311         {
2312           prog_error 'invalid entry in %compile_clean_files';
2313         }
2314     }
2316     my ($coms, $vars, $rules) =
2317       &file_contents_internal (1, "$libdir/am/compile.am",
2318                                new Automake::Location,
2319                                ('DEFAULT_INCLUDES' => $default_includes,
2320                                 'MOSTLYRMS' => join ("\n", @mostly_rms),
2321                                 'DISTRMS' => join ("\n", @dist_rms)));
2322     $output_vars .= $vars;
2323     $output_rules .= "$coms$rules";
2325     # Check for automatic de-ANSI-fication.
2326     if (option 'ansi2knr')
2327       {
2328         my ($ansi2knr_filename, $ansi2knr_where) = @{option 'ansi2knr'};
2329         my $ansi2knr_dir = '';
2331         require_variables ($ansi2knr_where, "option `ansi2knr' is used",
2332                            TRUE, "ANSI2KNR", "U");
2334         # topdir is where ansi2knr should be.
2335         if ($ansi2knr_filename eq 'ansi2knr')
2336           {
2337             # Only require ansi2knr files if they should appear in
2338             # this directory.
2339             require_file ($ansi2knr_where, FOREIGN,
2340                           'ansi2knr.c', 'ansi2knr.1');
2342             # ansi2knr needs to be built before subdirs, so unshift it.
2343             unshift (@all, '$(ANSI2KNR)');
2344           }
2345         else
2346           {
2347             $ansi2knr_dir = dirname ($ansi2knr_filename);
2348           }
2350         $output_rules .= &file_contents ('ansi2knr',
2351                                          new Automake::Location,
2352                                          'ANSI2KNR-DIR' => $ansi2knr_dir);
2354     }
2357 # handle_libtool ()
2358 # -----------------
2359 # Handle libtool rules.
2360 sub handle_libtool
2362   return unless var ('LIBTOOL');
2364   # Libtool requires some files, but only at top level.
2365   # (Starting with Libtool 2.0 we do not have to bother.  These
2366   # requirements are done with AC_REQUIRE_AUX_FILE.)
2367   require_conf_file_with_macro (TRUE, 'LIBTOOL', FOREIGN, @libtool_files)
2368     if $relative_dir eq '.' && ! $libtool_new_api;
2370   my @libtool_rms;
2371   foreach my $item (sort keys %libtool_clean_directories)
2372     {
2373       my $dir = ($item eq '.') ? '' : "$item/";
2374       # .libs is for Unix, _libs for DOS.
2375       push (@libtool_rms, "\t-rm -rf ${dir}.libs ${dir}_libs");
2376     }
2378   check_user_variables 'LIBTOOLFLAGS';
2380   # Output the libtool compilation rules.
2381   $output_rules .= &file_contents ('libtool',
2382                                    new Automake::Location,
2383                                    LTRMS => join ("\n", @libtool_rms));
2386 # handle_programs ()
2387 # ------------------
2388 # Handle C programs.
2389 sub handle_programs
2391   my @proglist = &am_install_var ('progs', 'PROGRAMS',
2392                                   'bin', 'sbin', 'libexec', 'pkglib',
2393                                   'noinst', 'check');
2394   return if ! @proglist;
2396   my $seen_global_libobjs =
2397     var ('LDADD') && &handle_lib_objects ('', 'LDADD');
2399   foreach my $pair (@proglist)
2400     {
2401       my ($where, $one_file) = @$pair;
2403       my $seen_libobjs = 0;
2404       my $obj = get_object_extension '.$(OBJEXT)';
2406       # Strip any $(EXEEXT) suffix the user might have added, or this
2407       # will confuse &handle_source_transform and &check_canonical_spelling.
2408       # We'll add $(EXEEXT) back later anyway.
2409       $one_file =~ s/\$\(EXEEXT\)$//;
2411       $known_programs{$one_file} = $where;
2413       # Canonicalize names and check for misspellings.
2414       my $xname = &check_canonical_spelling ($one_file, '_LDADD', '_LDFLAGS',
2415                                              '_SOURCES', '_OBJECTS',
2416                                              '_DEPENDENCIES');
2418       $where->push_context ("while processing program `$one_file'");
2419       $where->set (INTERNAL->get);
2421       my $linker = &handle_source_transform ($xname, $one_file, $obj, $where,
2422                                              NONLIBTOOL => 1, LIBTOOL => 0);
2424       if (var ($xname . "_LDADD"))
2425         {
2426           $seen_libobjs = &handle_lib_objects ($xname, $xname . '_LDADD');
2427         }
2428       else
2429         {
2430           # User didn't define prog_LDADD override.  So do it.
2431           &define_variable ($xname . '_LDADD', '$(LDADD)', $where);
2433           # This does a bit too much work.  But we need it to
2434           # generate _DEPENDENCIES when appropriate.
2435           if (var ('LDADD'))
2436             {
2437               $seen_libobjs = &handle_lib_objects ($xname, 'LDADD');
2438             }
2439         }
2441       reject_var ($xname . '_LIBADD',
2442                   "use `${xname}_LDADD', not `${xname}_LIBADD'");
2444       set_seen ($xname . '_DEPENDENCIES');
2445       set_seen ($xname . '_LDFLAGS');
2447       # Determine program to use for link.
2448       my $xlink = &define_per_target_linker_variable ($linker, $xname);
2450       # If the resulting program lies into a subdirectory,
2451       # make sure this directory will exist.
2452       my $dirstamp = require_build_directory_maybe ($one_file);
2454       $output_rules .= &file_contents ('program',
2455                                        $where,
2456                                        PROGRAM  => $one_file,
2457                                        XPROGRAM => $xname,
2458                                        XLINK    => $xlink,
2459                                        DIRSTAMP => $dirstamp,
2460                                        EXEEXT   => '$(EXEEXT)');
2462       if ($seen_libobjs || $seen_global_libobjs)
2463         {
2464           if (var ($xname . '_LDADD'))
2465             {
2466               &check_libobjs_sources ($xname, $xname . '_LDADD');
2467             }
2468           elsif (var ('LDADD'))
2469             {
2470               &check_libobjs_sources ($xname, 'LDADD');
2471             }
2472         }
2473     }
2477 # handle_libraries ()
2478 # -------------------
2479 # Handle libraries.
2480 sub handle_libraries
2482   my @liblist = &am_install_var ('libs', 'LIBRARIES',
2483                                  'lib', 'pkglib', 'noinst', 'check');
2484   return if ! @liblist;
2486   my @prefix = am_primary_prefixes ('LIBRARIES', 0, 'lib', 'pkglib',
2487                                     'noinst', 'check');
2489   if (@prefix)
2490     {
2491       my $var = rvar ($prefix[0] . '_LIBRARIES');
2492       $var->requires_variables ('library used', 'RANLIB');
2493     }
2495   &define_variable ('AR', 'ar', INTERNAL);
2496   &define_variable ('ARFLAGS', 'cru', INTERNAL);
2498   foreach my $pair (@liblist)
2499     {
2500       my ($where, $onelib) = @$pair;
2502       my $seen_libobjs = 0;
2503       # Check that the library fits the standard naming convention.
2504       my $bn = basename ($onelib);
2505       if ($bn !~ /^lib.*\.a$/)
2506         {
2507           $bn =~ s/^(?:lib)?(.*?)(?:\.[^.]*)?$/lib$1.a/;
2508           my $suggestion = dirname ($onelib) . "/$bn";
2509           $suggestion =~ s|^\./||g;
2510           msg ('error-gnu/warn', $where,
2511                "`$onelib' is not a standard library name\n"
2512                . "did you mean `$suggestion'?")
2513         }
2515       $where->push_context ("while processing library `$onelib'");
2516       $where->set (INTERNAL->get);
2518       my $obj = get_object_extension '.$(OBJEXT)';
2520       # Canonicalize names and check for misspellings.
2521       my $xlib = &check_canonical_spelling ($onelib, '_LIBADD', '_SOURCES',
2522                                             '_OBJECTS', '_DEPENDENCIES',
2523                                             '_AR');
2525       if (! var ($xlib . '_AR'))
2526         {
2527           &define_variable ($xlib . '_AR', '$(AR) $(ARFLAGS)', $where);
2528         }
2530       # Generate support for conditional object inclusion in
2531       # libraries.
2532       if (var ($xlib . '_LIBADD'))
2533         {
2534           if (&handle_lib_objects ($xlib, $xlib . '_LIBADD'))
2535             {
2536               $seen_libobjs = 1;
2537             }
2538         }
2539       else
2540         {
2541           &define_variable ($xlib . "_LIBADD", '', $where);
2542         }
2544       reject_var ($xlib . '_LDADD',
2545                   "use `${xlib}_LIBADD', not `${xlib}_LDADD'");
2547       # Make sure we at look at this.
2548       set_seen ($xlib . '_DEPENDENCIES');
2550       &handle_source_transform ($xlib, $onelib, $obj, $where,
2551                                 NONLIBTOOL => 1, LIBTOOL => 0);
2553       # If the resulting library lies into a subdirectory,
2554       # make sure this directory will exist.
2555       my $dirstamp = require_build_directory_maybe ($onelib);
2557       $output_rules .= &file_contents ('library',
2558                                        $where,
2559                                        LIBRARY  => $onelib,
2560                                        XLIBRARY => $xlib,
2561                                        DIRSTAMP => $dirstamp);
2563       if ($seen_libobjs)
2564         {
2565           if (var ($xlib . '_LIBADD'))
2566             {
2567               &check_libobjs_sources ($xlib, $xlib . '_LIBADD');
2568             }
2569         }
2570     }
2574 # handle_ltlibraries ()
2575 # ---------------------
2576 # Handle shared libraries.
2577 sub handle_ltlibraries
2579   my @liblist = &am_install_var ('ltlib', 'LTLIBRARIES',
2580                                  'noinst', 'lib', 'pkglib', 'check');
2581   return if ! @liblist;
2583   my @prefix = am_primary_prefixes ('LTLIBRARIES', 0, 'lib', 'pkglib',
2584                                     'noinst', 'check');
2586   if (@prefix)
2587     {
2588       my $var = rvar ($prefix[0] . '_LTLIBRARIES');
2589       $var->requires_variables ('Libtool library used', 'LIBTOOL');
2590     }
2592   my %instdirs = ();
2593   my %instconds = ();
2594   my %liblocations = ();        # Location (in Makefile.am) of each library.
2596   foreach my $key (@prefix)
2597     {
2598       # Get the installation directory of each library.
2599       (my $dir = $key) =~ s/^nobase_//;
2600       my $var = rvar ($key . '_LTLIBRARIES');
2602       # We reject libraries which are installed in several places
2603       # in the same condition, because we can only specify one
2604       # `-rpath' option.
2605       $var->traverse_recursively
2606         (sub
2607          {
2608            my ($var, $val, $cond, $full_cond) = @_;
2609            my $hcond = $full_cond->human;
2610            my $where = $var->rdef ($cond)->location;
2611            # A library cannot be installed in different directory
2612            # in overlapping conditions.
2613            if (exists $instconds{$val})
2614              {
2615                my ($msg, $acond) =
2616                  $instconds{$val}->ambiguous_p ($val, $full_cond);
2618                if ($msg)
2619                  {
2620                    error ($where, $msg, partial => 1);
2622                    my $dirtxt = "installed in `$dir'";
2623                    $dirtxt = "built for `$dir'"
2624                      if $dir eq 'EXTRA' || $dir eq 'noinst' || $dir eq 'check';
2625                    my $dircond =
2626                      $full_cond->true ? "" : " in condition $hcond";
2628                    error ($where, "`$val' should be $dirtxt$dircond ...",
2629                           partial => 1);
2631                    my $hacond = $acond->human;
2632                    my $adir = $instdirs{$val}{$acond};
2633                    my $adirtxt = "installed in `$adir'";
2634                    $adirtxt = "built for `$adir'"
2635                      if ($adir eq 'EXTRA' || $adir eq 'noinst'
2636                          || $adir eq 'check');
2637                    my $adircond = $acond->true ? "" : " in condition $hacond";
2639                    my $onlyone = ($dir ne $adir) ?
2640                      ("\nLibtool libraries can be built for only one "
2641                       . "destination.") : "";
2643                    error ($liblocations{$val}{$acond},
2644                           "... and should also be $adirtxt$adircond.$onlyone");
2645                    return;
2646                  }
2647              }
2648            else
2649              {
2650                $instconds{$val} = new Automake::DisjConditions;
2651              }
2652            $instdirs{$val}{$full_cond} = $dir;
2653            $liblocations{$val}{$full_cond} = $where;
2654            $instconds{$val} = $instconds{$val}->merge ($full_cond);
2655          },
2656          sub
2657          {
2658            return ();
2659          },
2660          skip_ac_subst => 1);
2661     }
2663   foreach my $pair (@liblist)
2664     {
2665       my ($where, $onelib) = @$pair;
2667       my $seen_libobjs = 0;
2668       my $obj = get_object_extension '.lo';
2670       # Canonicalize names and check for misspellings.
2671       my $xlib = &check_canonical_spelling ($onelib, '_LIBADD', '_LDFLAGS',
2672                                             '_SOURCES', '_OBJECTS',
2673                                             '_DEPENDENCIES');
2675       # Check that the library fits the standard naming convention.
2676       my $libname_rx = '^lib.*\.la';
2677       my $ldvar = var ("${xlib}_LDFLAGS") || var ('AM_LDFLAGS');
2678       my $ldvar2 = var ('LDFLAGS');
2679       if (($ldvar && grep (/-module/, $ldvar->value_as_list_recursive))
2680           || ($ldvar2 && grep (/-module/, $ldvar2->value_as_list_recursive)))
2681         {
2682           # Relax name checking for libtool modules.
2683           $libname_rx = '\.la';
2684         }
2686       my $bn = basename ($onelib);
2687       if ($bn !~ /$libname_rx$/)
2688         {
2689           my $type = 'library';
2690           if ($libname_rx eq '\.la')
2691             {
2692               $bn =~ s/^(lib|)(.*?)(?:\.[^.]*)?$/$1$2.la/;
2693               $type = 'module';
2694             }
2695           else
2696             {
2697               $bn =~ s/^(?:lib)?(.*?)(?:\.[^.]*)?$/lib$1.la/;
2698             }
2699           my $suggestion = dirname ($onelib) . "/$bn";
2700           $suggestion =~ s|^\./||g;
2701           msg ('error-gnu/warn', $where,
2702                "`$onelib' is not a standard libtool $type name\n"
2703                . "did you mean `$suggestion'?")
2704         }
2706       $where->push_context ("while processing Libtool library `$onelib'");
2707       $where->set (INTERNAL->get);
2709       # Make sure we look at these.
2710       set_seen ($xlib . '_LDFLAGS');
2711       set_seen ($xlib . '_DEPENDENCIES');
2713       # Generate support for conditional object inclusion in
2714       # libraries.
2715       if (var ($xlib . '_LIBADD'))
2716         {
2717           if (&handle_lib_objects ($xlib, $xlib . '_LIBADD'))
2718             {
2719               $seen_libobjs = 1;
2720             }
2721         }
2722       else
2723         {
2724           &define_variable ($xlib . "_LIBADD", '', $where);
2725         }
2727       reject_var ("${xlib}_LDADD",
2728                   "use `${xlib}_LIBADD', not `${xlib}_LDADD'");
2731       my $linker = &handle_source_transform ($xlib, $onelib, $obj, $where,
2732                                              NONLIBTOOL => 0, LIBTOOL => 1);
2734       # Determine program to use for link.
2735       my $xlink = &define_per_target_linker_variable ($linker, $xlib);
2737       my $rpathvar = "am_${xlib}_rpath";
2738       my $rpath = "\$($rpathvar)";
2739       foreach my $rcond ($instconds{$onelib}->conds)
2740         {
2741           my $val;
2742           if ($instdirs{$onelib}{$rcond} eq 'EXTRA'
2743               || $instdirs{$onelib}{$rcond} eq 'noinst'
2744               || $instdirs{$onelib}{$rcond} eq 'check')
2745             {
2746               # It's an EXTRA_ library, so we can't specify -rpath,
2747               # because we don't know where the library will end up.
2748               # The user probably knows, but generally speaking automake
2749               # doesn't -- and in fact configure could decide
2750               # dynamically between two different locations.
2751               $val = '';
2752             }
2753           else
2754             {
2755               $val = ('-rpath $(' . $instdirs{$onelib}{$rcond} . 'dir)');
2756             }
2757           if ($rcond->true)
2758             {
2759               # If $rcond is true there is only one condition and
2760               # there is no point defining an helper variable.
2761               $rpath = $val;
2762             }
2763           else
2764             {
2765               define_pretty_variable ($rpathvar, $rcond, INTERNAL, $val);
2766             }
2767         }
2769       # If the resulting library lies into a subdirectory,
2770       # make sure this directory will exist.
2771       my $dirstamp = require_build_directory_maybe ($onelib);
2773       # Remember to cleanup .libs/ in this directory.
2774       my $dirname = dirname $onelib;
2775       $libtool_clean_directories{$dirname} = 1;
2777       $output_rules .= &file_contents ('ltlibrary',
2778                                        $where,
2779                                        LTLIBRARY  => $onelib,
2780                                        XLTLIBRARY => $xlib,
2781                                        RPATH      => $rpath,
2782                                        XLINK      => $xlink,
2783                                        DIRSTAMP   => $dirstamp);
2784       if ($seen_libobjs)
2785         {
2786           if (var ($xlib . '_LIBADD'))
2787             {
2788               &check_libobjs_sources ($xlib, $xlib . '_LIBADD');
2789             }
2790         }
2791     }
2794 # See if any _SOURCES variable were misspelled.
2795 sub check_typos ()
2797   # It is ok if the user sets this particular variable.
2798   set_seen 'AM_LDFLAGS';
2800   foreach my $primary ('SOURCES', 'LIBADD', 'LDADD', 'LDFLAGS', 'DEPENDENCIES')
2801     {
2802       foreach my $var (variables $primary)
2803         {
2804           my $varname = $var->name;
2805           # A configure variable is always legitimate.
2806           next if exists $configure_vars{$varname};
2808           for my $cond ($var->conditions->conds)
2809             {
2810               $varname =~ /^(?:nobase_)?(?:dist_|nodist_)?(.*)_[[:alnum:]]+$/;
2811               msg_var ('syntax', $var, "variable `$varname' is defined but no"
2812                        . " program or\nlibrary has `$1' as canonic name"
2813                        . " (possible typo)")
2814                 unless $var->rdef ($cond)->seen;
2815             }
2816         }
2817     }
2821 # Handle scripts.
2822 sub handle_scripts
2824     # NOTE we no longer automatically clean SCRIPTS, because it is
2825     # useful to sometimes distribute scripts verbatim.  This happens
2826     # e.g. in Automake itself.
2827     &am_install_var ('-candist', 'scripts', 'SCRIPTS',
2828                      'bin', 'sbin', 'libexec', 'pkgdata',
2829                      'noinst', 'check');
2835 ## ------------------------ ##
2836 ## Handling Texinfo files.  ##
2837 ## ------------------------ ##
2839 # ($OUTFILE, $VFILE, @CLEAN_FILES)
2840 # &scan_texinfo_file ($FILENAME)
2841 # ------------------------------
2842 # $OUTFILE     - name of the info file produced by $FILENAME.
2843 # $VFILE       - name of the version.texi file used (undef if none).
2844 # @CLEAN_FILES - list of byproducts (indexes etc.)
2845 sub scan_texinfo_file ($)
2847   my ($filename) = @_;
2849   # Some of the following extensions are always created, no matter
2850   # whether indexes are used or not.  Other (like cps, fns, ... pgs)
2851   # are only created when they are used.  We used to scan $FILENAME
2852   # for their use, but that is not enough: they could be used in
2853   # included files.  We can't scan included files because we don't
2854   # know the include path.  Therefore we always erase these files, no
2855   # matter whether they are used or not.
2856   #
2857   # (tmp is only created if an @macro is used and a certain e-TeX
2858   # feature is not available.)
2859   my %clean_suffixes =
2860     map { $_ => 1 } (qw(aux log toc tmp
2861                         cp cps
2862                         fn fns
2863                         ky kys
2864                         vr vrs
2865                         tp tps
2866                         pg pgs)); # grep 'new.*index' texinfo.tex
2868   my $texi = new Automake::XFile "< $filename";
2869   verb "reading $filename";
2871   my ($outfile, $vfile);
2872   while ($_ = $texi->getline)
2873     {
2874       if (/^\@setfilename +(\S+)/)
2875         {
2876           # Honor only the first @setfilename.  (It's possible to have
2877           # more occurrences later if the manual shows examples of how
2878           # to use @setfilename...)
2879           next if $outfile;
2881           $outfile = $1;
2882           if ($outfile =~ /\.(.+)$/ && $1 ne 'info')
2883             {
2884               error ("$filename:$.",
2885                      "output `$outfile' has unrecognized extension");
2886               return;
2887             }
2888         }
2889       # A "version.texi" file is actually any file whose name matches
2890       # "vers*.texi".
2891       elsif (/^\@include\s+(vers[^.]*\.texi)\s*$/)
2892         {
2893           $vfile = $1;
2894         }
2896       # Try to find new or unused indexes.
2898       # Creating a new category of index.
2899       elsif (/^\@def(code)?index (\w+)/)
2900         {
2901           $clean_suffixes{$2} = 1;
2902           $clean_suffixes{"$2s"} = 1;
2903         }
2905       # Merging an index into an another.
2906       elsif (/^\@syn(code)?index (\w+) (\w+)/)
2907         {
2908           delete $clean_suffixes{"$2s"};
2909           $clean_suffixes{"$3s"} = 1;
2910         }
2912     }
2914   if (! $outfile)
2915     {
2916       err_am "`$filename' missing \@setfilename";
2917       return;
2918     }
2920   my $infobase = basename ($filename);
2921   $infobase =~ s/\.te?xi(nfo)?$//;
2922   return ($outfile, $vfile,
2923           map { "$infobase.$_" } (sort keys %clean_suffixes));
2927 # ($DIRSTAMP, @CLEAN_FILES)
2928 # output_texinfo_build_rules ($SOURCE, $DEST, $INSRC, @DEPENDENCIES)
2929 # ------------------------------------------------------------------
2930 # SOURCE - the source Texinfo file
2931 # DEST - the destination Info file
2932 # INSRC - wether DEST should be built in the source tree
2933 # DEPENDENCIES - known dependencies
2934 sub output_texinfo_build_rules ($$$@)
2936   my ($source, $dest, $insrc, @deps) = @_;
2938   # Split `a.texi' into `a' and `.texi'.
2939   my ($spfx, $ssfx) = ($source =~ /^(.*?)(\.[^.]*)?$/);
2940   my ($dpfx, $dsfx) = ($dest =~ /^(.*?)(\.[^.]*)?$/);
2942   $ssfx ||= "";
2943   $dsfx ||= "";
2945   # We can output two kinds of rules: the "generic" rules use Make
2946   # suffix rules and are appropriate when $source and $dest do not lie
2947   # in a sub-directory; the "specific" rules are needed in the other
2948   # case.
2949   #
2950   # The former are output only once (this is not really apparent here,
2951   # but just remember that some logic deeper in Automake will not
2952   # output the same rule twice); while the later need to be output for
2953   # each Texinfo source.
2954   my $generic;
2955   my $makeinfoflags;
2956   my $sdir = dirname $source;
2957   if ($sdir eq '.' && dirname ($dest) eq '.')
2958     {
2959       $generic = 1;
2960       $makeinfoflags = '-I $(srcdir)';
2961     }
2962   else
2963     {
2964       $generic = 0;
2965       $makeinfoflags = "-I $sdir -I \$(srcdir)/$sdir";
2966     }
2968   # A directory can contain two kinds of info files: some built in the
2969   # source tree, and some built in the build tree.  The rules are
2970   # different in each case.  However we cannot output two different
2971   # set of generic rules.  Because in-source builds are more usual, we
2972   # use generic rules in this case and fall back to "specific" rules
2973   # for build-dir builds.  (It should not be a problem to invert this
2974   # if needed.)
2975   $generic = 0 unless $insrc;
2977   # We cannot use a suffix rule to build info files with an empty
2978   # extension.  Otherwise we would output a single suffix inference
2979   # rule, with separate dependencies, as in
2980   #
2981   #    .texi:
2982   #             $(MAKEINFO) ...
2983   #    foo.info: foo.texi
2984   #
2985   # which confuse Solaris make.  (See the Autoconf manual for
2986   # details.)  Therefore we use a specific rule in this case.  This
2987   # applies to info files only (dvi and pdf files always have an
2988   # extension).
2989   my $generic_info = ($generic && $dsfx) ? 1 : 0;
2991   # If the resulting file lie into a subdirectory,
2992   # make sure this directory will exist.
2993   my $dirstamp = require_build_directory_maybe ($dest);
2995   my $dipfx = ($insrc ? '$(srcdir)/' : '') . $dpfx;
2997   $output_rules .= file_contents ('texibuild',
2998                                   new Automake::Location,
2999                                   DEPS             => "@deps",
3000                                   DEST_PREFIX      => $dpfx,
3001                                   DEST_INFO_PREFIX => $dipfx,
3002                                   DEST_SUFFIX      => $dsfx,
3003                                   DIRSTAMP         => $dirstamp,
3004                                   GENERIC          => $generic,
3005                                   GENERIC_INFO     => $generic_info,
3006                                   INSRC            => $insrc,
3007                                   MAKEINFOFLAGS    => $makeinfoflags,
3008                                   SOURCE           => ($generic
3009                                                        ? '$<' : $source),
3010                                   SOURCE_INFO      => ($generic_info
3011                                                        ? '$<' : $source),
3012                                   SOURCE_REAL      => $source,
3013                                   SOURCE_SUFFIX    => $ssfx,
3014                                   );
3015   return ($dirstamp, "$dpfx.dvi", "$dpfx.pdf", "$dpfx.ps", "$dpfx.html");
3019 # $TEXICLEANS
3020 # handle_texinfo_helper ($info_texinfos)
3021 # --------------------------------------
3022 # Handle all Texinfo source; helper for handle_texinfo.
3023 sub handle_texinfo_helper ($)
3025   my ($info_texinfos) = @_;
3026   my (@infobase, @info_deps_list, @texi_deps);
3027   my %versions;
3028   my $done = 0;
3029   my @texi_cleans;
3031   # Build a regex matching user-cleaned files.
3032   my $d = var 'DISTCLEANFILES';
3033   my $c = var 'CLEANFILES';
3034   my @f = ();
3035   push @f, $d->value_as_list_recursive (inner_expand => 1) if $d;
3036   push @f, $c->value_as_list_recursive (inner_expand => 1) if $c;
3037   @f = map { s|[^A-Za-z_0-9*\[\]\-]|\\$&|g; s|\*|[^/]*|g; $_; } @f;
3038   my $user_cleaned_files = '^(?:' . join ('|', @f) . ')$';
3040   foreach my $texi
3041       ($info_texinfos->value_as_list_recursive (inner_expand => 1))
3042     {
3043       my $infobase = $texi;
3044       $infobase =~ s/\.(txi|texinfo|texi)$//;
3046       if ($infobase eq $texi)
3047         {
3048           # FIXME: report line number.
3049           err_am "texinfo file `$texi' has unrecognized extension";
3050           next;
3051         }
3053       push @infobase, $infobase;
3055       # If 'version.texi' is referenced by input file, then include
3056       # automatic versioning capability.
3057       my ($out_file, $vtexi, @clean_files) =
3058         scan_texinfo_file ("$relative_dir/$texi")
3059         or next;
3060       push (@texi_cleans, @clean_files);
3062       # If the Texinfo source is in a subdirectory, create the
3063       # resulting info in this subdirectory.  If it is in the current
3064       # directory, try hard to not prefix "./" because it breaks the
3065       # generic rules.
3066       my $outdir = dirname ($texi) . '/';
3067       $outdir = "" if $outdir eq './';
3068       $out_file =  $outdir . $out_file;
3070       # Until Automake 1.6.3, .info files were built in the
3071       # source tree.  This was an obstacle to the support of
3072       # non-distributed .info files, and non-distributed .texi
3073       # files.
3074       #
3075       # * Non-distributed .texi files is important in some packages
3076       #   where .texi files are built at make time, probably using
3077       #   other binaries built in the package itself, maybe using
3078       #   tools or information found on the build host.  Because
3079       #   these files are not distributed they are always rebuilt
3080       #   at make time; they should therefore not lie in the source
3081       #   directory.  One plan was to support this using
3082       #   nodist_info_TEXINFOS or something similar.  (Doing this
3083       #   requires some sanity checks.  For instance Automake should
3084       #   not allow:
3085       #      dist_info_TEXINFO = foo.texi
3086       #      nodist_foo_TEXINFO = included.texi
3087       #   because a distributed file should never depend on a
3088       #   non-distributed file.)
3089       #
3090       # * If .texi files are not distributed, then .info files should
3091       #   not be distributed either.  There are also cases where one
3092       #   want to distribute .texi files, but do not want to
3093       #   distribute the .info files.  For instance the Texinfo package
3094       #   distributes the tool used to build these files; it would
3095       #   be a waste of space to distribute them.  It's not clear
3096       #   which syntax we should use to indicate that .info files should
3097       #   not be distributed.  Akim Demaille suggested that eventually
3098       #   we switch to a new syntax:
3099       #   |  Maybe we should take some inspiration from what's already
3100       #   |  done in the rest of Automake.  Maybe there is too much
3101       #   |  syntactic sugar here, and you want
3102       #   |     nodist_INFO = bar.info
3103       #   |     dist_bar_info_SOURCES = bar.texi
3104       #   |     bar_texi_DEPENDENCIES = foo.texi
3105       #   |  with a bit of magic to have bar.info represent the whole
3106       #   |  bar*info set.  That's a lot more verbose that the current
3107       #   |  situation, but it is # not new, hence the user has less
3108       #   |  to learn.
3109       #   |
3110       #   |  But there is still too much room for meaningless specs:
3111       #   |     nodist_INFO = bar.info
3112       #   |     dist_bar_info_SOURCES = bar.texi
3113       #   |     dist_PS = bar.ps something-written-by-hand.ps
3114       #   |     nodist_bar_ps_SOURCES = bar.texi
3115       #   |     bar_texi_DEPENDENCIES = foo.texi
3116       #   |  here bar.texi is dist_ in line 2, and nodist_ in 4.
3117       #
3118       # Back to the point, it should be clear that in order to support
3119       # non-distributed .info files, we need to build them in the
3120       # build tree, not in the source tree (non-distributed .texi
3121       # files are less of a problem, because we do not output build
3122       # rules for them).  In Automake 1.7 .info build rules have been
3123       # largely cleaned up so that .info files get always build in the
3124       # build tree, even when distributed.  The idea was that
3125       #   (1) if during a VPATH build the .info file was found to be
3126       #       absent or out-of-date (in the source tree or in the
3127       #       build tree), Make would rebuild it in the build tree.
3128       #       If an up-to-date source-tree of the .info file existed,
3129       #       make would not rebuild it in the build tree.
3130       #   (2) having two copies of .info files, one in the source tree
3131       #       and one (newer) in the build tree is not a problem
3132       #       because `make dist' always pick files in the build tree
3133       #       first.
3134       # However it turned out the be a bad idea for several reasons:
3135       #   * Tru64, OpenBSD, and FreeBSD (not NetBSD) Make do not behave
3136       #     like GNU Make on point (1) above.  These implementations
3137       #     of Make would always rebuild .info files in the build
3138       #     tree, even if such files were up to date in the source
3139       #     tree.  Consequently, it was impossible to perform a VPATH
3140       #     build of a package containing Texinfo files using these
3141       #     Make implementations.
3142       #     (Refer to the Autoconf Manual, section "Limitation of
3143       #     Make", paragraph "VPATH", item "target lookup", for
3144       #     an account of the differences between these
3145       #     implementations.)
3146       #   * The GNU Coding Standards require these files to be built
3147       #     in the source-tree (when they are distributed, that is).
3148       #   * Keeping a fresher copy of distributed files in the
3149       #     build tree can be annoying during development because
3150       #     - if the files is kept under CVS, you really want it
3151       #       to be updated in the source tree
3152       #     - it is confusing that `make distclean' does not erase
3153       #       all files in the build tree.
3154       #
3155       # Consequently, starting with Automake 1.8, .info files are
3156       # built in the source tree again.  Because we still plan to
3157       # support non-distributed .info files at some point, we
3158       # have a single variable ($INSRC) that controls whether
3159       # the current .info file must be built in the source tree
3160       # or in the build tree.  Actually this variable is switched
3161       # off for .info files that appear to be cleaned; this is
3162       # for backward compatibility with package such as Texinfo,
3163       # which do things like
3164       #   info_TEXINFOS = texinfo.txi info-stnd.texi info.texi
3165       #   DISTCLEANFILES = texinfo texinfo-* info*.info*
3166       #   # Do not create info files for distribution.
3167       #   dist-info:
3168       # in order not to distribute .info files.
3169       my $insrc = ($out_file =~ $user_cleaned_files) ? 0 : 1;
3171       my $soutdir = '$(srcdir)/' . $outdir;
3172       $outdir = $soutdir if $insrc;
3174       # If user specified file_TEXINFOS, then use that as explicit
3175       # dependency list.
3176       @texi_deps = ();
3177       push (@texi_deps, "$soutdir$vtexi") if $vtexi;
3179       my $canonical = canonicalize ($infobase);
3180       if (var ($canonical . "_TEXINFOS"))
3181         {
3182           push (@texi_deps, '$(' . $canonical . '_TEXINFOS)');
3183           push_dist_common ('$(' . $canonical . '_TEXINFOS)');
3184         }
3186       my ($dirstamp, @cfiles) =
3187         output_texinfo_build_rules ($texi, $out_file, $insrc, @texi_deps);
3188       push (@texi_cleans, @cfiles);
3190       push (@info_deps_list, $out_file);
3192       # If a vers*.texi file is needed, emit the rule.
3193       if ($vtexi)
3194         {
3195           err_am ("`$vtexi', included in `$texi', "
3196                   . "also included in `$versions{$vtexi}'")
3197             if defined $versions{$vtexi};
3198           $versions{$vtexi} = $texi;
3200           # We number the stamp-vti files.  This is doable since the
3201           # actual names don't matter much.  We only number starting
3202           # with the second one, so that the common case looks nice.
3203           my $vti = ($done ? $done : 'vti');
3204           ++$done;
3206           # This is ugly, but it is our historical practice.
3207           if ($config_aux_dir_set_in_configure_ac)
3208             {
3209               require_conf_file_with_macro (TRUE, 'info_TEXINFOS', FOREIGN,
3210                                             'mdate-sh');
3211             }
3212           else
3213             {
3214               require_file_with_macro (TRUE, 'info_TEXINFOS',
3215                                        FOREIGN, 'mdate-sh');
3216             }
3218           my $conf_dir;
3219           if ($config_aux_dir_set_in_configure_ac)
3220             {
3221               $conf_dir = "$am_config_aux_dir/";
3222             }
3223           else
3224             {
3225               $conf_dir = '$(srcdir)/';
3226             }
3227           $output_rules .= file_contents ('texi-vers',
3228                                           new Automake::Location,
3229                                           TEXI     => $texi,
3230                                           VTI      => $vti,
3231                                           STAMPVTI => "${soutdir}stamp-$vti",
3232                                           VTEXI    => "$soutdir$vtexi",
3233                                           MDDIR    => $conf_dir,
3234                                           DIRSTAMP => $dirstamp);
3235         }
3236     }
3238   # Handle location of texinfo.tex.
3239   my $need_texi_file = 0;
3240   my $texinfodir;
3241   if (var ('TEXINFO_TEX'))
3242     {
3243       # The user defined TEXINFO_TEX so assume he knows what he is
3244       # doing.
3245       $texinfodir = ('$(srcdir)/'
3246                      . dirname (variable_value ('TEXINFO_TEX')));
3247     }
3248   elsif (option 'cygnus')
3249     {
3250       $texinfodir = '$(top_srcdir)/../texinfo';
3251       define_variable ('TEXINFO_TEX', "$texinfodir/texinfo.tex", INTERNAL);
3252     }
3253   elsif ($config_aux_dir_set_in_configure_ac)
3254     {
3255       $texinfodir = $am_config_aux_dir;
3256       define_variable ('TEXINFO_TEX', "$texinfodir/texinfo.tex", INTERNAL);
3257       $need_texi_file = 2; # so that we require_conf_file later
3258     }
3259   else
3260     {
3261       $texinfodir = '$(srcdir)';
3262       $need_texi_file = 1;
3263     }
3264   define_variable ('am__TEXINFO_TEX_DIR', $texinfodir, INTERNAL);
3266   push (@dist_targets, 'dist-info');
3268   if (! option 'no-installinfo')
3269     {
3270       # Make sure documentation is made and installed first.  Use
3271       # $(INFO_DEPS), not 'info', because otherwise recursive makes
3272       # get run twice during "make all".
3273       unshift (@all, '$(INFO_DEPS)');
3274     }
3276   define_files_variable ("DVIS", @infobase, 'dvi', INTERNAL);
3277   define_files_variable ("PDFS", @infobase, 'pdf', INTERNAL);
3278   define_files_variable ("PSS", @infobase, 'ps', INTERNAL);
3279   define_files_variable ("HTMLS", @infobase, 'html', INTERNAL);
3281   # This next isn't strictly needed now -- the places that look here
3282   # could easily be changed to look in info_TEXINFOS.  But this is
3283   # probably better, in case noinst_TEXINFOS is ever supported.
3284   define_variable ("TEXINFOS", variable_value ('info_TEXINFOS'), INTERNAL);
3286   # Do some error checking.  Note that this file is not required
3287   # when in Cygnus mode; instead we defined TEXINFO_TEX explicitly
3288   # up above.
3289   if ($need_texi_file && ! option 'no-texinfo.tex')
3290     {
3291       if ($need_texi_file > 1)
3292         {
3293           require_conf_file_with_macro (TRUE, 'info_TEXINFOS', FOREIGN,
3294                                         'texinfo.tex');
3295         }
3296       else
3297         {
3298           require_file_with_macro (TRUE, 'info_TEXINFOS', FOREIGN,
3299                                    'texinfo.tex');
3300         }
3301     }
3303   return makefile_wrap ("", "\t  ", @texi_cleans);
3307 # handle_texinfo ()
3308 # -----------------
3309 # Handle all Texinfo source.
3310 sub handle_texinfo ()
3312   reject_var 'TEXINFOS', "`TEXINFOS' is an anachronism; use `info_TEXINFOS'";
3313   # FIXME: I think this is an obsolete future feature name.
3314   reject_var 'html_TEXINFOS', "HTML generation not yet supported";
3316   my $info_texinfos = var ('info_TEXINFOS');
3317   my $texiclean = "";
3318   if ($info_texinfos)
3319     {
3320       $texiclean = handle_texinfo_helper ($info_texinfos);
3321     }
3322   $output_rules .=  file_contents ('texinfos',
3323                                    new Automake::Location,
3324                                    TEXICLEAN     => $texiclean,
3325                                    'LOCAL-TEXIS' => !!$info_texinfos);
3329 # Handle any man pages.
3330 sub handle_man_pages
3332   reject_var 'MANS', "`MANS' is an anachronism; use `man_MANS'";
3334   # Find all the sections in use.  We do this by first looking for
3335   # "standard" sections, and then looking for any additional
3336   # sections used in man_MANS.
3337   my (%sections, %vlist);
3338   # We handle nodist_ for uniformity.  man pages aren't distributed
3339   # by default so it isn't actually very important.
3340   foreach my $pfx ('', 'dist_', 'nodist_')
3341     {
3342       # Add more sections as needed.
3343       foreach my $section ('0'..'9', 'n', 'l')
3344         {
3345           my $varname = $pfx . 'man' . $section . '_MANS';
3346           if (var ($varname))
3347             {
3348               $sections{$section} = 1;
3349               $varname = '$(' . $varname . ')';
3350               $vlist{$varname} = 1;
3352               &push_dist_common ($varname)
3353                 if $pfx eq 'dist_';
3354             }
3355         }
3357       my $varname = $pfx . 'man_MANS';
3358       my $var = var ($varname);
3359       if ($var)
3360         {
3361           foreach ($var->value_as_list_recursive)
3362             {
3363               # A page like `foo.1c' goes into man1dir.
3364               if (/\.([0-9a-z])([a-z]*)$/)
3365                 {
3366                   $sections{$1} = 1;
3367                 }
3368             }
3370           $varname = '$(' . $varname . ')';
3371           $vlist{$varname} = 1;
3372           &push_dist_common ($varname)
3373             if $pfx eq 'dist_';
3374         }
3375     }
3377   return unless %sections;
3379   # Now for each section, generate an install and uninstall rule.
3380   # Sort sections so output is deterministic.
3381   foreach my $section (sort keys %sections)
3382     {
3383       $output_rules .= &file_contents ('mans',
3384                                        new Automake::Location,
3385                                        SECTION => $section);
3386     }
3388   my @mans = sort keys %vlist;
3389   $output_vars .= file_contents ('mans-vars',
3390                                  new Automake::Location,
3391                                  MANS => "@mans");
3393   push (@all, '$(MANS)')
3394     unless option 'no-installman';
3397 # Handle DATA variables.
3398 sub handle_data
3400     &am_install_var ('-noextra', '-candist', 'data', 'DATA',
3401                      'data', 'dataroot', 'dvi', 'html', 'pdf', 'ps',
3402                      'sysconf', 'sharedstate', 'localstate',
3403                      'pkgdata', 'lisp', 'noinst', 'check');
3406 # Handle TAGS.
3407 sub handle_tags
3409     my @tag_deps = ();
3410     my @ctag_deps = ();
3411     if (var ('SUBDIRS'))
3412     {
3413         $output_rules .= ("tags-recursive:\n"
3414                           . "\tlist=\'\$(SUBDIRS)\'; for subdir in \$\$list; do \\\n"
3415                           # Never fail here if a subdir fails; it
3416                           # isn't important.
3417                           . "\t  test \"\$\$subdir\" = . || (cd \$\$subdir"
3418                           . " && \$(MAKE) \$(AM_MAKEFLAGS) tags); \\\n"
3419                           . "\tdone\n");
3420         push (@tag_deps, 'tags-recursive');
3421         &depend ('.PHONY', 'tags-recursive');
3423         $output_rules .= ("ctags-recursive:\n"
3424                           . "\tlist=\'\$(SUBDIRS)\'; for subdir in \$\$list; do \\\n"
3425                           # Never fail here if a subdir fails; it
3426                           # isn't important.
3427                           . "\t  test \"\$\$subdir\" = . || (cd \$\$subdir"
3428                           . " && \$(MAKE) \$(AM_MAKEFLAGS) ctags); \\\n"
3429                           . "\tdone\n");
3430         push (@ctag_deps, 'ctags-recursive');
3431         &depend ('.PHONY', 'ctags-recursive');
3432     }
3434     if (&saw_sources_p (1)
3435         || var ('ETAGS_ARGS')
3436         || @tag_deps)
3437     {
3438         my @config;
3439         foreach my $spec (@config_headers)
3440         {
3441             my ($out, @ins) = split_config_file_spec ($spec);
3442             foreach my $in (@ins)
3443               {
3444                 # If the config header source is in this directory,
3445                 # require it.
3446                 push @config, basename ($in)
3447                   if $relative_dir eq dirname ($in);
3448               }
3449         }
3450         $output_rules .= &file_contents ('tags',
3451                                          new Automake::Location,
3452                                          CONFIG    => "@config",
3453                                          TAGSDIRS  => "@tag_deps",
3454                                          CTAGSDIRS => "@ctag_deps");
3456         set_seen 'TAGS_DEPENDENCIES';
3457     }
3458     elsif (reject_var ('TAGS_DEPENDENCIES',
3459                        "doesn't make sense to define `TAGS_DEPENDENCIES'"
3460                        . "without\nsources or `ETAGS_ARGS'"))
3461     {
3462     }
3463     else
3464     {
3465         # Every Makefile must define some sort of TAGS rule.
3466         # Otherwise, it would be possible for a top-level "make TAGS"
3467         # to fail because some subdirectory failed.
3468         $output_rules .= "tags: TAGS\nTAGS:\n\n";
3469         # Ditto ctags.
3470         $output_rules .= "ctags: CTAGS\nCTAGS:\n\n";
3471     }
3474 # Handle multilib support.
3475 sub handle_multilib
3477   if ($seen_multilib && $relative_dir eq '.')
3478     {
3479       $output_rules .= &file_contents ('multilib', new Automake::Location);
3480       push (@all, 'all-multi');
3481     }
3485 # user_phony_rule ($NAME)
3486 # -----------------------
3487 # Return false if rule $NAME does not exist.  Otherwise,
3488 # declare it as phony, complete its definition (in case it is
3489 # conditional), and return its Automake::Rule instance.
3490 sub user_phony_rule ($)
3492   my ($name) = @_;
3493   my $rule = rule $name;
3494   if ($rule)
3495     {
3496       depend ('.PHONY', $name);
3497       # Define $NAME in all condition where it is not already defined,
3498       # so that it is always OK to depend on $NAME.
3499       for my $c ($rule->not_always_defined_in_cond (TRUE)->conds)
3500         {
3501           Automake::Rule::define ($name, 'internal', RULE_AUTOMAKE,
3502                                   $c, INTERNAL);
3503           $output_rules .= $c->subst_string . "$name:\n";
3504         }
3505     }
3506   return $rule;
3510 # $BOOLEAN
3511 # &for_dist_common ($A, $B)
3512 # -------------------------
3513 # Subroutine for &handle_dist: sort files to dist.
3515 # We put README first because it then becomes easier to make a
3516 # Usenet-compliant shar file (in these, README must be first).
3518 # FIXME: do more ordering of files here.
3519 sub for_dist_common
3521     return 0
3522         if $a eq $b;
3523     return -1
3524         if $a eq 'README';
3525     return 1
3526         if $b eq 'README';
3527     return $a cmp $b;
3530 # fill_dist_dirs(@FILES)
3531 # ----------------------
3532 # Record in %dist_dirs the directory part of any file passed.
3533 sub fill_dist_dirs (@)
3535   my @copy = @_;
3536   foreach (@copy)
3537     {
3538       s/\$\(top_srcdir\)/$topsrcdir/;
3539       s/\$\(srcdir\)/./;
3540       # Strip any leading `./'.
3541       s,^(:?\./+)*,,;
3542       next unless s,/+[^/]+$,,;
3543       $dist_dirs{$_} = 1
3544         unless $_ eq '.';
3545     }
3548 # handle_dist
3549 # -----------
3550 # Handle 'dist' target.
3551 sub handle_dist ()
3553   # Substutions for distdit.am
3554   my %transform;
3556   # Define DIST_SUBDIRS.  This must always be done, regardless of the
3557   # no-dist setting: target like `distclean' or `maintainer-clean' use it.
3558   my $subdirs = var ('SUBDIRS');
3559   if ($subdirs)
3560     {
3561       # If SUBDIRS is conditionally defined, then set DIST_SUBDIRS
3562       # to all possible directories, and use it.  If DIST_SUBDIRS is
3563       # defined, just use it.
3565       # Note that we check DIST_SUBDIRS first on purpose, so that
3566       # we don't call has_conditional_contents for now reason.
3567       # (In the past one project used so many conditional subdirectories
3568       # that calling has_conditional_contents on SUBDIRS caused
3569       # automake to grow to 150Mb -- this should not happen with
3570       # the current implementation of has_conditional_contents,
3571       # but it's more efficient to avoid the call anyway.)
3572       if (var ('DIST_SUBDIRS'))
3573         {
3574         }
3575       elsif ($subdirs->has_conditional_contents)
3576         {
3577           define_pretty_variable
3578             ('DIST_SUBDIRS', TRUE, INTERNAL,
3579              uniq ($subdirs->value_as_list_recursive));
3580         }
3581       else
3582         {
3583           # We always define this because that is what `distclean'
3584           # wants.
3585           define_pretty_variable ('DIST_SUBDIRS', TRUE, INTERNAL,
3586                                   '$(SUBDIRS)');
3587         }
3588     }
3590   # The remaining definitions are only required when a dist target is used.
3591   return if option 'no-dist';
3593   # At least one of the archive formats must be enabled.
3594   if ($relative_dir eq '.')
3595     {
3596       my $archive_defined = option 'no-dist-gzip' ? 0 : 1;
3597       $archive_defined ||=
3598         grep { option "dist-$_" } ('shar', 'zip', 'tarZ', 'bzip2');
3599       error (option 'no-dist-gzip',
3600              "no-dist-gzip specified but no dist-* specified, "
3601              . "at least one archive format must be enabled")
3602         unless $archive_defined;
3603     }
3605   # Look for common files that should be included in distribution.
3606   # If the aux dir is set, and it does not have a Makefile.am, then
3607   # we check for these files there as well.
3608   my $check_aux = 0;
3609   if ($relative_dir eq '.'
3610       && $config_aux_dir_set_in_configure_ac)
3611     {
3612       if (! &is_make_dir ($config_aux_dir))
3613         {
3614           $check_aux = 1;
3615         }
3616     }
3617   foreach my $cfile (@common_files)
3618     {
3619       if (dir_has_case_matching_file ($relative_dir, $cfile)
3620           # The file might be absent, but if it can be built it's ok.
3621           || rule $cfile)
3622         {
3623           &push_dist_common ($cfile);
3624         }
3626       # Don't use `elsif' here because a file might meaningfully
3627       # appear in both directories.
3628       if ($check_aux && dir_has_case_matching_file ($config_aux_dir, $cfile))
3629         {
3630           &push_dist_common ("$config_aux_dir/$cfile")
3631         }
3632     }
3634   # We might copy elements from $configure_dist_common to
3635   # %dist_common if we think we need to.  If the file appears in our
3636   # directory, we would have discovered it already, so we don't
3637   # check that.  But if the file is in a subdir without a Makefile,
3638   # we want to distribute it here if we are doing `.'.  Ugly!
3639   if ($relative_dir eq '.')
3640     {
3641       foreach my $file (split (' ' , $configure_dist_common))
3642         {
3643           push_dist_common ($file)
3644             unless is_make_dir (dirname ($file));
3645         }
3646     }
3648   # Files to distributed.  Don't use ->value_as_list_recursive
3649   # as it recursively expands `$(dist_pkgdata_DATA)' etc.
3650   my @dist_common = split (' ', rvar ('DIST_COMMON')->variable_value);
3651   @dist_common = uniq (sort for_dist_common (@dist_common));
3652   variable_delete 'DIST_COMMON';
3653   define_pretty_variable ('DIST_COMMON', TRUE, INTERNAL, @dist_common);
3655   # Now that we've processed DIST_COMMON, disallow further attempts
3656   # to set it.
3657   $handle_dist_run = 1;
3659   # Scan EXTRA_DIST to see if we need to distribute anything from a
3660   # subdir.  If so, add it to the list.  I didn't want to do this
3661   # originally, but there were so many requests that I finally
3662   # relented.
3663   my $extra_dist = var ('EXTRA_DIST');
3664   # FIXME: This should be fixed to work with conditions.  That
3665   # will require only making the entries in %dist_dirs under the
3666   # appropriate condition.  This is meaningful if the nature of
3667   # the distribution should depend upon the configure options
3668   # used.
3669   fill_dist_dirs ($extra_dist->value_as_list_recursive (skip_ac_subst => 1))
3670     if $extra_dist;
3672   # We have to check DIST_COMMON for extra directories in case the
3673   # user put a source used in AC_OUTPUT into a subdir.
3674   fill_dist_dirs (rvar ('DIST_COMMON')
3675                   ->value_as_list_recursive (skip_ac_subst => 1));
3677   $transform{'DISTCHECK-HOOK'} = !! rule 'distcheck-hook';
3678   $transform{'GETTEXT'} = $seen_gettext && !$seen_gettext_external;
3680   # Prepend $(distdir) to each directory given.
3681   my %rewritten = map { '$(distdir)/' . "$_" => 1 } keys %dist_dirs;
3682   $transform{'DISTDIRS'} = join (' ', sort keys %rewritten);
3684   # If the target `dist-hook' exists, make sure it is run.  This
3685   # allows users to do random weird things to the distribution
3686   # before it is packaged up.
3687   push (@dist_targets, 'dist-hook')
3688     if user_phony_rule 'dist-hook';
3689   $transform{'DIST-TARGETS'} = join (' ', @dist_targets);
3691   my $flm = option ('filename-length-max');
3692   my $filename_filter = $flm ? '.' x $flm->[1] : '';
3694   $output_rules .= &file_contents ('distdir',
3695                                    new Automake::Location,
3696                                    %transform,
3697                                    FILENAME_FILTER => $filename_filter);
3701 # check_directory ($NAME, $WHERE)
3702 # -------------------------------
3703 # Ensure $NAME is a directory, and that it uses sane name.
3704 # Use $WHERE as a location in the diagnostic, if any.
3705 sub check_directory ($$)
3707   my ($dir, $where) = @_;
3709   error $where, "required directory $relative_dir/$dir does not exist"
3710     unless -d "$relative_dir/$dir";
3712   # If an `obj/' directory exists, BSD make will enter it before
3713   # reading `Makefile'.  Hence the `Makefile' in the current directory
3714   # will not be read.
3715   #
3716   #  % cat Makefile
3717   #  all:
3718   #          echo Hello
3719   #  % cat obj/Makefile
3720   #  all:
3721   #          echo World
3722   #  % make      # GNU make
3723   #  echo Hello
3724   #  Hello
3725   #  % pmake     # BSD make
3726   #  echo World
3727   #  World
3728   msg ('portability', $where,
3729        "naming a subdirectory `obj' causes troubles with BSD make")
3730     if $dir eq 'obj';
3732   # `aux' is probably the most important of the following forbidden name,
3733   # since it's tempting to use it as an AC_CONFIG_AUX_DIR.
3734   msg ('portability', $where,
3735        "name `$dir' is reserved on W32 and DOS platforms")
3736     if grep (/^\Q$dir\E$/i, qw/aux lpt1 lpt2 lpt3 com1 com2 com3 com4 con prn/);
3739 # check_directories_in_var ($VARIABLE)
3740 # ------------------------------------
3741 # Recursively check all items in variables $VARIABLE as directories
3742 sub check_directories_in_var ($)
3744   my ($var) = @_;
3745   $var->traverse_recursively
3746     (sub
3747      {
3748        my ($var, $val, $cond, $full_cond) = @_;
3749        check_directory ($val, $var->rdef ($cond)->location);
3750        return ();
3751      },
3752      undef,
3753      skip_ac_subst => 1);
3756 # &handle_subdirs ()
3757 # ------------------
3758 # Handle subdirectories.
3759 sub handle_subdirs ()
3761   my $subdirs = var ('SUBDIRS');
3762   return
3763     unless $subdirs;
3765   check_directories_in_var $subdirs;
3767   my $dsubdirs = var ('DIST_SUBDIRS');
3768   check_directories_in_var $dsubdirs
3769     if $dsubdirs;
3771   $output_rules .= &file_contents ('subdirs', new Automake::Location);
3772   rvar ('RECURSIVE_TARGETS')->rdef (TRUE)->{'pretty'} = VAR_SORTED; # Gross!
3776 # ($REGEN, @DEPENDENCIES)
3777 # &scan_aclocal_m4
3778 # ----------------
3779 # If aclocal.m4 creation is automated, return the list of its dependencies.
3780 sub scan_aclocal_m4 ()
3782   my $regen_aclocal = 0;
3784   set_seen 'CONFIG_STATUS_DEPENDENCIES';
3785   set_seen 'CONFIGURE_DEPENDENCIES';
3787   if (-f 'aclocal.m4')
3788     {
3789       &define_variable ("ACLOCAL_M4", '$(top_srcdir)/aclocal.m4', INTERNAL);
3791       my $aclocal = new Automake::XFile "< aclocal.m4";
3792       my $line = $aclocal->getline;
3793       $regen_aclocal = $line =~ 'generated automatically by aclocal';
3794     }
3796   my @ac_deps = ();
3798   if (set_seen ('ACLOCAL_M4_SOURCES'))
3799     {
3800       push (@ac_deps, '$(ACLOCAL_M4_SOURCES)');
3801       msg_var ('obsolete', 'ACLOCAL_M4_SOURCES',
3802                "`ACLOCAL_M4_SOURCES' is obsolete.\n"
3803                . "It should be safe to simply remove it.");
3804     }
3806   # Note that it might be possible that aclocal.m4 doesn't exist but
3807   # should be auto-generated.  This case probably isn't very
3808   # important.
3810   return ($regen_aclocal, @ac_deps);
3814 # Helper function for substitute_ac_subst_variables.
3815 sub substitute_ac_subst_variables_worker($)
3817   my ($token) = @_;
3818   return "\@$token\@" if var $token;
3819   return "\${$token\}";
3822 # substitute_ac_subst_variables ($TEXT)
3823 # -------------------------------------
3824 # Replace any occurence of ${FOO} in $TEXT by @FOO@ if FOO is an AC_SUBST
3825 # variable.
3826 sub substitute_ac_subst_variables ($)
3828   my ($text) = @_;
3829   $text =~ s/\${([^ \t=:+{}]+)}/&substitute_ac_subst_variables_worker ($1)/ge;
3830   return $text;
3833 # @DEPENDENCIES
3834 # &prepend_srcdir (@INPUTS)
3835 # -------------------------
3836 # Prepend $(srcdir) or $(top_srcdir) to all @INPUTS.  The idea is that
3837 # if an input file has a directory part the same as the current
3838 # directory, then the directory part is simply replaced by $(srcdir).
3839 # But if the directory part is different, then $(top_srcdir) is
3840 # prepended.
3841 sub prepend_srcdir (@)
3843   my (@inputs) = @_;
3844   my @newinputs;
3846   foreach my $single (@inputs)
3847     {
3848       if (dirname ($single) eq $relative_dir)
3849         {
3850           push (@newinputs, '$(srcdir)/' . basename ($single));
3851         }
3852       else
3853         {
3854           push (@newinputs, '$(top_srcdir)/' . $single);
3855         }
3856     }
3857   return @newinputs;
3860 # @DEPENDENCIES
3861 # rewrite_inputs_into_dependencies ($OUTPUT, @INPUTS)
3862 # ---------------------------------------------------
3863 # Compute a list of dependencies appropriate for the rebuild
3864 # rule of
3865 #   AC_CONFIG_FILES($OUTPUT:$INPUT[0]:$INPUTS[1]:...)
3866 # Also distribute $INPUTs which are not build by another AC_CONFIG_FILES.
3867 sub rewrite_inputs_into_dependencies ($@)
3869   my ($file, @inputs) = @_;
3870   my @res = ();
3872   for my $i (@inputs)
3873     {
3874       # We cannot create dependencies on shell variables.
3875       next if (substitute_ac_subst_variables $i) =~ /\$/;
3877       if (exists $ac_config_files_location{$i})
3878         {
3879           my $di = dirname $i;
3880           if ($di eq $relative_dir)
3881             {
3882               $i = basename $i;
3883             }
3884           # In the top-level Makefile we do not use $(top_builddir), because
3885           # we are already there, and since the targets are built without
3886           # a $(top_builddir), it helps BSD Make to match them with
3887           # dependencies.
3888           elsif ($relative_dir ne '.')
3889             {
3890               $i = '$(top_builddir)/' . $i;
3891             }
3892         }
3893       else
3894         {
3895           msg ('error', $ac_config_files_location{$file},
3896                "required file `$i' not found")
3897             unless $i =~ /\$/ || exists $output_files{$i} || -f $i;
3898           ($i) = prepend_srcdir ($i);
3899           push_dist_common ($i);
3900         }
3901       push @res, $i;
3902     }
3903   return @res;
3908 # &handle_configure ($MAKEFILE_AM, $MAKEFILE_IN, $MAKEFILE, @INPUTS)
3909 # ------------------------------------------------------------------
3910 # Handle remaking and configure stuff.
3911 # We need the name of the input file, to do proper remaking rules.
3912 sub handle_configure ($$$@)
3914   my ($makefile_am, $makefile_in, $makefile, @inputs) = @_;
3916   prog_error 'empty @inputs'
3917     unless @inputs;
3919   my ($rel_makefile_am, $rel_makefile_in) = prepend_srcdir ($makefile_am,
3920                                                             $makefile_in);
3921   my $rel_makefile = basename $makefile;
3923   my $colon_infile = ':' . join (':', @inputs);
3924   $colon_infile = '' if $colon_infile eq ":$makefile.in";
3925   my @rewritten = rewrite_inputs_into_dependencies ($makefile, @inputs);
3926   my ($regen_aclocal_m4, @aclocal_m4_deps) = scan_aclocal_m4;
3927   define_pretty_variable ('am__aclocal_m4_deps', TRUE, INTERNAL,
3928                           @configure_deps, @aclocal_m4_deps,
3929                           '$(top_srcdir)/' . $configure_ac);
3930   my @configuredeps = ('$(am__aclocal_m4_deps)', '$(CONFIGURE_DEPENDENCIES)');
3931   push @configuredeps, '$(ACLOCAL_M4)' if -f 'aclocal.m4';
3932   define_pretty_variable ('am__configure_deps', TRUE, INTERNAL,
3933                           @configuredeps);
3935   $output_rules .= file_contents
3936     ('configure',
3937      new Automake::Location,
3938      MAKEFILE              => $rel_makefile,
3939      'MAKEFILE-DEPS'       => "@rewritten",
3940      'CONFIG-MAKEFILE'     => ($relative_dir eq '.') ? '$@' : '$(subdir)/$@',
3941      'MAKEFILE-IN'         => $rel_makefile_in,
3942      'MAKEFILE-IN-DEPS'    => "@include_stack",
3943      'MAKEFILE-AM'         => $rel_makefile_am,
3944      STRICTNESS            => global_option 'cygnus'
3945                                 ? 'cygnus' : $strictness_name,
3946      'USE-DEPS'            => global_option 'no-dependencies'
3947                                 ? ' --ignore-deps' : '',
3948      'MAKEFILE-AM-SOURCES' => "$makefile$colon_infile",
3949      'REGEN-ACLOCAL-M4'    => $regen_aclocal_m4);
3951   if ($relative_dir eq '.')
3952     {
3953       &push_dist_common ('acconfig.h')
3954         if -f 'acconfig.h';
3955     }
3957   # If we have a configure header, require it.
3958   my $hdr_index = 0;
3959   my @distclean_config;
3960   foreach my $spec (@config_headers)
3961     {
3962       $hdr_index += 1;
3963       # $CONFIG_H_PATH: config.h from top level.
3964       my ($config_h_path, @ins) = split_config_file_spec ($spec);
3965       my $config_h_dir = dirname ($config_h_path);
3967       # If the header is in the current directory we want to build
3968       # the header here.  Otherwise, if we're at the topmost
3969       # directory and the header's directory doesn't have a
3970       # Makefile, then we also want to build the header.
3971       if ($relative_dir eq $config_h_dir
3972           || ($relative_dir eq '.' && ! &is_make_dir ($config_h_dir)))
3973         {
3974           my ($cn_sans_dir, $stamp_dir);
3975           if ($relative_dir eq $config_h_dir)
3976             {
3977               $cn_sans_dir = basename ($config_h_path);
3978               $stamp_dir = '';
3979             }
3980           else
3981             {
3982               $cn_sans_dir = $config_h_path;
3983               if ($config_h_dir eq '.')
3984                 {
3985                   $stamp_dir = '';
3986                 }
3987               else
3988                 {
3989                   $stamp_dir = $config_h_dir . '/';
3990                 }
3991             }
3993           # This will also distribute all inputs.
3994           @ins = rewrite_inputs_into_dependencies ($config_h_path, @ins);
3996           # Cannot define rebuild rules for filenames with shell variables.
3997           next if (substitute_ac_subst_variables $config_h_path) =~ /\$/;
3999           # Header defined in this directory.
4000           my @files;
4001           if (-f $config_h_path . '.top')
4002             {
4003               push (@files, "$cn_sans_dir.top");
4004             }
4005           if (-f $config_h_path . '.bot')
4006             {
4007               push (@files, "$cn_sans_dir.bot");
4008             }
4010           push_dist_common (@files);
4012           # For now, acconfig.h can only appear in the top srcdir.
4013           if (-f 'acconfig.h')
4014             {
4015               push (@files, '$(top_srcdir)/acconfig.h');
4016             }
4018           my $stamp = "${stamp_dir}stamp-h${hdr_index}";
4019           $output_rules .=
4020             file_contents ('remake-hdr',
4021                            new Automake::Location,
4022                            FILES            => "@files",
4023                            CONFIG_H         => $cn_sans_dir,
4024                            CONFIG_HIN       => $ins[0],
4025                            CONFIG_H_DEPS    => "@ins",
4026                            CONFIG_H_PATH    => $config_h_path,
4027                            STAMP            => "$stamp");
4029           push @distclean_config, $cn_sans_dir, $stamp;
4030         }
4031     }
4033   $output_rules .= file_contents ('clean-hdr',
4034                                   new Automake::Location,
4035                                   FILES => "@distclean_config")
4036     if @distclean_config;
4038   # Distribute and define mkinstalldirs only if it is already present
4039   # in the package, for backward compatibility (some people may still
4040   # use $(mkinstalldirs)).
4041   my $mkidpath = "$config_aux_dir/mkinstalldirs";
4042   if (-f $mkidpath)
4043     {
4044       # Use require_file so that any existing script gets updated
4045       # by --force-missing.
4046       require_conf_file ($mkidpath, FOREIGN, 'mkinstalldirs');
4047       define_variable ('mkinstalldirs',
4048                        "\$(SHELL) $am_config_aux_dir/mkinstalldirs", INTERNAL);
4049     }
4050   else
4051     {
4052       # Use $(install_sh), not $(mkdir_p) because the latter requires
4053       # at least one argument, and $(mkinstalldirs) used to work
4054       # even without arguments (e.g. $(mkinstalldirs) $(conditional_dir)).
4055       define_variable ('mkinstalldirs', '$(install_sh) -d', INTERNAL);
4056     }
4058   reject_var ('CONFIG_HEADER',
4059               "`CONFIG_HEADER' is an anachronism; now determined "
4060               . "automatically\nfrom `$configure_ac'");
4062   my @config_h;
4063   foreach my $spec (@config_headers)
4064     {
4065       my ($out, @ins) = split_config_file_spec ($spec);
4066       # Generate CONFIG_HEADER define.
4067       if ($relative_dir eq dirname ($out))
4068         {
4069           push @config_h, basename ($out);
4070         }
4071       else
4072         {
4073           push @config_h, "\$(top_builddir)/$out";
4074         }
4075     }
4076   define_variable ("CONFIG_HEADER", "@config_h", INTERNAL)
4077     if @config_h;
4079   # Now look for other files in this directory which must be remade
4080   # by config.status, and generate rules for them.
4081   my @actual_other_files = ();
4082   foreach my $lfile (@other_input_files)
4083     {
4084       my $file;
4085       my @inputs;
4086       if ($lfile =~ /^([^:]*):(.*)$/)
4087         {
4088           # This is the ":" syntax of AC_OUTPUT.
4089           $file = $1;
4090           @inputs = split (':', $2);
4091         }
4092       else
4093         {
4094           # Normal usage.
4095           $file = $lfile;
4096           @inputs = $file . '.in';
4097         }
4099       # Automake files should not be stored in here, but in %MAKE_LIST.
4100       prog_error ("$lfile in \@other_input_files\n"
4101                   . "\@other_input_files = (@other_input_files)")
4102         if -f $file . '.am';
4104       my $local = basename ($file);
4106       # Make sure the dist directory for each input file is created.
4107       # We only have to do this at the topmost level though.  This
4108       # is a bit ugly but it easier than spreading out the logic,
4109       # especially in cases like AC_OUTPUT(foo/out:bar/in), where
4110       # there is no Makefile in bar/.
4111       fill_dist_dirs (@inputs)
4112         if $relative_dir eq '.';
4114       # We skip files that aren't in this directory.  However, if
4115       # the file's directory does not have a Makefile, and we are
4116       # currently doing `.', then we create a rule to rebuild the
4117       # file in the subdir.
4118       my $fd = dirname ($file);
4119       if ($fd ne $relative_dir)
4120         {
4121           if ($relative_dir eq '.' && ! &is_make_dir ($fd))
4122             {
4123               $local = $file;
4124             }
4125           else
4126             {
4127               next;
4128             }
4129         }
4131       my @rewritten_inputs = rewrite_inputs_into_dependencies ($file, @inputs);
4133       # Cannot output rules for shell variables.
4134       next if (substitute_ac_subst_variables $local) =~ /\$/;
4136       $output_rules .= ($local . ': '
4137                         . '$(top_builddir)/config.status '
4138                         . "@rewritten_inputs\n"
4139                         . "\t"
4140                         . 'cd $(top_builddir) && '
4141                         . '$(SHELL) ./config.status '
4142                         . ($relative_dir eq '.' ? '' : '$(subdir)/')
4143                         . '$@'
4144                         . "\n");
4145       push (@actual_other_files, $local);
4146     }
4148   # For links we should clean destinations and distribute sources.
4149   foreach my $spec (@config_links)
4150     {
4151       my ($link, $file) = split /:/, $spec;
4152       # Some people do AC_CONFIG_LINKS($computed).  We only handle
4153       # the DEST:SRC form.
4154       next unless $file;
4155       my $where = $ac_config_files_location{$link};
4157       # Skip destinations that contain shell variables.
4158       if ((substitute_ac_subst_variables $link) !~ /\$/)
4159         {
4160           # We skip links that aren't in this directory.  However, if
4161           # the link's directory does not have a Makefile, and we are
4162           # currently doing `.', then we add the link to CONFIG_CLEAN_FILES
4163           # in `.'s Makefile.in.
4164           my $local = basename ($link);
4165           my $fd = dirname ($link);
4166           if ($fd ne $relative_dir)
4167             {
4168               if ($relative_dir eq '.' && ! &is_make_dir ($fd))
4169                 {
4170                   $local = $link;
4171                 }
4172               else
4173                 {
4174                   $local = undef;
4175                 }
4176             }
4177           push @actual_other_files, $local if $local;
4178         }
4180       # Do not process sources that contain shell variables.
4181       if ((substitute_ac_subst_variables $file) !~ /\$/)
4182         {
4183           my $fd = dirname ($file);
4185           # Make sure the dist directory for each input file is created.
4186           # We only have to do this at the topmost level though.
4187           if ($relative_dir eq '.')
4188             {
4189               $dist_dirs{$fd} = 1;
4190             }
4192           # We distribute files that are in this directory.
4193           # At the top-level (`.') we also distribute files whose
4194           # directory does not have a Makefile.
4195           if (($fd eq $relative_dir)
4196               || ($relative_dir eq '.' && ! &is_make_dir ($fd)))
4197             {
4198               # The following will distribute $file as a side-effect when
4199               # it is appropriate (i.e., when $file is not already an output).
4200               # We do not need the result, just the side-effect.
4201               rewrite_inputs_into_dependencies ($link, $file);
4202             }
4203         }
4204     }
4206   # These files get removed by "make distclean".
4207   define_pretty_variable ('CONFIG_CLEAN_FILES', TRUE, INTERNAL,
4208                           @actual_other_files);
4211 # Handle C headers.
4212 sub handle_headers
4214     my @r = &am_install_var ('-defaultdist', 'header', 'HEADERS', 'include',
4215                              'oldinclude', 'pkginclude',
4216                              'noinst', 'check');
4217     foreach (@r)
4218     {
4219       next unless $_->[1] =~ /\..*$/;
4220       &saw_extension ($&);
4221     }
4224 sub handle_gettext
4226   return if ! $seen_gettext || $relative_dir ne '.';
4228   my $subdirs = var 'SUBDIRS';
4230   if (! $subdirs)
4231     {
4232       err_ac "AM_GNU_GETTEXT used but SUBDIRS not defined";
4233       return;
4234     }
4236   # Perform some sanity checks to help users get the right setup.
4237   # We disable these tests when po/ doesn't exist in order not to disallow
4238   # unusual gettext setups.
4239   #
4240   # Bruno Haible:
4241   # | The idea is:
4242   # |
4243   # |  1) If a package doesn't have a directory po/ at top level, it
4244   # |     will likely have multiple po/ directories in subpackages.
4245   # |
4246   # |  2) It is useful to warn for the absence of intl/ if AM_GNU_GETTEXT
4247   # |     is used without 'external'. It is also useful to warn for the
4248   # |     presence of intl/ if AM_GNU_GETTEXT([external]) is used. Both
4249   # |     warnings apply only to the usual layout of packages, therefore
4250   # |     they should both be disabled if no po/ directory is found at
4251   # |     top level.
4253   if (-d 'po')
4254     {
4255       my @subdirs = $subdirs->value_as_list_recursive;
4257       msg_var ('syntax', $subdirs,
4258                "AM_GNU_GETTEXT used but `po' not in SUBDIRS")
4259         if ! grep ($_ eq 'po', @subdirs);
4261       # intl/ is not required when AM_GNU_GETTEXT is called with
4262       # the `external' option.
4263       msg_var ('syntax', $subdirs,
4264                "AM_GNU_GETTEXT used but `intl' not in SUBDIRS")
4265         if (! $seen_gettext_external
4266             && ! grep ($_ eq 'intl', @subdirs));
4268       # intl/ should not be used with AM_GNU_GETTEXT([external])
4269       msg_var ('syntax', $subdirs,
4270                "`intl' should not be in SUBDIRS when "
4271                . "AM_GNU_GETTEXT([external]) is used")
4272         if ($seen_gettext_external && grep ($_ eq 'intl', @subdirs));
4273     }
4275   require_file ($ac_gettext_location, GNU, 'ABOUT-NLS');
4278 # Handle footer elements.
4279 sub handle_footer
4281     reject_rule ('.SUFFIXES',
4282                  "use variable `SUFFIXES', not target `.SUFFIXES'");
4284     # Note: AIX 4.1 /bin/make will fail if any suffix rule appears
4285     # before .SUFFIXES.  So we make sure that .SUFFIXES appears before
4286     # anything else, by sticking it right after the default: target.
4287     $output_header .= ".SUFFIXES:\n";
4288     my $suffixes = var 'SUFFIXES';
4289     my @suffixes = Automake::Rule::suffixes;
4290     if (@suffixes || $suffixes)
4291     {
4292         # Make sure SUFFIXES has unique elements.  Sort them to ensure
4293         # the output remains consistent.  However, $(SUFFIXES) is
4294         # always at the start of the list, unsorted.  This is done
4295         # because make will choose rules depending on the ordering of
4296         # suffixes, and this lets the user have some control.  Push
4297         # actual suffixes, and not $(SUFFIXES).  Some versions of make
4298         # do not like variable substitutions on the .SUFFIXES line.
4299         my @user_suffixes = ($suffixes
4300                              ? $suffixes->value_as_list_recursive : ());
4302         my %suffixes = map { $_ => 1 } @suffixes;
4303         delete @suffixes{@user_suffixes};
4305         $output_header .= (".SUFFIXES: "
4306                            . join (' ', @user_suffixes, sort keys %suffixes)
4307                            . "\n");
4308     }
4310     $output_trailer .= file_contents ('footer', new Automake::Location);
4314 # Generate `make install' rules.
4315 sub handle_install ()
4317   $output_rules .= &file_contents
4318     ('install',
4319      new Automake::Location,
4320      maybe_BUILT_SOURCES => (set_seen ('BUILT_SOURCES')
4321                              ? (" \$(BUILT_SOURCES)\n"
4322                                 . "\t\$(MAKE) \$(AM_MAKEFLAGS)")
4323                              : ''),
4324      'installdirs-local' => (user_phony_rule 'installdirs-local'
4325                              ? ' installdirs-local' : ''),
4326      am__installdirs => variable_value ('am__installdirs') || '');
4330 # Deal with all and all-am.
4331 sub handle_all ($)
4333     my ($makefile) = @_;
4335     # Output `all-am'.
4337     # Put this at the beginning for the sake of non-GNU makes.  This
4338     # is still wrong if these makes can run parallel jobs.  But it is
4339     # right enough.
4340     unshift (@all, basename ($makefile));
4342     foreach my $spec (@config_headers)
4343       {
4344         my ($out, @ins) = split_config_file_spec ($spec);
4345         push (@all, basename ($out))
4346           if dirname ($out) eq $relative_dir;
4347       }
4349     # Install `all' hooks.
4350     push (@all, "all-local")
4351       if user_phony_rule "all-local";
4353     &pretty_print_rule ("all-am:", "\t\t", @all);
4354     &depend ('.PHONY', 'all-am', 'all');
4357     # Output `all'.
4359     my @local_headers = ();
4360     push @local_headers, '$(BUILT_SOURCES)'
4361       if var ('BUILT_SOURCES');
4362     foreach my $spec (@config_headers)
4363       {
4364         my ($out, @ins) = split_config_file_spec ($spec);
4365         push @local_headers, basename ($out)
4366           if dirname ($out) eq $relative_dir;
4367       }
4369     if (@local_headers)
4370       {
4371         # We need to make sure config.h is built before we recurse.
4372         # We also want to make sure that built sources are built
4373         # before any ordinary `all' targets are run.  We can't do this
4374         # by changing the order of dependencies to the "all" because
4375         # that breaks when using parallel makes.  Instead we handle
4376         # things explicitly.
4377         $output_all .= ("all: @local_headers"
4378                         . "\n\t"
4379                         . '$(MAKE) $(AM_MAKEFLAGS) '
4380                         . (var ('SUBDIRS') ? 'all-recursive' : 'all-am')
4381                         . "\n\n");
4382       }
4383     else
4384       {
4385         $output_all .= "all: " . (var ('SUBDIRS')
4386                                   ? 'all-recursive' : 'all-am') . "\n\n";
4387       }
4391 # &do_check_merge_target ()
4392 # -------------------------
4393 # Handle check merge target specially.
4394 sub do_check_merge_target ()
4396   # Include user-defined local form of target.
4397   push @check_tests, 'check-local'
4398     if user_phony_rule 'check-local';
4400   # In --cygnus mode, check doesn't depend on all.
4401   if (option 'cygnus')
4402     {
4403       # Just run the local check rules.
4404       pretty_print_rule ('check-am:', "\t\t", @check);
4405     }
4406   else
4407     {
4408       # The check target must depend on the local equivalent of
4409       # `all', to ensure all the primary targets are built.  Then it
4410       # must build the local check rules.
4411       $output_rules .= "check-am: all-am\n";
4412       pretty_print_rule ("\t\$(MAKE) \$(AM_MAKEFLAGS)", "\t  ",
4413                          @check)
4414         if @check;
4415     }
4416   pretty_print_rule ("\t\$(MAKE) \$(AM_MAKEFLAGS)", "\t  ",
4417                      @check_tests)
4418     if @check_tests;
4420   depend '.PHONY', 'check', 'check-am';
4421   # Handle recursion.  We have to honor BUILT_SOURCES like for `all:'.
4422   $output_rules .= ("check: "
4423                     . (var ('BUILT_SOURCES')
4424                        ? "\$(BUILT_SOURCES)\n\t\$(MAKE) \$(AM_MAKEFLAGS) "
4425                        : '')
4426                     . (var ('SUBDIRS') ? 'check-recursive' : 'check-am')
4427                     . "\n");
4430 # handle_clean ($MAKEFILE)
4431 # ------------------------
4432 # Handle all 'clean' targets.
4433 sub handle_clean ($)
4435   my ($makefile) = @_;
4437   # Clean the files listed in user variables if they exist.
4438   $clean_files{'$(MOSTLYCLEANFILES)'} = MOSTLY_CLEAN
4439     if var ('MOSTLYCLEANFILES');
4440   $clean_files{'$(CLEANFILES)'} = CLEAN
4441     if var ('CLEANFILES');
4442   $clean_files{'$(DISTCLEANFILES)'} = DIST_CLEAN
4443     if var ('DISTCLEANFILES');
4444   $clean_files{'$(MAINTAINERCLEANFILES)'} = MAINTAINER_CLEAN
4445     if var ('MAINTAINERCLEANFILES');
4447   # Built sources are automatically removed by maintainer-clean.
4448   $clean_files{'$(BUILT_SOURCES)'} = MAINTAINER_CLEAN
4449     if var ('BUILT_SOURCES');
4451   # Compute a list of "rm"s to run for each target.
4452   my %rms = (MOSTLY_CLEAN, [],
4453              CLEAN, [],
4454              DIST_CLEAN, [],
4455              MAINTAINER_CLEAN, []);
4457   foreach my $file (keys %clean_files)
4458     {
4459       my $when = $clean_files{$file};
4460       prog_error 'invalid entry in %clean_files'
4461         unless exists $rms{$when};
4463       my $rm = "rm -f $file";
4464       # If file is a variable, make sure when don't call `rm -f' without args.
4465       $rm ="test -z \"$file\" || $rm"
4466         if ($file =~ /^\s*\$(\(.*\)|\{.*\})\s*$/);
4468       push @{$rms{$when}}, "\t-$rm\n";
4469     }
4471   $output_rules .= &file_contents
4472     ('clean',
4473      new Automake::Location,
4474      MOSTLYCLEAN_RMS      => join ('', sort @{$rms{&MOSTLY_CLEAN}}),
4475      CLEAN_RMS            => join ('', sort @{$rms{&CLEAN}}),
4476      DISTCLEAN_RMS        => join ('', sort @{$rms{&DIST_CLEAN}}),
4477      MAINTAINER_CLEAN_RMS => join ('', sort @{$rms{&MAINTAINER_CLEAN}}),
4478      MAKEFILE             => basename $makefile,
4479      );
4483 # &target_cmp ($A, $B)
4484 # --------------------
4485 # Subroutine for &handle_factored_dependencies to let `.PHONY' and
4486 # other `.TARGETS' be last.
4487 sub target_cmp
4489   return 0 if $a eq $b;
4491   my $a1 = substr ($a, 0, 1);
4492   my $b1 = substr ($b, 0, 1);
4493   if ($a1 ne $b1)
4494     {
4495       return -1 if $b1 eq '.';
4496       return 1 if $a1 eq '.';
4497     }
4498   return $a cmp $b;
4502 # &handle_factored_dependencies ()
4503 # --------------------------------
4504 # Handle everything related to gathered targets.
4505 sub handle_factored_dependencies
4507   # Reject bad hooks.
4508   foreach my $utarg ('uninstall-data-local', 'uninstall-data-hook',
4509                      'uninstall-exec-local', 'uninstall-exec-hook',
4510                      'uninstall-dvi-local',
4511                      'uninstall-html-local',
4512                      'uninstall-info-local',
4513                      'uninstall-pdf-local',
4514                      'uninstall-ps-local')
4515     {
4516       my $x = $utarg;
4517       $x =~ s/-.*-/-/;
4518       reject_rule ($utarg, "use `$x', not `$utarg'");
4519     }
4521   reject_rule ('install-local',
4522                "use `install-data-local' or `install-exec-local', "
4523                . "not `install-local'");
4525   reject_rule ('install-hook',
4526                "use `install-data-hook' or `install-exec-hook', "
4527                . "not `install-hook'");
4529   # Install the -local hooks.
4530   foreach (keys %dependencies)
4531     {
4532       # Hooks are installed on the -am targets.
4533       s/-am$// or next;
4534       depend ("$_-am", "$_-local")
4535         if user_phony_rule "$_-local";
4536     }
4538   # Install the -hook hooks.
4539   # FIXME: Why not be as liberal as we are with -local hooks?
4540   foreach ('install-exec', 'install-data', 'uninstall')
4541     {
4542       if (user_phony_rule "$_-hook")
4543         {
4544           $actions{"$_-am"} .=
4545             ("\t\@\$(NORMAL_INSTALL)\n"
4546              . "\t" . '$(MAKE) $(AM_MAKEFLAGS) ' . "$_-hook\n");
4547           depend ('.MAKE', "$_-am");
4548         }
4549     }
4551   # All the required targets are phony.
4552   depend ('.PHONY', keys %required_targets);
4554   # Actually output gathered targets.
4555   foreach (sort target_cmp keys %dependencies)
4556     {
4557       # If there is nothing about this guy, skip it.
4558       next
4559         unless (@{$dependencies{$_}}
4560                 || $actions{$_}
4561                 || $required_targets{$_});
4563       # Define gathered targets in undefined conditions.
4564       # FIXME: Right now we must handle .PHONY as an exception,
4565       # because people write things like
4566       #    .PHONY: myphonytarget
4567       # to append dependencies.  This would not work if Automake
4568       # refrained from defining its own .PHONY target as it does
4569       # with other overridden targets.
4570       # Likewise for `.MAKE'.
4571       my @undefined_conds = (TRUE,);
4572       if ($_ ne '.PHONY' && $_ ne '.MAKE')
4573         {
4574           @undefined_conds =
4575             Automake::Rule::define ($_, 'internal',
4576                                     RULE_AUTOMAKE, TRUE, INTERNAL);
4577         }
4578       my @uniq_deps = uniq (sort @{$dependencies{$_}});
4579       foreach my $cond (@undefined_conds)
4580         {
4581           my $condstr = $cond->subst_string;
4582           &pretty_print_rule ("$condstr$_:", "$condstr\t", @uniq_deps);
4583           $output_rules .= $actions{$_} if defined $actions{$_};
4584           $output_rules .= "\n";
4585         }
4586     }
4590 # &handle_tests_dejagnu ()
4591 # ------------------------
4592 sub handle_tests_dejagnu
4594     push (@check_tests, 'check-DEJAGNU');
4595     $output_rules .= file_contents ('dejagnu', new Automake::Location);
4599 # Handle TESTS variable and other checks.
4600 sub handle_tests
4602   if (option 'dejagnu')
4603     {
4604       &handle_tests_dejagnu;
4605     }
4606   else
4607     {
4608       foreach my $c ('DEJATOOL', 'RUNTEST', 'RUNTESTFLAGS')
4609         {
4610           reject_var ($c, "`$c' defined but `dejagnu' not in "
4611                       . "`AUTOMAKE_OPTIONS'");
4612         }
4613     }
4615   if (var ('TESTS'))
4616     {
4617       push (@check_tests, 'check-TESTS');
4618       $output_rules .= &file_contents ('check', new Automake::Location);
4620       # Tests that are known programs should have $(EXEEXT) appended.
4621       append_exeext { exists $known_programs{$_[0]} } 'TESTS';
4622     }
4625 # Handle Emacs Lisp.
4626 sub handle_emacs_lisp
4628   my @elfiles = &am_install_var ('-candist', 'lisp', 'LISP',
4629                                  'lisp', 'noinst');
4631   return if ! @elfiles;
4633   define_pretty_variable ('am__ELFILES', TRUE, INTERNAL,
4634                           map { $_->[1] } @elfiles);
4635   define_pretty_variable ('am__ELCFILES', TRUE, INTERNAL,
4636                           '$(am__ELFILES:.el=.elc)');
4637   # This one can be overridden by users.
4638   define_pretty_variable ('ELCFILES', TRUE, INTERNAL, '$(LISP:.el=.elc)');
4640   push @all, '$(ELCFILES)';
4642   require_variables ($elfiles[0][0], "Emacs Lisp sources seen", TRUE,
4643                      'EMACS', 'lispdir');
4644   require_conf_file ($elfiles[0][0], FOREIGN, 'elisp-comp');
4645   &define_variable ('elisp_comp', "$am_config_aux_dir/elisp-comp", INTERNAL);
4648 # Handle Python
4649 sub handle_python
4651   my @pyfiles = &am_install_var ('-defaultdist', 'python', 'PYTHON',
4652                                  'noinst');
4653   return if ! @pyfiles;
4655   require_variables ($pyfiles[0][0], "Python sources seen", TRUE, 'PYTHON');
4656   require_conf_file ($pyfiles[0][0], FOREIGN, 'py-compile');
4657   &define_variable ('py_compile', "$am_config_aux_dir/py-compile", INTERNAL);
4660 # Handle Java.
4661 sub handle_java
4663     my @sourcelist = &am_install_var ('-candist',
4664                                       'java', 'JAVA',
4665                                       'java', 'noinst', 'check');
4666     return if ! @sourcelist;
4668     my @prefix = am_primary_prefixes ('JAVA', 1,
4669                                       'java', 'noinst', 'check');
4671     my $dir;
4672     foreach my $curs (@prefix)
4673       {
4674         next
4675           if $curs eq 'EXTRA';
4677         err_var "${curs}_JAVA", "multiple _JAVA primaries in use"
4678           if defined $dir;
4679         $dir = $curs;
4680       }
4683     push (@all, 'class' . $dir . '.stamp');
4687 # Handle some of the minor options.
4688 sub handle_minor_options
4690   if (option 'readme-alpha')
4691     {
4692       if ($relative_dir eq '.')
4693         {
4694           if ($package_version !~ /^$GNITS_VERSION_PATTERN$/)
4695             {
4696               msg ('error-gnits', $package_version_location,
4697                    "version `$package_version' doesn't follow " .
4698                    "Gnits standards");
4699             }
4700           if (defined $1 && -f 'README-alpha')
4701             {
4702               # This means we have an alpha release.  See
4703               # GNITS_VERSION_PATTERN for details.
4704               push_dist_common ('README-alpha');
4705             }
4706         }
4707     }
4710 ################################################################
4712 # ($OUTPUT, @INPUTS)
4713 # &split_config_file_spec ($SPEC)
4714 # -------------------------------
4715 # Decode the Autoconf syntax for config files (files, headers, links
4716 # etc.).
4717 sub split_config_file_spec ($)
4719   my ($spec) = @_;
4720   my ($output, @inputs) = split (/:/, $spec);
4722   push @inputs, "$output.in"
4723     unless @inputs;
4725   return ($output, @inputs);
4728 # $input
4729 # locate_am (@POSSIBLE_SOURCES)
4730 # -----------------------------
4731 # AC_CONFIG_FILES allow specifications such as Makefile:top.in:mid.in:bot.in
4732 # This functions returns the first *.in file for which a *.am exists.
4733 # It returns undef otherwise.
4734 sub locate_am (@)
4736   my (@rest) = @_;
4737   my $input;
4738   foreach my $file (@rest)
4739     {
4740       if (($file =~ /^(.*)\.in$/) && -f "$1.am")
4741         {
4742           $input = $file;
4743           last;
4744         }
4745     }
4746   return $input;
4749 my %make_list;
4751 # &scan_autoconf_config_files ($WHERE, $CONFIG-FILES)
4752 # ---------------------------------------------------
4753 # Study $CONFIG-FILES which is the first argument to AC_CONFIG_FILES
4754 # (or AC_OUTPUT).
4755 sub scan_autoconf_config_files ($$)
4757   my ($where, $config_files) = @_;
4759   # Look at potential Makefile.am's.
4760   foreach (split ' ', $config_files)
4761     {
4762       # Must skip empty string for Perl 4.
4763       next if $_ eq "\\" || $_ eq '';
4765       # Handle $local:$input syntax.
4766       my ($local, @rest) = split (/:/);
4767       @rest = ("$local.in",) unless @rest;
4768       my $input = locate_am @rest;
4769       if ($input)
4770         {
4771           # We have a file that automake should generate.
4772           $make_list{$input} = join (':', ($local, @rest));
4773         }
4774       else
4775         {
4776           # We have a file that automake should cause to be
4777           # rebuilt, but shouldn't generate itself.
4778           push (@other_input_files, $_);
4779         }
4780       $ac_config_files_location{$local} = $where;
4781     }
4785 # &scan_autoconf_traces ($FILENAME)
4786 # ---------------------------------
4787 sub scan_autoconf_traces ($)
4789   my ($filename) = @_;
4791   # Macros to trace, with their minimal number of arguments.
4792   #
4793   # IMPORTANT: If you add a macro here, you should also add this macro
4794   # =========  to Automake-preselection in autoconf/lib/autom4te.in.
4795   my %traced = (
4796                 AC_CANONICAL_BUILD => 0,
4797                 AC_CANONICAL_HOST => 0,
4798                 AC_CANONICAL_TARGET => 0,
4799                 AC_CONFIG_AUX_DIR => 1,
4800                 AC_CONFIG_FILES => 1,
4801                 AC_CONFIG_HEADERS => 1,
4802                 AC_CONFIG_LIBOBJ_DIR => 1,
4803                 AC_CONFIG_LINKS => 1,
4804                 AC_INIT => 0,
4805                 AC_LIBSOURCE => 1,
4806                 AC_REQUIRE_AUX_FILE => 1,
4807                 AC_SUBST_TRACE => 1,
4808                 AM_AUTOMAKE_VERSION => 1,
4809                 AM_CONDITIONAL => 2,
4810                 AM_ENABLE_MULTILIB => 0,
4811                 AM_GNU_GETTEXT => 0,
4812                 AM_INIT_AUTOMAKE => 0,
4813                 AM_MAINTAINER_MODE => 0,
4814                 AM_PROG_CC_C_O => 0,
4815                 _AM_SUBST_NOTMAKE => 1,
4816                 LT_SUPPORTED_TAG => 1,
4817                 _LT_AC_TAGCONFIG => 0,
4818                 m4_include => 1,
4819                 m4_sinclude => 1,
4820                 sinclude => 1,
4821               );
4823   my $traces = ($ENV{AUTOCONF} || 'autoconf') . " ";
4825   # Use a separator unlikely to be used, not `:', the default, which
4826   # has a precise meaning for AC_CONFIG_FILES and so on.
4827   $traces .= join (' ',
4828                    map { "--trace=$_" . ':\$f:\$l::\$n::\${::}%' }
4829                    (keys %traced));
4831   my $tracefh = new Automake::XFile ("$traces $filename |");
4832   verb "reading $traces";
4834   while ($_ = $tracefh->getline)
4835     {
4836       chomp;
4837       my ($here, @args) = split (/::/);
4838       my $where = new Automake::Location $here;
4839       my $macro = $args[0];
4841       prog_error ("unrequested trace `$macro'")
4842         unless exists $traced{$macro};
4844       # Skip and diagnose malformed calls.
4845       if ($#args < $traced{$macro})
4846         {
4847           msg ('syntax', $where, "not enough arguments for $macro");
4848           next;
4849         }
4851       # Alphabetical ordering please.
4852       if ($macro eq 'AC_CANONICAL_BUILD')
4853         {
4854           if ($seen_canonical <= AC_CANONICAL_BUILD)
4855             {
4856               $seen_canonical = AC_CANONICAL_BUILD;
4857               $canonical_location = $where;
4858             }
4859         }
4860       elsif ($macro eq 'AC_CANONICAL_HOST')
4861         {
4862           if ($seen_canonical <= AC_CANONICAL_HOST)
4863             {
4864               $seen_canonical = AC_CANONICAL_HOST;
4865               $canonical_location = $where;
4866             }
4867         }
4868       elsif ($macro eq 'AC_CANONICAL_TARGET')
4869         {
4870           $seen_canonical = AC_CANONICAL_TARGET;
4871           $canonical_location = $where;
4872         }
4873       elsif ($macro eq 'AC_CONFIG_AUX_DIR')
4874         {
4875           if ($seen_init_automake)
4876             {
4877               error ($where, "AC_CONFIG_AUX_DIR must be called before "
4878                      . "AM_INIT_AUTOMAKE...", partial => 1);
4879               error ($seen_init_automake, "... AM_INIT_AUTOMAKE called here");
4880             }
4881           $config_aux_dir = $args[1];
4882           $config_aux_dir_set_in_configure_ac = 1;
4883           $relative_dir = '.';
4884           check_directory ($config_aux_dir, $where);
4885         }
4886       elsif ($macro eq 'AC_CONFIG_FILES')
4887         {
4888           # Look at potential Makefile.am's.
4889           scan_autoconf_config_files ($where, $args[1]);
4890         }
4891       elsif ($macro eq 'AC_CONFIG_HEADERS')
4892         {
4893           foreach my $spec (split (' ', $args[1]))
4894             {
4895               my ($dest, @src) = split (':', $spec);
4896               $ac_config_files_location{$dest} = $where;
4897               push @config_headers, $spec;
4898             }
4899         }
4900       elsif ($macro eq 'AC_CONFIG_LIBOBJ_DIR')
4901         {
4902           $config_libobj_dir = $args[1];
4903           $relative_dir = '.';
4904           check_directory ($config_libobj_dir, $where);
4905         }
4906       elsif ($macro eq 'AC_CONFIG_LINKS')
4907         {
4908           foreach my $spec (split (' ', $args[1]))
4909             {
4910               my ($dest, $src) = split (':', $spec);
4911               $ac_config_files_location{$dest} = $where;
4912               push @config_links, $spec;
4913             }
4914         }
4915       elsif ($macro eq 'AC_INIT')
4916         {
4917           if (defined $args[2])
4918             {
4919               $package_version = $args[2];
4920               $package_version_location = $where;
4921             }
4922         }
4923       elsif ($macro eq 'AC_LIBSOURCE')
4924         {
4925           $libsources{$args[1]} = $here;
4926         }
4927       elsif ($macro eq 'AC_REQUIRE_AUX_FILE')
4928         {
4929           # Only remember the first time a file is required.
4930           $required_aux_file{$args[1]} = $where
4931             unless exists $required_aux_file{$args[1]};
4932         }
4933       elsif ($macro eq 'AC_SUBST_TRACE')
4934         {
4935           # Just check for alphanumeric in AC_SUBST_TRACE.  If you do
4936           # AC_SUBST(5), then too bad.
4937           $configure_vars{$args[1]} = $where
4938             if $args[1] =~ /^\w+$/;
4939         }
4940       elsif ($macro eq 'AM_AUTOMAKE_VERSION')
4941         {
4942           error ($where,
4943                  "version mismatch.  This is Automake $VERSION,\n" .
4944                  "but the definition used by this AM_INIT_AUTOMAKE\n" .
4945                  "comes from Automake $args[1].  You should recreate\n" .
4946                  "aclocal.m4 with aclocal and run automake again.\n",
4947                  # $? = 63 is used to indicate version mismatch to missing.
4948                  exit_code => 63)
4949             if $VERSION ne $args[1];
4951           $seen_automake_version = 1;
4952         }
4953       elsif ($macro eq 'AM_CONDITIONAL')
4954         {
4955           $configure_cond{$args[1]} = $where;
4956         }
4957       elsif ($macro eq 'AM_ENABLE_MULTILIB')
4958         {
4959           $seen_multilib = $where;
4960         }
4961       elsif ($macro eq 'AM_GNU_GETTEXT')
4962         {
4963           $seen_gettext = $where;
4964           $ac_gettext_location = $where;
4965           $seen_gettext_external = grep ($_ eq 'external', @args);
4966         }
4967       elsif ($macro eq 'AM_INIT_AUTOMAKE')
4968         {
4969           $seen_init_automake = $where;
4970           if (defined $args[2])
4971             {
4972               $package_version = $args[2];
4973               $package_version_location = $where;
4974             }
4975           elsif (defined $args[1])
4976             {
4977               exit $exit_code
4978                 if (process_global_option_list ($where,
4979                                                 split (' ', $args[1])));
4980             }
4981         }
4982       elsif ($macro eq 'AM_MAINTAINER_MODE')
4983         {
4984           $seen_maint_mode = $where;
4985         }
4986       elsif ($macro eq 'AM_PROG_CC_C_O')
4987         {
4988           $seen_cc_c_o = $where;
4989         }
4990       elsif ($macro eq '_AM_SUBST_NOTMAKE')
4991         {
4992           $ignored_configure_vars{$args[1]} = $where;
4993         }
4994       elsif ($macro eq 'm4_include'
4995              || $macro eq 'm4_sinclude'
4996              || $macro eq 'sinclude')
4997         {
4998           # Skip missing `sinclude'd files.
4999           next if $macro ne 'm4_include' && ! -f $args[1];
5001           # Some modified versions of Autoconf don't use
5002           # forzen files.  Consequently it's possible that we see all
5003           # m4_include's performed during Autoconf's startup.
5004           # Obviously we don't want to distribute Autoconf's files
5005           # so we skip absolute filenames here.
5006           push @configure_deps, '$(top_srcdir)/' . $args[1]
5007             unless $here =~ m,^(?:\w:)?[\\/],;
5008           # Keep track of the greatest timestamp.
5009           if (-e $args[1])
5010             {
5011               my $mtime = mtime $args[1];
5012               $configure_deps_greatest_timestamp = $mtime
5013                 if $mtime > $configure_deps_greatest_timestamp;
5014             }
5015         }
5016       elsif ($macro eq 'LT_SUPPORTED_TAG')
5017         {
5018           $libtool_tags{$args[1]} = 1;
5019           $libtool_new_api = 1;
5020         }
5021       elsif ($macro eq '_LT_AC_TAGCONFIG')
5022         {
5023           # _LT_AC_TAGCONFIG is an old macro present in Libtool 1.5.
5024           # We use it to detect whether tags are supported.  Our
5025           # prefered interface is LT_SUPPORTED_TAG, but it was
5026           # introduced in Libtool 1.6.
5027           if (0 == keys %libtool_tags)
5028             {
5029               # Hardcode the tags supported by Libtool 1.5.
5030               %libtool_tags = (CC => 1, CXX => 1, GCJ => 1, F77 => 1);
5031             }
5032         }
5033     }
5035   $tracefh->close;
5039 # &scan_autoconf_files ()
5040 # -----------------------
5041 # Check whether we use `configure.ac' or `configure.in'.
5042 # Scan it (and possibly `aclocal.m4') for interesting things.
5043 # We must scan aclocal.m4 because there might be AC_SUBSTs and such there.
5044 sub scan_autoconf_files ()
5046   # Reinitialize libsources here.  This isn't really necessary,
5047   # since we currently assume there is only one configure.ac.  But
5048   # that won't always be the case.
5049   %libsources = ();
5051   # Keep track of the youngest configure dependency.
5052   $configure_deps_greatest_timestamp = mtime $configure_ac;
5053   if (-e 'aclocal.m4')
5054     {
5055       my $mtime = mtime 'aclocal.m4';
5056       $configure_deps_greatest_timestamp = $mtime
5057         if $mtime > $configure_deps_greatest_timestamp;
5058     }
5060   scan_autoconf_traces ($configure_ac);
5062   @configure_input_files = sort keys %make_list;
5063   # Set input and output files if not specified by user.
5064   if (! @input_files)
5065     {
5066       @input_files = @configure_input_files;
5067       %output_files = %make_list;
5068     }
5071   if (! $seen_init_automake)
5072     {
5073       err_ac ("no proper invocation of AM_INIT_AUTOMAKE was found.\nYou "
5074               . "should verify that $configure_ac invokes AM_INIT_AUTOMAKE,"
5075               . "\nthat aclocal.m4 is present in the top-level directory,\n"
5076               . "and that aclocal.m4 was recently regenerated "
5077               . "(using aclocal).");
5078     }
5079   else
5080     {
5081       if (! $seen_automake_version)
5082         {
5083           if (-f 'aclocal.m4')
5084             {
5085               error ($seen_init_automake,
5086                      "your implementation of AM_INIT_AUTOMAKE comes from " .
5087                      "an\nold Automake version.  You should recreate " .
5088                      "aclocal.m4\nwith aclocal and run automake again.\n",
5089                      # $? = 63 is used to indicate version mismatch to missing.
5090                      exit_code => 63);
5091             }
5092           else
5093             {
5094               error ($seen_init_automake,
5095                      "no proper implementation of AM_INIT_AUTOMAKE was " .
5096                      "found,\nprobably because aclocal.m4 is missing...\n" .
5097                      "You should run aclocal to create this file, then\n" .
5098                      "run automake again.\n");
5099             }
5100         }
5101     }
5103   locate_aux_dir ();
5105   # Reorder @input_files so that the Makefile that distributes aux
5106   # files is processed last.  This is important because each directory
5107   # can require auxiliary scripts and we should wait until they have
5108   # been installed before distributing them.
5110   # The Makefile.in that distribute the aux files is the one in
5111   # $config_aux_dir or the top-level Makefile.
5112   my $auxdirdist = is_make_dir ($config_aux_dir) ? $config_aux_dir : '.';
5113   my @new_input_files = ();
5114   while (@input_files)
5115     {
5116       my $in = pop @input_files;
5117       my @ins = split (/:/, $output_files{$in});
5118       if (dirname ($ins[0]) eq $auxdirdist)
5119         {
5120           push @new_input_files, $in;
5121           $automake_will_process_aux_dir = 1;
5122         }
5123       else
5124         {
5125           unshift @new_input_files, $in;
5126         }
5127     }
5128   @input_files = @new_input_files;
5130   # If neither the auxdir/Makefile nor the ./Makefile are generated
5131   # by Automake, we won't distribute the aux files anyway.  Assume
5132   # the user know what (s)he does, and pretend we will distribute
5133   # them to disable the error in require_file_internal.
5134   $automake_will_process_aux_dir = 1 if ! is_make_dir ($auxdirdist);
5136   # Look for some files we need.  Always check for these.  This
5137   # check must be done for every run, even those where we are only
5138   # looking at a subdir Makefile.  We must set relative_dir for
5139   # maybe_push_required_file to work.
5140   $relative_dir = '.';
5141   foreach my $file (keys %required_aux_file)
5142     {
5143       require_conf_file ($required_aux_file{$file}->get, FOREIGN, $file)
5144     }
5145   err_am "`install.sh' is an anachronism; use `install-sh' instead"
5146     if -f $config_aux_dir . '/install.sh';
5148   # Preserve dist_common for later.
5149   $configure_dist_common = variable_value ('DIST_COMMON') || '';
5153 ################################################################
5155 # Set up for Cygnus mode.
5156 sub check_cygnus
5158   my $cygnus = option 'cygnus';
5159   return unless $cygnus;
5161   set_strictness ('foreign');
5162   set_option ('no-installinfo', $cygnus);
5163   set_option ('no-dependencies', $cygnus);
5164   set_option ('no-dist', $cygnus);
5166   err_ac "`AM_MAINTAINER_MODE' required when --cygnus specified"
5167     if !$seen_maint_mode;
5170 # Do any extra checking for GNU standards.
5171 sub check_gnu_standards
5173   if ($relative_dir eq '.')
5174     {
5175       # In top level (or only) directory.
5176       require_file ("$am_file.am", GNU,
5177                     qw/INSTALL NEWS README AUTHORS ChangeLog/);
5179       # Accept one of these three licenses; default to COPYING.
5180       # Make sure we do not overwrite an existing license.
5181       my $license;
5182       foreach (qw /COPYING COPYING.LIB COPYING.LESSER/)
5183         {
5184           if (-f $_)
5185             {
5186               $license = $_;
5187               last;
5188             }
5189         }
5190       require_file ("$am_file.am", GNU, 'COPYING')
5191         unless $license;
5192     }
5194   for my $opt ('no-installman', 'no-installinfo')
5195     {
5196       msg ('error-gnu', option $opt,
5197            "option `$opt' disallowed by GNU standards")
5198         if option $opt;
5199     }
5202 # Do any extra checking for GNITS standards.
5203 sub check_gnits_standards
5205   if ($relative_dir eq '.')
5206     {
5207       # In top level (or only) directory.
5208       require_file ("$am_file.am", GNITS, 'THANKS');
5209     }
5212 ################################################################
5214 # Functions to handle files of each language.
5216 # Each `lang_X_rewrite($DIRECTORY, $BASE, $EXT)' function follows a
5217 # simple formula: Return value is LANG_SUBDIR if the resulting object
5218 # file should be in a subdir if the source file is, LANG_PROCESS if
5219 # file is to be dealt with, LANG_IGNORE otherwise.
5221 # Much of the actual processing is handled in
5222 # handle_single_transform.  These functions exist so that
5223 # auxiliary information can be recorded for a later cleanup pass.
5224 # Note that the calls to these functions are computed, so don't bother
5225 # searching for their precise names in the source.
5227 # This is just a convenience function that can be used to determine
5228 # when a subdir object should be used.
5229 sub lang_sub_obj
5231     return option 'subdir-objects' ? LANG_SUBDIR : LANG_PROCESS;
5234 # Rewrite a single C source file.
5235 sub lang_c_rewrite
5237   my ($directory, $base, $ext, $nonansi_obj, $have_per_exec_flags, $var) = @_;
5239   if (option 'ansi2knr' && $base =~ /_$/)
5240     {
5241       # FIXME: include line number in error.
5242       err_am "C source file `$base.c' would be deleted by ansi2knr rules";
5243     }
5245   my $r = LANG_PROCESS;
5246   if (option 'subdir-objects')
5247     {
5248       $r = LANG_SUBDIR;
5249       if ($directory && $directory ne '.')
5250         {
5251           $base = $directory . '/' . $base;
5253           # libtool is always able to put the object at the proper place,
5254           # so we do not have to require AM_PROG_CC_C_O when building .lo files.
5255           msg_var ('portability', $var,
5256                    "compiling `$base.c' in subdir requires "
5257                    . "`AM_PROG_CC_C_O' in `$configure_ac'",
5258                    uniq_scope => US_GLOBAL,
5259                    uniq_part => 'AM_PROG_CC_C_O subdir')
5260             unless $seen_cc_c_o || $nonansi_obj eq '.lo';
5261         }
5263       # In this case we already have the directory information, so
5264       # don't add it again.
5265       $de_ansi_files{$base} = '';
5266     }
5267   else
5268     {
5269       $de_ansi_files{$base} = (($directory eq '.' || $directory eq '')
5270                                ? ''
5271                                : "$directory/");
5272     }
5274   if (! $seen_cc_c_o
5275       && $have_per_exec_flags
5276       && ! option 'subdir-objects'
5277       && $nonansi_obj ne '.lo')
5278     {
5279       msg_var ('portability',
5280                $var, "compiling `$base.c' with per-target flags requires "
5281                . "`AM_PROG_CC_C_O' in `$configure_ac'",
5282                uniq_scope => US_GLOBAL,
5283                uniq_part => 'AM_PROG_CC_C_O per-target')
5284     }
5286     return $r;
5289 # Rewrite a single C++ source file.
5290 sub lang_cxx_rewrite
5292     return &lang_sub_obj;
5295 # Rewrite a single header file.
5296 sub lang_header_rewrite
5298     # Header files are simply ignored.
5299     return LANG_IGNORE;
5302 # Rewrite a single yacc file.
5303 sub lang_yacc_rewrite
5305     my ($directory, $base, $ext) = @_;
5307     my $r = &lang_sub_obj;
5308     (my $newext = $ext) =~ tr/y/c/;
5309     return ($r, $newext);
5312 # Rewrite a single yacc++ file.
5313 sub lang_yaccxx_rewrite
5315     my ($directory, $base, $ext) = @_;
5317     my $r = &lang_sub_obj;
5318     (my $newext = $ext) =~ tr/y/c/;
5319     return ($r, $newext);
5322 # Rewrite a single lex file.
5323 sub lang_lex_rewrite
5325     my ($directory, $base, $ext) = @_;
5327     my $r = &lang_sub_obj;
5328     (my $newext = $ext) =~ tr/l/c/;
5329     return ($r, $newext);
5332 # Rewrite a single lex++ file.
5333 sub lang_lexxx_rewrite
5335     my ($directory, $base, $ext) = @_;
5337     my $r = &lang_sub_obj;
5338     (my $newext = $ext) =~ tr/l/c/;
5339     return ($r, $newext);
5342 # Rewrite a single assembly file.
5343 sub lang_asm_rewrite
5345     return &lang_sub_obj;
5348 # Rewrite a single preprocessed assembly file.
5349 sub lang_cppasm_rewrite
5351     return &lang_sub_obj;
5354 # Rewrite a single Fortran 77 file.
5355 sub lang_f77_rewrite
5357     return LANG_PROCESS;
5360 # Rewrite a single Fortran file.
5361 sub lang_fc_rewrite
5363     return LANG_PROCESS;
5366 # Rewrite a single preprocessed Fortran file.
5367 sub lang_ppfc_rewrite
5369     return LANG_PROCESS;
5372 # Rewrite a single preprocessed Fortran 77 file.
5373 sub lang_ppf77_rewrite
5375     return LANG_PROCESS;
5378 # Rewrite a single ratfor file.
5379 sub lang_ratfor_rewrite
5381     return LANG_PROCESS;
5384 # Rewrite a single Objective C file.
5385 sub lang_objc_rewrite
5387     return &lang_sub_obj;
5390 # Rewrite a single Java file.
5391 sub lang_java_rewrite
5393     return LANG_SUBDIR;
5396 # The lang_X_finish functions are called after all source file
5397 # processing is done.  Each should handle defining rules for the
5398 # language, etc.  A finish function is only called if a source file of
5399 # the appropriate type has been seen.
5401 sub lang_c_finish
5403     # Push all libobjs files onto de_ansi_files.  We actually only
5404     # push files which exist in the current directory, and which are
5405     # genuine source files.
5406     foreach my $file (keys %libsources)
5407     {
5408         if ($file =~ /^(.*)\.[cly]$/ && -f "$relative_dir/$file")
5409         {
5410             $de_ansi_files{$1} = ''
5411         }
5412     }
5414     if (option 'ansi2knr' && keys %de_ansi_files)
5415     {
5416         # Make all _.c files depend on their corresponding .c files.
5417         my @objects;
5418         foreach my $base (sort keys %de_ansi_files)
5419         {
5420             # Each _.c file must depend on ansi2knr; otherwise it
5421             # might be used in a parallel build before it is built.
5422             # We need to support files in the srcdir and in the build
5423             # dir (because these files might be auto-generated.  But
5424             # we can't use $< -- some makes only define $< during a
5425             # suffix rule.
5426             my $ansfile = $de_ansi_files{$base} . $base . '.c';
5427             $output_rules .= ($base . "_.c: $ansfile \$(ANSI2KNR)\n\t"
5428                               . '$(CPP) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) '
5429                               . '`if test -f $(srcdir)/' . $ansfile
5430                               . '; then echo $(srcdir)/' . $ansfile
5431                               . '; else echo ' . $ansfile . '; fi` '
5432                               . "| sed 's/^# \\([0-9]\\)/#line \\1/' "
5433                               . '| $(ANSI2KNR) > $@'
5434                               # If ansi2knr fails then we shouldn't
5435                               # create the _.c file
5436                               . " || rm -f \$\@\n");
5437             push (@objects, $base . '_.$(OBJEXT)');
5438             push (@objects, $base . '_.lo')
5439               if var ('LIBTOOL');
5441             # Explicitly clean the _.c files if they are in a
5442             # subdirectory. (In the current directory they get erased
5443             # by a `rm -f *_.c' rule.)
5444             $clean_files{$base . '_.c'} = MOSTLY_CLEAN
5445               if dirname ($base) ne '.';
5446         }
5448         # Make all _.o (and _.lo) files depend on ansi2knr.
5449         # Use a sneaky little hack to make it print nicely.
5450         &pretty_print_rule ('', '', @objects, ':', '$(ANSI2KNR)');
5451     }
5454 # This is a yacc helper which is called whenever we have decided to
5455 # compile a yacc file.
5456 sub lang_yacc_target_hook
5458     my ($self, $aggregate, $output, $input, %transform) = @_;
5460     my $flag = $aggregate . "_YFLAGS";
5461     my $flagvar = var $flag;
5462     my $YFLAGSvar = var 'YFLAGS';
5463     if (($flagvar && $flagvar->variable_value =~ /$DASH_D_PATTERN/o)
5464         || ($YFLAGSvar && $YFLAGSvar->variable_value =~ /$DASH_D_PATTERN/o))
5465     {
5466         (my $output_base = $output) =~ s/$KNOWN_EXTENSIONS_PATTERN$//;
5467         my $header = $output_base . '.h';
5469         # Found a `-d' that applies to the compilation of this file.
5470         # Add a dependency for the generated header file, and arrange
5471         # for that file to be included in the distribution.
5472         foreach my $cond (Automake::Rule::define (${header}, 'internal',
5473                                                   RULE_AUTOMAKE, TRUE,
5474                                                   INTERNAL))
5475           {
5476             my $condstr = $cond->subst_string;
5477             $output_rules .=
5478               "$condstr${header}: $output\n"
5479               # Recover from removal of $header
5480               . "$condstr\t\@if test ! -f \$@; then \\\n"
5481               . "$condstr\t  rm -f $output; \\\n"
5482               . "$condstr\t  \$(MAKE) \$(AM_MAKEFLAGS) $output; \\\n"
5483               . "$condstr\telse :; fi\n";
5484           }
5485         # Distribute the generated file, unless its .y source was
5486         # listed in a nodist_ variable.  (&handle_source_transform
5487         # will set DIST_SOURCE.)
5488         &push_dist_common ($header)
5489           if $transform{'DIST_SOURCE'};
5491         # If the files are built in the build directory, then we want
5492         # to remove them with `make clean'.  If they are in srcdir
5493         # they shouldn't be touched.  However, we can't determine this
5494         # statically, and the GNU rules say that yacc/lex output files
5495         # should be removed by maintainer-clean.  So that's what we
5496         # do.
5497         $clean_files{$header} = MAINTAINER_CLEAN;
5498     }
5499     # Erase $OUTPUT on `make maintainer-clean' (by GNU standards).
5500     # See the comment above for $HEADER.
5501     $clean_files{$output} = MAINTAINER_CLEAN;
5504 # This is a lex helper which is called whenever we have decided to
5505 # compile a lex file.
5506 sub lang_lex_target_hook
5508     my ($self, $aggregate, $output, $input) = @_;
5509     # If the files are built in the build directory, then we want to
5510     # remove them with `make clean'.  If they are in srcdir they
5511     # shouldn't be touched.  However, we can't determine this
5512     # statically, and the GNU rules say that yacc/lex output files
5513     # should be removed by maintainer-clean.  So that's what we do.
5514     $clean_files{$output} = MAINTAINER_CLEAN;
5517 # This is a helper for both lex and yacc.
5518 sub yacc_lex_finish_helper
5520   return if defined $language_scratch{'lex-yacc-done'};
5521   $language_scratch{'lex-yacc-done'} = 1;
5523   # If there is more than one distinct yacc (resp lex) source file
5524   # in a given directory, then the `ylwrap' program is required to
5525   # allow parallel builds to work correctly.  FIXME: for now, no
5526   # line number.
5527   require_conf_file ($configure_ac, FOREIGN, 'ylwrap');
5528   &define_variable ('YLWRAP', "$am_config_aux_dir/ylwrap", INTERNAL);
5531 sub lang_yacc_finish
5533   return if defined $language_scratch{'yacc-done'};
5534   $language_scratch{'yacc-done'} = 1;
5536   reject_var 'YACCFLAGS', "`YACCFLAGS' obsolete; use `YFLAGS' instead";
5538   &yacc_lex_finish_helper
5539     if count_files_for_language ('yacc') > 1;
5543 sub lang_lex_finish
5545   return if defined $language_scratch{'lex-done'};
5546   $language_scratch{'lex-done'} = 1;
5548   &yacc_lex_finish_helper
5549     if count_files_for_language ('lex') > 1;
5553 # Given a hash table of linker names, pick the name that has the most
5554 # precedence.  This is lame, but something has to have global
5555 # knowledge in order to eliminate the conflict.  Add more linkers as
5556 # required.
5557 sub resolve_linker
5559     my (%linkers) = @_;
5561     foreach my $l (qw(GCJLINK CXXLINK F77LINK FCLINK OBJCLINK))
5562     {
5563         return $l if defined $linkers{$l};
5564     }
5565     return 'LINK';
5568 # Called to indicate that an extension was used.
5569 sub saw_extension
5571     my ($ext) = @_;
5572     if (! defined $extension_seen{$ext})
5573     {
5574         $extension_seen{$ext} = 1;
5575     }
5576     else
5577     {
5578         ++$extension_seen{$ext};
5579     }
5582 # Return the number of files seen for a given language.  Knows about
5583 # special cases we care about.  FIXME: this is hideous.  We need
5584 # something that involves real language objects.  For instance yacc
5585 # and yaccxx could both derive from a common yacc class which would
5586 # know about the strange ylwrap requirement.  (Or better yet we could
5587 # just not support legacy yacc!)
5588 sub count_files_for_language
5590     my ($name) = @_;
5592     my @names;
5593     if ($name eq 'yacc' || $name eq 'yaccxx')
5594     {
5595         @names = ('yacc', 'yaccxx');
5596     }
5597     elsif ($name eq 'lex' || $name eq 'lexxx')
5598     {
5599         @names = ('lex', 'lexxx');
5600     }
5601     else
5602     {
5603         @names = ($name);
5604     }
5606     my $r = 0;
5607     foreach $name (@names)
5608     {
5609         my $lang = $languages{$name};
5610         foreach my $ext (@{$lang->extensions})
5611         {
5612             $r += $extension_seen{$ext}
5613                 if defined $extension_seen{$ext};
5614         }
5615     }
5617     return $r
5620 # Called to ask whether source files have been seen . If HEADERS is 1,
5621 # headers can be included.
5622 sub saw_sources_p
5624     my ($headers) = @_;
5626     # count all the sources
5627     my $count = 0;
5628     foreach my $val (values %extension_seen)
5629     {
5630         $count += $val;
5631     }
5633     if (!$headers)
5634     {
5635         $count -= count_files_for_language ('header');
5636     }
5638     return $count > 0;
5642 # register_language (%ATTRIBUTE)
5643 # ------------------------------
5644 # Register a single language.
5645 # Each %ATTRIBUTE is of the form ATTRIBUTE => VALUE.
5646 sub register_language (%)
5648   my (%option) = @_;
5650   # Set the defaults.
5651   $option{'ansi'} = 0
5652     unless defined $option{'ansi'};
5653   $option{'autodep'} = 'no'
5654     unless defined $option{'autodep'};
5655   $option{'linker'} = ''
5656     unless defined $option{'linker'};
5657   $option{'flags'} = []
5658     unless defined $option{'flags'};
5659   $option{'output_extensions'} = sub { return ( '.$(OBJEXT)', '.lo' ) }
5660     unless defined $option{'output_extensions'};
5661   $option{'nodist_specific'} = 0
5662     unless defined $option{'nodist_specific'};
5664   my $lang = new Language (%option);
5666   # Fill indexes.
5667   $extension_map{$_} = $lang->name foreach @{$lang->extensions};
5668   $languages{$lang->name} = $lang;
5669   my $link = $lang->linker;
5670   if ($link)
5671     {
5672       if (exists $link_languages{$link})
5673         {
5674           prog_error ("`$link' has different definitions in "
5675                       . $lang->name . " and " . $link_languages{$link}->name)
5676             if $lang->link ne $link_languages{$link}->link;
5677         }
5678       else
5679         {
5680           $link_languages{$link} = $lang;
5681         }
5682     }
5684   # Update the pattern of known extensions.
5685   accept_extensions (@{$lang->extensions});
5687   # Upate the $suffix_rule map.
5688   foreach my $suffix (@{$lang->extensions})
5689     {
5690       foreach my $dest (&{$lang->output_extensions} ($suffix))
5691         {
5692           register_suffix_rule (INTERNAL, $suffix, $dest);
5693         }
5694     }
5697 # derive_suffix ($EXT, $OBJ)
5698 # --------------------------
5699 # This function is used to find a path from a user-specified suffix $EXT
5700 # to $OBJ or to some other suffix we recognize internally, e.g. `cc'.
5701 sub derive_suffix ($$)
5703   my ($source_ext, $obj) = @_;
5705   while (! $extension_map{$source_ext}
5706          && $source_ext ne $obj
5707          && exists $suffix_rules->{$source_ext}
5708          && exists $suffix_rules->{$source_ext}{$obj})
5709     {
5710       $source_ext = $suffix_rules->{$source_ext}{$obj}[0];
5711     }
5713   return $source_ext;
5717 ################################################################
5719 # Pretty-print something and append to output_rules.
5720 sub pretty_print_rule
5722     $output_rules .= &makefile_wrap (@_);
5726 ################################################################
5729 ## -------------------------------- ##
5730 ## Handling the conditional stack.  ##
5731 ## -------------------------------- ##
5734 # $STRING
5735 # make_conditional_string ($NEGATE, $COND)
5736 # ----------------------------------------
5737 sub make_conditional_string ($$)
5739   my ($negate, $cond) = @_;
5740   $cond = "${cond}_TRUE"
5741     unless $cond =~ /^TRUE|FALSE$/;
5742   $cond = Automake::Condition::conditional_negate ($cond)
5743     if $negate;
5744   return $cond;
5748 # $COND
5749 # cond_stack_if ($NEGATE, $COND, $WHERE)
5750 # --------------------------------------
5751 sub cond_stack_if ($$$)
5753   my ($negate, $cond, $where) = @_;
5755   error $where, "$cond does not appear in AM_CONDITIONAL"
5756     if ! $configure_cond{$cond} && $cond !~ /^TRUE|FALSE$/;
5758   push (@cond_stack, make_conditional_string ($negate, $cond));
5760   return new Automake::Condition (@cond_stack);
5764 # $COND
5765 # cond_stack_else ($NEGATE, $COND, $WHERE)
5766 # ----------------------------------------
5767 sub cond_stack_else ($$$)
5769   my ($negate, $cond, $where) = @_;
5771   if (! @cond_stack)
5772     {
5773       error $where, "else without if";
5774       return FALSE;
5775     }
5777   $cond_stack[$#cond_stack] =
5778     Automake::Condition::conditional_negate ($cond_stack[$#cond_stack]);
5780   # If $COND is given, check against it.
5781   if (defined $cond)
5782     {
5783       $cond = make_conditional_string ($negate, $cond);
5785       error ($where, "else reminder ($negate$cond) incompatible with "
5786              . "current conditional: $cond_stack[$#cond_stack]")
5787         if $cond_stack[$#cond_stack] ne $cond;
5788     }
5790   return new Automake::Condition (@cond_stack);
5794 # $COND
5795 # cond_stack_endif ($NEGATE, $COND, $WHERE)
5796 # -----------------------------------------
5797 sub cond_stack_endif ($$$)
5799   my ($negate, $cond, $where) = @_;
5800   my $old_cond;
5802   if (! @cond_stack)
5803     {
5804       error $where, "endif without if";
5805       return TRUE;
5806     }
5808   # If $COND is given, check against it.
5809   if (defined $cond)
5810     {
5811       $cond = make_conditional_string ($negate, $cond);
5813       error ($where, "endif reminder ($negate$cond) incompatible with "
5814              . "current conditional: $cond_stack[$#cond_stack]")
5815         if $cond_stack[$#cond_stack] ne $cond;
5816     }
5818   pop @cond_stack;
5820   return new Automake::Condition (@cond_stack);
5827 ## ------------------------ ##
5828 ## Handling the variables.  ##
5829 ## ------------------------ ##
5832 # &define_pretty_variable ($VAR, $COND, $WHERE, @VALUE)
5833 # -----------------------------------------------------
5834 # Like define_variable, but the value is a list, and the variable may
5835 # be defined conditionally.  The second argument is the Condition
5836 # under which the value should be defined; this should be the empty
5837 # string to define the variable unconditionally.  The third argument
5838 # is a list holding the values to use for the variable.  The value is
5839 # pretty printed in the output file.
5840 sub define_pretty_variable ($$$@)
5842     my ($var, $cond, $where, @value) = @_;
5844     if (! vardef ($var, $cond))
5845     {
5846         Automake::Variable::define ($var, VAR_AUTOMAKE, '', $cond, "@value",
5847                                     '', $where, VAR_PRETTY);
5848         rvar ($var)->rdef ($cond)->set_seen;
5849     }
5853 # define_variable ($VAR, $VALUE, $WHERE)
5854 # --------------------------------------
5855 # Define a new Automake Makefile variable VAR to VALUE, but only if
5856 # not already defined.
5857 sub define_variable ($$$)
5859     my ($var, $value, $where) = @_;
5860     define_pretty_variable ($var, TRUE, $where, $value);
5864 # define_files_variable ($VAR, \@BASENAME, $EXTENSION, $WHERE)
5865 # -----------------------------------------------------------
5866 # Define the $VAR which content is the list of file names composed of
5867 # a @BASENAME and the $EXTENSION.
5868 sub define_files_variable ($\@$$)
5870   my ($var, $basename, $extension, $where) = @_;
5871   define_variable ($var,
5872                    join (' ', map { "$_.$extension" } @$basename),
5873                    $where);
5877 # Like define_variable, but define a variable to be the configure
5878 # substitution by the same name.
5879 sub define_configure_variable ($)
5881   my ($var) = @_;
5883   my $pretty = VAR_ASIS;
5884   my $owner = VAR_CONFIGURE;
5886   # Some variables we do not want to output.  For instance it
5887   # would be a bad idea to output `U = @U@` when `@U@` can be
5888   # substituted as `\`.
5889   $pretty = VAR_SILENT if exists $ignored_configure_vars{$var};
5891   # ANSI2KNR is a variable that Automake wants to redefine, so
5892   # it must be owned by Automake.  (It is also used as a proof
5893   # that AM_C_PROTOTYPES has been run, that's why we do not simply
5894   # omit the AC_SUBST.)
5895   $owner = VAR_AUTOMAKE if $var eq 'ANSI2KNR';
5897   Automake::Variable::define ($var, $owner, '', TRUE, subst $var,
5898                               '', $configure_vars{$var}, $pretty);
5902 # define_compiler_variable ($LANG)
5903 # --------------------------------
5904 # Define a compiler variable.  We also handle defining the `LT'
5905 # version of the command when using libtool.
5906 sub define_compiler_variable ($)
5908     my ($lang) = @_;
5910     my ($var, $value) = ($lang->compiler, $lang->compile);
5911     my $libtool_tag = '';
5912     $libtool_tag = '--tag=' . $lang->libtool_tag . ' '
5913       if $lang->libtool_tag && exists $libtool_tags{$lang->libtool_tag};
5914     &define_variable ($var, $value, INTERNAL);
5915     &define_variable ("LT$var",
5916                       "\$(LIBTOOL) $libtool_tag\$(AM_LIBTOOLFLAGS) "
5917                       . "\$(LIBTOOLFLAGS) --mode=compile $value",
5918                       INTERNAL)
5919       if var ('LIBTOOL');
5923 # define_linker_variable ($LANG)
5924 # ------------------------------
5925 # Define linker variables.
5926 sub define_linker_variable ($)
5928     my ($lang) = @_;
5930     my $libtool_tag = '';
5931     $libtool_tag = '--tag=' . $lang->libtool_tag . ' '
5932       if $lang->libtool_tag && exists $libtool_tags{$lang->libtool_tag};
5933     # CCLD = $(CC).
5934     &define_variable ($lang->lder, $lang->ld, INTERNAL);
5935     # CCLINK = $(CCLD) blah blah...
5936     &define_variable ($lang->linker,
5937                       ((var ('LIBTOOL') ?
5938                         "\$(LIBTOOL) $libtool_tag\$(AM_LIBTOOLFLAGS) "
5939                         . "\$(LIBTOOLFLAGS) --mode=link " : '')
5940                        . $lang->link),
5941                       INTERNAL);
5944 sub define_per_target_linker_variable ($$)
5946   my ($linker, $target) = @_;
5948   # If the user wrote a custom link command, we don't define ours.
5949   return "${target}_LINK"
5950     if set_seen "${target}_LINK";
5952   my $xlink = $linker ? $linker : 'LINK';
5954   my $lang = $link_languages{$xlink};
5955   prog_error "Unknown language for linker variable `$xlink'"
5956     unless $lang;
5958   my $link_command = $lang->link;
5959   if (var 'LIBTOOL')
5960     {
5961       my $libtool_tag = '';
5962       $libtool_tag = '--tag=' . $lang->libtool_tag . ' '
5963         if $lang->libtool_tag && exists $libtool_tags{$lang->libtool_tag};
5965       $link_command =
5966         "\$(LIBTOOL) $libtool_tag\$(AM_LIBTOOLFLAGS) \$(LIBTOOLFLAGS) "
5967         . "--mode=link " . $link_command;
5968     }
5970   # Rewrite each occurrence of `AM_$flag' in the link
5971   # command into `${derived}_$flag' if it exists.
5972   my $orig_command = $link_command;
5973   my @flags = (@{$lang->flags}, 'LDFLAGS');
5974   push @flags, 'LIBTOOLFLAGS' if var 'LIBTOOL';
5975   for my $flag (@flags)
5976     {
5977       my $val = "${target}_$flag";
5978       $link_command =~ s/\(AM_$flag\)/\($val\)/
5979         if set_seen ($val);
5980     }
5982   # If the computed command is the same as the generic command, use
5983   # the command linker variable.
5984   return $lang->linker
5985     if $link_command eq $orig_command;
5987   &define_variable ("${target}_LINK", $link_command, INTERNAL);
5988   return "${target}_LINK";
5991 ################################################################
5993 # &check_trailing_slash ($WHERE, $LINE)
5994 # --------------------------------------
5995 # Return 1 iff $LINE ends with a slash.
5996 # Might modify $LINE.
5997 sub check_trailing_slash ($\$)
5999   my ($where, $line) = @_;
6001   # Ignore `##' lines.
6002   return 0 if $$line =~ /$IGNORE_PATTERN/o;
6004   # Catch and fix a common error.
6005   msg "syntax", $where, "whitespace following trailing backslash"
6006     if $$line =~ s/\\\s+\n$/\\\n/;
6008   return $$line =~ /\\$/;
6012 # &read_am_file ($AMFILE, $WHERE)
6013 # -------------------------------
6014 # Read Makefile.am and set up %contents.  Simultaneously copy lines
6015 # from Makefile.am into $output_trailer, or define variables as
6016 # appropriate.  NOTE we put rules in the trailer section.  We want
6017 # user rules to come after our generated stuff.
6018 sub read_am_file ($$)
6020     my ($amfile, $where) = @_;
6022     my $am_file = new Automake::XFile ("< $amfile");
6023     verb "reading $amfile";
6025     # Keep track of the youngest output dependency.
6026     my $mtime = mtime $amfile;
6027     $output_deps_greatest_timestamp = $mtime
6028       if $mtime > $output_deps_greatest_timestamp;
6030     my $spacing = '';
6031     my $comment = '';
6032     my $blank = 0;
6033     my $saw_bk = 0;
6034     my $var_look = VAR_ASIS;
6036     use constant IN_VAR_DEF => 0;
6037     use constant IN_RULE_DEF => 1;
6038     use constant IN_COMMENT => 2;
6039     my $prev_state = IN_RULE_DEF;
6041     while ($_ = $am_file->getline)
6042     {
6043         $where->set ("$amfile:$.");
6044         if (/$IGNORE_PATTERN/o)
6045         {
6046             # Merely delete comments beginning with two hashes.
6047         }
6048         elsif (/$WHITE_PATTERN/o)
6049         {
6050             error $where, "blank line following trailing backslash"
6051               if $saw_bk;
6052             # Stick a single white line before the incoming macro or rule.
6053             $spacing = "\n";
6054             $blank = 1;
6055             # Flush all comments seen so far.
6056             if ($comment ne '')
6057             {
6058                 $output_vars .= $comment;
6059                 $comment = '';
6060             }
6061         }
6062         elsif (/$COMMENT_PATTERN/o)
6063         {
6064             # Stick comments before the incoming macro or rule.  Make
6065             # sure a blank line precedes the first block of comments.
6066             $spacing = "\n" unless $blank;
6067             $blank = 1;
6068             $comment .= $spacing . $_;
6069             $spacing = '';
6070             $prev_state = IN_COMMENT;
6071         }
6072         else
6073         {
6074             last;
6075         }
6076         $saw_bk = check_trailing_slash ($where, $_);
6077     }
6079     # We save the conditional stack on entry, and then check to make
6080     # sure it is the same on exit.  This lets us conditionally include
6081     # other files.
6082     my @saved_cond_stack = @cond_stack;
6083     my $cond = new Automake::Condition (@cond_stack);
6085     my $last_var_name = '';
6086     my $last_var_type = '';
6087     my $last_var_value = '';
6088     my $last_where;
6089     # FIXME: shouldn't use $_ in this loop; it is too big.
6090     while ($_)
6091     {
6092         $where->set ("$amfile:$.");
6094         # Make sure the line is \n-terminated.
6095         chomp;
6096         $_ .= "\n";
6098         # Don't look at MAINTAINER_MODE_TRUE here.  That shouldn't be
6099         # used by users.  @MAINT@ is an anachronism now.
6100         $_ =~ s/\@MAINT\@//g
6101             unless $seen_maint_mode;
6103         my $new_saw_bk = check_trailing_slash ($where, $_);
6105         if (/$IGNORE_PATTERN/o)
6106         {
6107             # Merely delete comments beginning with two hashes.
6109             # Keep any backslash from the previous line.
6110             $new_saw_bk = $saw_bk;
6111         }
6112         elsif (/$WHITE_PATTERN/o)
6113         {
6114             # Stick a single white line before the incoming macro or rule.
6115             $spacing = "\n";
6116             error $where, "blank line following trailing backslash"
6117               if $saw_bk;
6118         }
6119         elsif (/$COMMENT_PATTERN/o)
6120         {
6121             error $where, "comment following trailing backslash"
6122               if $saw_bk && $comment eq '';
6124             # Stick comments before the incoming macro or rule.
6125             $comment .= $spacing . $_;
6126             $spacing = '';
6127             $prev_state = IN_COMMENT;
6128         }
6129         elsif ($saw_bk)
6130         {
6131             if ($prev_state == IN_RULE_DEF)
6132             {
6133               my $cond = new Automake::Condition @cond_stack;
6134               $output_trailer .= $cond->subst_string;
6135               $output_trailer .= $_;
6136             }
6137             elsif ($prev_state == IN_COMMENT)
6138             {
6139                 # If the line doesn't start with a `#', add it.
6140                 # We do this because a continued comment like
6141                 #   # A = foo \
6142                 #         bar \
6143                 #         baz
6144                 # is not portable.  BSD make doesn't honor
6145                 # escaped newlines in comments.
6146                 s/^#?/#/;
6147                 $comment .= $spacing . $_;
6148             }
6149             else # $prev_state == IN_VAR_DEF
6150             {
6151               $last_var_value .= ' '
6152                 unless $last_var_value =~ /\s$/;
6153               $last_var_value .= $_;
6155               if (!/\\$/)
6156                 {
6157                   Automake::Variable::define ($last_var_name, VAR_MAKEFILE,
6158                                               $last_var_type, $cond,
6159                                               $last_var_value, $comment,
6160                                               $last_where, VAR_ASIS)
6161                     if $cond != FALSE;
6162                   $comment = $spacing = '';
6163                 }
6164             }
6165         }
6167         elsif (/$IF_PATTERN/o)
6168           {
6169             $cond = cond_stack_if ($1, $2, $where);
6170           }
6171         elsif (/$ELSE_PATTERN/o)
6172           {
6173             $cond = cond_stack_else ($1, $2, $where);
6174           }
6175         elsif (/$ENDIF_PATTERN/o)
6176           {
6177             $cond = cond_stack_endif ($1, $2, $where);
6178           }
6180         elsif (/$RULE_PATTERN/o)
6181         {
6182             # Found a rule.
6183             $prev_state = IN_RULE_DEF;
6185             # For now we have to output all definitions of user rules
6186             # and can't diagnose duplicates (see the comment in
6187             # Automake::Rule::define). So we go on and ignore the return value.
6188             Automake::Rule::define ($1, $amfile, RULE_USER, $cond, $where);
6190             check_variable_expansions ($_, $where);
6192             $output_trailer .= $comment . $spacing;
6193             my $cond = new Automake::Condition @cond_stack;
6194             $output_trailer .= $cond->subst_string;
6195             $output_trailer .= $_;
6196             $comment = $spacing = '';
6197         }
6198         elsif (/$ASSIGNMENT_PATTERN/o)
6199         {
6200             # Found a macro definition.
6201             $prev_state = IN_VAR_DEF;
6202             $last_var_name = $1;
6203             $last_var_type = $2;
6204             $last_var_value = $3;
6205             $last_where = $where->clone;
6206             if ($3 ne '' && substr ($3, -1) eq "\\")
6207               {
6208                 # We preserve the `\' because otherwise the long lines
6209                 # that are generated will be truncated by broken
6210                 # `sed's.
6211                 $last_var_value = $3 . "\n";
6212               }
6213             # Normally we try to output variable definitions in the
6214             # same format they were input.  However, POSIX compliant
6215             # systems are not required to support lines longer than
6216             # 2048 bytes (most notably, some sed implementation are
6217             # limited to 4000 bytes, and sed is used by config.status
6218             # to rewrite Makefile.in into Makefile).  Moreover nobody
6219             # would really write such long lines by hand since it is
6220             # hardly maintainable.  So if a line is longer that 1000
6221             # bytes (an arbitrary limit), assume it has been
6222             # automatically generated by some tools, and flatten the
6223             # variable definition.  Otherwise, keep the variable as it
6224             # as been input.
6225             $var_look = VAR_PRETTY if length ($last_var_value) >= 1000;
6227             if (!/\\$/)
6228               {
6229                 Automake::Variable::define ($last_var_name, VAR_MAKEFILE,
6230                                             $last_var_type, $cond,
6231                                             $last_var_value, $comment,
6232                                             $last_where, $var_look)
6233                   if $cond != FALSE;
6234                 $comment = $spacing = '';
6235                 $var_look = VAR_ASIS;
6236               }
6237         }
6238         elsif (/$INCLUDE_PATTERN/o)
6239         {
6240             my $path = $1;
6242             if ($path =~ s/^\$\(top_srcdir\)\///)
6243               {
6244                 push (@include_stack, "\$\(top_srcdir\)/$path");
6245                 # Distribute any included file.
6247                 # Always use the $(top_srcdir) prefix in DIST_COMMON,
6248                 # otherwise OSF make will implicitly copy the included
6249                 # file in the build tree during `make distdir' to satisfy
6250                 # the dependency.
6251                 # (subdircond2.test and subdircond3.test will fail.)
6252                 push_dist_common ("\$\(top_srcdir\)/$path");
6253               }
6254             else
6255               {
6256                 $path =~ s/\$\(srcdir\)\///;
6257                 push (@include_stack, "\$\(srcdir\)/$path");
6258                 # Always use the $(srcdir) prefix in DIST_COMMON,
6259                 # otherwise OSF make will implicitly copy the included
6260                 # file in the build tree during `make distdir' to satisfy
6261                 # the dependency.
6262                 # (subdircond2.test and subdircond3.test will fail.)
6263                 push_dist_common ("\$\(srcdir\)/$path");
6264                 $path = $relative_dir . "/" . $path if $relative_dir ne '.';
6265               }
6266             $where->push_context ("`$path' included from here");
6267             &read_am_file ($path, $where);
6268             $where->pop_context;
6269         }
6270         else
6271         {
6272             # This isn't an error; it is probably a continued rule.
6273             # In fact, this is what we assume.
6274             $prev_state = IN_RULE_DEF;
6275             check_variable_expansions ($_, $where);
6276             $output_trailer .= $comment . $spacing;
6277             my $cond = new Automake::Condition @cond_stack;
6278             $output_trailer .= $cond->subst_string;
6279             $output_trailer .= $_;
6280             $comment = $spacing = '';
6281             error $where, "`#' comment at start of rule is unportable"
6282               if $_ =~ /^\t\s*\#/;
6283         }
6285         $saw_bk = $new_saw_bk;
6286         $_ = $am_file->getline;
6287     }
6289     $output_trailer .= $comment;
6291     error ($where, "trailing backslash on last line")
6292       if $saw_bk;
6294     error ($where, (@cond_stack ? "unterminated conditionals: @cond_stack"
6295                     : "too many conditionals closed in include file"))
6296       if "@saved_cond_stack" ne "@cond_stack";
6300 # define_standard_variables ()
6301 # ----------------------------
6302 # A helper for read_main_am_file which initializes configure variables
6303 # and variables from header-vars.am.
6304 sub define_standard_variables
6306   my $saved_output_vars = $output_vars;
6307   my ($comments, undef, $rules) =
6308     file_contents_internal (1, "$libdir/am/header-vars.am",
6309                             new Automake::Location);
6311   foreach my $var (sort keys %configure_vars)
6312     {
6313       &define_configure_variable ($var);
6314     }
6316   $output_vars .= $comments . $rules;
6319 # Read main am file.
6320 sub read_main_am_file
6322     my ($amfile) = @_;
6324     # This supports the strange variable tricks we are about to play.
6325     prog_error (macros_dump () . "variable defined before read_main_am_file")
6326       if (scalar (variables) > 0);
6328     # Generate copyright header for generated Makefile.in.
6329     # We do discard the output of predefined variables, handled below.
6330     $output_vars = ("# $in_file_name generated by automake "
6331                    . $VERSION . " from $am_file_name.\n");
6332     $output_vars .= '# ' . subst ('configure_input') . "\n";
6333     $output_vars .= $gen_copyright;
6335     # We want to predefine as many variables as possible.  This lets
6336     # the user set them with `+=' in Makefile.am.
6337     &define_standard_variables;
6339     # Read user file, which might override some of our values.
6340     &read_am_file ($amfile, new Automake::Location);
6345 ################################################################
6347 # $FLATTENED
6348 # &flatten ($STRING)
6349 # ------------------
6350 # Flatten the $STRING and return the result.
6351 sub flatten
6353   $_ = shift;
6355   s/\\\n//somg;
6356   s/\s+/ /g;
6357   s/^ //;
6358   s/ $//;
6360   return $_;
6363 # transform($TOKEN, \%PAIRS)
6364 # ==========================
6365 # If ($TOKEN, $VAL) is in %PAIRS:
6366 #   - replaces %$TOKEN% with $VAL,
6367 #   - enables/disables ?$TOKEN? and ?!$TOKEN?,
6368 #   - replaces %?$TOKEN% with TRUE or FALSE.
6369 sub transform($$)
6371   my ($token, $transform) = @_;
6373   if (substr ($token, 0, 1) eq '%')
6374     {
6375       my $cond = (substr ($token, 1, 1) eq '?') ? 1 : 0;
6376       $token = substr ($token, 1 + $cond, -1);
6377       my $val = $transform->{$token};
6378       prog_error "Unknown %token% `$token'" unless defined $val;
6379       if ($cond)
6380         {
6381           return $val ? 'TRUE' : 'FALSE';
6382         }
6383       else
6384         {
6385           return $val;
6386         }
6387     }
6388   # Now $token is '?xxx?' or '?!xxx?'.
6389   my $neg = (substr ($token, 1, 1) eq '!') ? 1 : 0;
6390   $token = substr ($token, 1 + $neg, -1);
6391   my $val = $transform->{$token};
6392   prog_error "Unknown ?token? `$token' (neg = $neg)" unless defined $val;
6393   return (!!$val == $neg) ? '##%' : '';
6396 # @PARAGRAPHS
6397 # &make_paragraphs ($MAKEFILE, [%TRANSFORM])
6398 # ------------------------------------------
6399 # Load a $MAKEFILE, apply the %TRANSFORM, and return it as a list of
6400 # paragraphs.
6401 sub make_paragraphs ($%)
6403   my ($file, %transform) = @_;
6405   # Complete %transform with global options.
6406   # Note that %transform goes last, so it overrides global options.
6407   %transform = ('CYGNUS'      => !! option 'cygnus',
6408                  'MAINTAINER-MODE'
6409                  => $seen_maint_mode ? subst ('MAINTAINER_MODE_TRUE') : '',
6411                  'BZIP2'       => !! option 'dist-bzip2',
6412                  'COMPRESS'    => !! option 'dist-tarZ',
6413                  'GZIP'        =>  ! option 'no-dist-gzip',
6414                  'SHAR'        => !! option 'dist-shar',
6415                  'ZIP'         => !! option 'dist-zip',
6417                  'INSTALL-INFO' =>  ! option 'no-installinfo',
6418                  'INSTALL-MAN'  =>  ! option 'no-installman',
6419                  'CK-NEWS'      => !! option 'check-news',
6421                  'SUBDIRS'      => !! var ('SUBDIRS'),
6422                  'TOPDIR_P'     => $relative_dir eq '.',
6424                  'BUILD'    => ($seen_canonical >= AC_CANONICAL_BUILD),
6425                  'HOST'     => ($seen_canonical >= AC_CANONICAL_HOST),
6426                  'TARGET'   => ($seen_canonical >= AC_CANONICAL_TARGET),
6428                  'LIBTOOL'      => !! var ('LIBTOOL'),
6429                  'NONLIBTOOL'   => 1,
6430                  'FIRST'        => ! $transformed_files{$file},
6431                 %transform);
6433   $transformed_files{$file} = 1;
6434   $_ = $am_file_cache{$file};
6436   if (! defined $_)
6437     {
6438       verb "reading $file";
6439       # Swallow the whole file.
6440       my $fc_file = new Automake::XFile "< $file";
6441       my $saved_dollar_slash = $/;
6442       undef $/;
6443       $_ = $fc_file->getline;
6444       $/ = $saved_dollar_slash;
6445       $fc_file->close;
6447       # Remove ##-comments.
6448       # Besides we don't need more than two consecutive new-lines.
6449       s/(?:$IGNORE_PATTERN|(?<=\n\n)\n+)//gom;
6451       $am_file_cache{$file} = $_;
6452     }
6454   # Substitute Automake template tokens.
6455   s/(?:%\??[\w\-]+%|\?!?[\w\-]+\?)/transform($&, \%transform)/ge;
6456   # transform() may have added some ##%-comments to strip.
6457   # (we use `##%' instead of `##' so we can distinguish ##%##%##% from
6458   # ####### and do not remove the latter.)
6459   s/^[ \t]*(?:##%)+.*\n//gm;
6461   # Split at unescaped new lines.
6462   my @lines = split (/(?<!\\)\n/, $_);
6463   my @res;
6465   while (defined ($_ = shift @lines))
6466     {
6467       my $paragraph = $_;
6468       # If we are a rule, eat as long as we start with a tab.
6469       if (/$RULE_PATTERN/smo)
6470         {
6471           while (defined ($_ = shift @lines) && $_ =~ /^\t/)
6472             {
6473               $paragraph .= "\n$_";
6474             }
6475           unshift (@lines, $_);
6476         }
6478       # If we are a comments, eat as much comments as you can.
6479       elsif (/$COMMENT_PATTERN/smo)
6480         {
6481           while (defined ($_ = shift @lines)
6482                  && $_ =~ /$COMMENT_PATTERN/smo)
6483             {
6484               $paragraph .= "\n$_";
6485             }
6486           unshift (@lines, $_);
6487         }
6489       push @res, $paragraph;
6490     }
6492   return @res;
6497 # ($COMMENT, $VARIABLES, $RULES)
6498 # &file_contents_internal ($IS_AM, $FILE, $WHERE, [%TRANSFORM])
6499 # -------------------------------------------------------------
6500 # Return contents of a file from $libdir/am, automatically skipping
6501 # macros or rules which are already known. $IS_AM iff the caller is
6502 # reading an Automake file (as opposed to the user's Makefile.am).
6503 sub file_contents_internal ($$$%)
6505     my ($is_am, $file, $where, %transform) = @_;
6507     $where->set ($file);
6509     my $result_vars = '';
6510     my $result_rules = '';
6511     my $comment = '';
6512     my $spacing = '';
6514     # The following flags are used to track rules spanning across
6515     # multiple paragraphs.
6516     my $is_rule = 0;            # 1 if we are processing a rule.
6517     my $discard_rule = 0;       # 1 if the current rule should not be output.
6519     # We save the conditional stack on entry, and then check to make
6520     # sure it is the same on exit.  This lets us conditionally include
6521     # other files.
6522     my @saved_cond_stack = @cond_stack;
6523     my $cond = new Automake::Condition (@cond_stack);
6525     foreach (make_paragraphs ($file, %transform))
6526     {
6527         # FIXME: no line number available.
6528         $where->set ($file);
6530         # Sanity checks.
6531         error $where, "blank line following trailing backslash:\n$_"
6532           if /\\$/;
6533         error $where, "comment following trailing backslash:\n$_"
6534           if /\\#/;
6536         if (/^$/)
6537         {
6538             $is_rule = 0;
6539             # Stick empty line before the incoming macro or rule.
6540             $spacing = "\n";
6541         }
6542         elsif (/$COMMENT_PATTERN/mso)
6543         {
6544             $is_rule = 0;
6545             # Stick comments before the incoming macro or rule.
6546             $comment = "$_\n";
6547         }
6549         # Handle inclusion of other files.
6550         elsif (/$INCLUDE_PATTERN/o)
6551         {
6552             if ($cond != FALSE)
6553               {
6554                 my $file = ($is_am ? "$libdir/am/" : '') . $1;
6555                 $where->push_context ("`$file' included from here");
6556                 # N-ary `.=' fails.
6557                 my ($com, $vars, $rules)
6558                   = file_contents_internal ($is_am, $file, $where, %transform);
6559                 $where->pop_context;
6560                 $comment .= $com;
6561                 $result_vars .= $vars;
6562                 $result_rules .= $rules;
6563               }
6564         }
6566         # Handling the conditionals.
6567         elsif (/$IF_PATTERN/o)
6568           {
6569             $cond = cond_stack_if ($1, $2, $file);
6570           }
6571         elsif (/$ELSE_PATTERN/o)
6572           {
6573             $cond = cond_stack_else ($1, $2, $file);
6574           }
6575         elsif (/$ENDIF_PATTERN/o)
6576           {
6577             $cond = cond_stack_endif ($1, $2, $file);
6578           }
6580         # Handling rules.
6581         elsif (/$RULE_PATTERN/mso)
6582         {
6583           $is_rule = 1;
6584           $discard_rule = 0;
6585           # Separate relationship from optional actions: the first
6586           # `new-line tab" not preceded by backslash (continuation
6587           # line).
6588           my $paragraph = $_;
6589           /^(.*?)(?:(?<!\\)\n(\t.*))?$/s;
6590           my ($relationship, $actions) = ($1, $2 || '');
6592           # Separate targets from dependencies: the first colon.
6593           $relationship =~ /^([^:]+\S+) *: *(.*)$/som;
6594           my ($targets, $dependencies) = ($1, $2);
6595           # Remove the escaped new lines.
6596           # I don't know why, but I have to use a tmp $flat_deps.
6597           my $flat_deps = &flatten ($dependencies);
6598           my @deps = split (' ', $flat_deps);
6600           foreach (split (' ' , $targets))
6601             {
6602               # FIXME: 1. We are not robust to people defining several targets
6603               # at once, only some of them being in %dependencies.  The
6604               # actions from the targets in %dependencies are usually generated
6605               # from the content of %actions, but if some targets in $targets
6606               # are not in %dependencies the ELSE branch will output
6607               # a rule for all $targets (i.e. the targets which are both
6608               # in %dependencies and $targets will have two rules).
6610               # FIXME: 2. The logic here is not able to output a
6611               # multi-paragraph rule several time (e.g. for each condition
6612               # it is defined for) because it only knows the first paragraph.
6614               # FIXME: 3. We are not robust to people defining a subset
6615               # of a previously defined "multiple-target" rule.  E.g.
6616               # `foo:' after `foo bar:'.
6618               # Output only if not in FALSE.
6619               if (defined $dependencies{$_} && $cond != FALSE)
6620                 {
6621                   &depend ($_, @deps);
6622                   if ($actions{$_})
6623                     {
6624                       $actions{$_} .= "\n$actions" if $actions;
6625                     }
6626                   else
6627                     {
6628                       $actions{$_} = $actions;
6629                     }
6630                 }
6631               else
6632                 {
6633                   # Free-lance dependency.  Output the rule for all the
6634                   # targets instead of one by one.
6635                   my @undefined_conds =
6636                     Automake::Rule::define ($targets, $file,
6637                                             $is_am ? RULE_AUTOMAKE : RULE_USER,
6638                                             $cond, $where);
6639                   for my $undefined_cond (@undefined_conds)
6640                     {
6641                       my $condparagraph = $paragraph;
6642                       $condparagraph =~ s/^/$undefined_cond->subst_string/gme;
6643                       $result_rules .= "$spacing$comment$condparagraph\n";
6644                     }
6645                   if (scalar @undefined_conds == 0)
6646                     {
6647                       # Remember to discard next paragraphs
6648                       # if they belong to this rule.
6649                       # (but see also FIXME: #2 above.)
6650                       $discard_rule = 1;
6651                     }
6652                   $comment = $spacing = '';
6653                   last;
6654                 }
6655             }
6656         }
6658         elsif (/$ASSIGNMENT_PATTERN/mso)
6659         {
6660             my ($var, $type, $val) = ($1, $2, $3);
6661             error $where, "variable `$var' with trailing backslash"
6662               if /\\$/;
6664             $is_rule = 0;
6666             Automake::Variable::define ($var,
6667                                         $is_am ? VAR_AUTOMAKE : VAR_MAKEFILE,
6668                                         $type, $cond, $val, $comment, $where,
6669                                         VAR_ASIS)
6670               if $cond != FALSE;
6672             $comment = $spacing = '';
6673         }
6674         else
6675         {
6676             # This isn't an error; it is probably some tokens which
6677             # configure is supposed to replace, such as `@SET-MAKE@',
6678             # or some part of a rule cut by an if/endif.
6679             if (! $cond->false && ! ($is_rule && $discard_rule))
6680               {
6681                 s/^/$cond->subst_string/gme;
6682                 $result_rules .= "$spacing$comment$_\n";
6683               }
6684             $comment = $spacing = '';
6685         }
6686     }
6688     error ($where, @cond_stack ?
6689            "unterminated conditionals: @cond_stack" :
6690            "too many conditionals closed in include file")
6691       if "@saved_cond_stack" ne "@cond_stack";
6693     return ($comment, $result_vars, $result_rules);
6697 # $CONTENTS
6698 # &file_contents ($BASENAME, $WHERE, [%TRANSFORM])
6699 # ------------------------------------------------
6700 # Return contents of a file from $libdir/am, automatically skipping
6701 # macros or rules which are already known.
6702 sub file_contents ($$%)
6704     my ($basename, $where, %transform) = @_;
6705     my ($comments, $variables, $rules) =
6706       file_contents_internal (1, "$libdir/am/$basename.am", $where,
6707                               %transform);
6708     return "$comments$variables$rules";
6712 # @PREFIX
6713 # &am_primary_prefixes ($PRIMARY, $CAN_DIST, @PREFIXES)
6714 # -----------------------------------------------------
6715 # Find all variable prefixes that are used for install directories.  A
6716 # prefix `zar' qualifies iff:
6718 # * `zardir' is a variable.
6719 # * `zar_PRIMARY' is a variable.
6721 # As a side effect, it looks for misspellings.  It is an error to have
6722 # a variable ending in a "reserved" suffix whose prefix is unknown, e.g.
6723 # "bin_PROGRAMS".  However, unusual prefixes are allowed if a variable
6724 # of the same name (with "dir" appended) exists.  For instance, if the
6725 # variable "zardir" is defined, then "zar_PROGRAMS" becomes valid.
6726 # This is to provide a little extra flexibility in those cases which
6727 # need it.
6728 sub am_primary_prefixes ($$@)
6730   my ($primary, $can_dist, @prefixes) = @_;
6732   local $_;
6733   my %valid = map { $_ => 0 } @prefixes;
6734   $valid{'EXTRA'} = 0;
6735   foreach my $var (variables $primary)
6736     {
6737       # Automake is allowed to define variables that look like primaries
6738       # but which aren't.  E.g. INSTALL_sh_DATA.
6739       # Autoconf can also define variables like INSTALL_DATA, so
6740       # ignore all configure variables (at least those which are not
6741       # redefined in Makefile.am).
6742       # FIXME: We should make sure that these variables are not
6743       # conditionally defined (or else adjust the condition below).
6744       my $def = $var->def (TRUE);
6745       next if $def && $def->owner != VAR_MAKEFILE;
6747       my $varname = $var->name;
6749       if ($varname =~ /^(nobase_)?(dist_|nodist_)?(.*)_[[:alnum:]]+$/)
6750         {
6751           my ($base, $dist, $X) = ($1 || '', $2 || '', $3 || '');
6752           if ($dist ne '' && ! $can_dist)
6753             {
6754               err_var ($var,
6755                        "invalid variable `$varname': `dist' is forbidden");
6756             }
6757           # Standard directories must be explicitly allowed.
6758           elsif (! defined $valid{$X} && exists $standard_prefix{$X})
6759             {
6760               err_var ($var,
6761                        "`${X}dir' is not a legitimate directory " .
6762                        "for `$primary'");
6763             }
6764           # A not explicitly valid directory is allowed if Xdir is defined.
6765           elsif (! defined $valid{$X} &&
6766                  $var->requires_variables ("`$varname' is used", "${X}dir"))
6767             {
6768               # Nothing to do.  Any error message has been output
6769               # by $var->requires_variables.
6770             }
6771           else
6772             {
6773               # Ensure all extended prefixes are actually used.
6774               $valid{"$base$dist$X"} = 1;
6775             }
6776         }
6777       else
6778         {
6779           prog_error "unexpected variable name: $varname";
6780         }
6781     }
6783   # Return only those which are actually defined.
6784   return sort grep { var ($_ . '_' . $primary) } keys %valid;
6788 # Handle `where_HOW' variable magic.  Does all lookups, generates
6789 # install code, and possibly generates code to define the primary
6790 # variable.  The first argument is the name of the .am file to munge,
6791 # the second argument is the primary variable (e.g. HEADERS), and all
6792 # subsequent arguments are possible installation locations.
6794 # Returns list of [$location, $value] pairs, where
6795 # $value's are the values in all where_HOW variable, and $location
6796 # there associated location (the place here their parent variables were
6797 # defined).
6799 # FIXME: this should be rewritten to be cleaner.  It should be broken
6800 # up into multiple functions.
6802 # Usage is: am_install_var (OPTION..., file, HOW, where...)
6803 sub am_install_var
6805   my (@args) = @_;
6807   my $do_require = 1;
6808   my $can_dist = 0;
6809   my $default_dist = 0;
6810   while (@args)
6811     {
6812       if ($args[0] eq '-noextra')
6813         {
6814           $do_require = 0;
6815         }
6816       elsif ($args[0] eq '-candist')
6817         {
6818           $can_dist = 1;
6819         }
6820       elsif ($args[0] eq '-defaultdist')
6821         {
6822           $default_dist = 1;
6823           $can_dist = 1;
6824         }
6825       elsif ($args[0] !~ /^-/)
6826         {
6827           last;
6828         }
6829       shift (@args);
6830     }
6832   my ($file, $primary, @prefix) = @args;
6834   # Now that configure substitutions are allowed in where_HOW
6835   # variables, it is an error to actually define the primary.  We
6836   # allow `JAVA', as it is customarily used to mean the Java
6837   # interpreter.  This is but one of several Java hacks.  Similarly,
6838   # `PYTHON' is customarily used to mean the Python interpreter.
6839   reject_var $primary, "`$primary' is an anachronism"
6840     unless $primary eq 'JAVA' || $primary eq 'PYTHON';
6842   # Get the prefixes which are valid and actually used.
6843   @prefix = am_primary_prefixes ($primary, $can_dist, @prefix);
6845   # If a primary includes a configure substitution, then the EXTRA_
6846   # form is required.  Otherwise we can't properly do our job.
6847   my $require_extra;
6849   my @used = ();
6850   my @result = ();
6852   foreach my $X (@prefix)
6853     {
6854       my $nodir_name = $X;
6855       my $one_name = $X . '_' . $primary;
6856       my $one_var = var $one_name;
6858       my $strip_subdir = 1;
6859       # If subdir prefix should be preserved, do so.
6860       if ($nodir_name =~ /^nobase_/)
6861         {
6862           $strip_subdir = 0;
6863           $nodir_name =~ s/^nobase_//;
6864         }
6866       # If files should be distributed, do so.
6867       my $dist_p = 0;
6868       if ($can_dist)
6869         {
6870           $dist_p = (($default_dist && $nodir_name !~ /^nodist_/)
6871                      || (! $default_dist && $nodir_name =~ /^dist_/));
6872           $nodir_name =~ s/^(dist|nodist)_//;
6873         }
6876       # Use the location of the currently processed variable.
6877       # We are not processing a particular condition, so pick the first
6878       # available.
6879       my $tmpcond = $one_var->conditions->one_cond;
6880       my $where = $one_var->rdef ($tmpcond)->location->clone;
6882       # Append actual contents of where_PRIMARY variable to
6883       # @result, skipping @substitutions@.
6884       foreach my $locvals ($one_var->value_as_list_recursive (location => 1))
6885         {
6886           my ($loc, $value) = @$locvals;
6887           # Skip configure substitutions.
6888           if ($value =~ /^\@.*\@$/)
6889             {
6890               if ($nodir_name eq 'EXTRA')
6891                 {
6892                   error ($where,
6893                          "`$one_name' contains configure substitution, "
6894                          . "but shouldn't");
6895                 }
6896               # Check here to make sure variables defined in
6897               # configure.ac do not imply that EXTRA_PRIMARY
6898               # must be defined.
6899               elsif (! defined $configure_vars{$one_name})
6900                 {
6901                   $require_extra = $one_name
6902                     if $do_require;
6903                 }
6904             }
6905           else
6906             {
6907               push (@result, $locvals);
6908             }
6909         }
6910       # A blatant hack: we rewrite each _PROGRAMS primary to include
6911       # EXEEXT.
6912       append_exeext { 1 } $one_name
6913         if $primary eq 'PROGRAMS';
6914       # "EXTRA" shouldn't be used when generating clean targets,
6915       # all, or install targets.  We used to warn if EXTRA_FOO was
6916       # defined uselessly, but this was annoying.
6917       next
6918         if $nodir_name eq 'EXTRA';
6920       if ($nodir_name eq 'check')
6921         {
6922           push (@check, '$(' . $one_name . ')');
6923         }
6924       else
6925         {
6926           push (@used, '$(' . $one_name . ')');
6927         }
6929       # Is this to be installed?
6930       my $install_p = $nodir_name ne 'noinst' && $nodir_name ne 'check';
6932       # If so, with install-exec? (or install-data?).
6933       my $exec_p = ($nodir_name =~ /$EXEC_DIR_PATTERN/o);
6935       my $check_options_p = $install_p && !! option 'std-options';
6937       # Use the location of the currently processed variable as context.
6938       $where->push_context ("while processing `$one_name'");
6940       # The variable containing all file to distribute.
6941       my $distvar = "\$($one_name)";
6942       $distvar = shadow_unconditionally ($one_name, $where)
6943         if ($dist_p && $one_var->has_conditional_contents);
6945       # Singular form of $PRIMARY.
6946       (my $one_primary = $primary) =~ s/S$//;
6947       $output_rules .= &file_contents ($file, $where,
6948                                        PRIMARY     => $primary,
6949                                        ONE_PRIMARY => $one_primary,
6950                                        DIR         => $X,
6951                                        NDIR        => $nodir_name,
6952                                        BASE        => $strip_subdir,
6954                                        EXEC      => $exec_p,
6955                                        INSTALL   => $install_p,
6956                                        DIST      => $dist_p,
6957                                        DISTVAR   => $distvar,
6958                                        'CK-OPTS' => $check_options_p);
6959     }
6961   # The JAVA variable is used as the name of the Java interpreter.
6962   # The PYTHON variable is used as the name of the Python interpreter.
6963   if (@used && $primary ne 'JAVA' && $primary ne 'PYTHON')
6964     {
6965       # Define it.
6966       define_pretty_variable ($primary, TRUE, INTERNAL, @used);
6967       $output_vars .= "\n";
6968     }
6970   err_var ($require_extra,
6971            "`$require_extra' contains configure substitution,\n"
6972            . "but `EXTRA_$primary' not defined")
6973     if ($require_extra && ! var ('EXTRA_' . $primary));
6975   # Push here because PRIMARY might be configure time determined.
6976   push (@all, '$(' . $primary . ')')
6977     if @used && $primary ne 'JAVA' && $primary ne 'PYTHON';
6979   # Make the result unique.  This lets the user use conditionals in
6980   # a natural way, but still lets us program lazily -- we don't have
6981   # to worry about handling a particular object more than once.
6982   # We will keep only one location per object.
6983   my %result = ();
6984   for my $pair (@result)
6985     {
6986       my ($loc, $val) = @$pair;
6987       $result{$val} = $loc;
6988     }
6989   my @l = sort keys %result;
6990   return map { [$result{$_}->clone, $_] } @l;
6994 ################################################################
6996 # Each key in this hash is the name of a directory holding a
6997 # Makefile.in.  These variables are local to `is_make_dir'.
6998 my %make_dirs = ();
6999 my $make_dirs_set = 0;
7001 sub is_make_dir
7003     my ($dir) = @_;
7004     if (! $make_dirs_set)
7005     {
7006         foreach my $iter (@configure_input_files)
7007         {
7008             $make_dirs{dirname ($iter)} = 1;
7009         }
7010         # We also want to notice Makefile.in's.
7011         foreach my $iter (@other_input_files)
7012         {
7013             if ($iter =~ /Makefile\.in$/)
7014             {
7015                 $make_dirs{dirname ($iter)} = 1;
7016             }
7017         }
7018         $make_dirs_set = 1;
7019     }
7020     return defined $make_dirs{$dir};
7023 ################################################################
7025 # Find the aux dir.  This should match the algorithm used by
7026 # ./configure. (See the Autoconf documentation for for
7027 # AC_CONFIG_AUX_DIR.)
7028 sub locate_aux_dir ()
7030   if (! $config_aux_dir_set_in_configure_ac)
7031     {
7032       # The default auxiliary directory is the first
7033       # of ., .., or ../.. that contains install-sh.
7034       # Assume . if install-sh doesn't exist yet.
7035       for my $dir (qw (. .. ../..))
7036         {
7037           if (-f "$dir/install-sh")
7038             {
7039               $config_aux_dir = $dir;
7040               last;
7041             }
7042         }
7043       $config_aux_dir = '.' unless $config_aux_dir;
7044     }
7045   # Avoid unsightly '/.'s.
7046   $am_config_aux_dir =
7047     '$(top_srcdir)' . ($config_aux_dir eq '.' ? "" : "/$config_aux_dir");
7048   $am_config_aux_dir =~ s,/*$,,;
7052 # &maybe_push_required_file ($DIR, $FILE, $FULLFILE)
7053 # --------------------------------------------------
7054 # See if we want to push this file onto dist_common.  This function
7055 # encodes the rules for deciding when to do so.
7056 sub maybe_push_required_file
7058   my ($dir, $file, $fullfile) = @_;
7060   if ($dir eq $relative_dir)
7061     {
7062       push_dist_common ($file);
7063       return 1;
7064     }
7065   elsif ($relative_dir eq '.' && ! &is_make_dir ($dir))
7066     {
7067       # If we are doing the topmost directory, and the file is in a
7068       # subdir which does not have a Makefile, then we distribute it
7069       # here.
7071       # If a required file is above the source tree, it is important
7072       # to prefix it with `$(srcdir)' so that no VPATH search is
7073       # performed.  Otherwise problems occur with Make implementations
7074       # that rewrite and simplify rules whose dependencies are found in a
7075       # VPATH location.  Here is an example with OSF1/Tru64 Make.
7076       #
7077       #   % cat Makefile
7078       #   VPATH = sub
7079       #   distdir: ../a
7080       #           echo ../a
7081       #   % ls
7082       #   Makefile a
7083       #   % make
7084       #   echo a
7085       #   a
7086       #
7087       # Dependency `../a' was found in `sub/../a', but this make
7088       # implementation simplified it as `a'.  (Note that the sub/
7089       # directory does not even exist.)
7090       #
7091       # This kind of VPATH rewriting seems hard to cancel.  The
7092       # distdir.am hack against VPATH rewriting works only when no
7093       # simplification is done, i.e., for dependencies which are in
7094       # subdirectories, not in enclosing directories.  Hence, in
7095       # the latter case we use a full path to make sure no VPATH
7096       # search occurs.
7097       $fullfile = '$(srcdir)/' . $fullfile
7098         if $dir =~ m,^\.\.(?:$|/),;
7100       push_dist_common ($fullfile);
7101       return 1;
7102     }
7103   return 0;
7107 # If a file name appears as a key in this hash, then it has already
7108 # been checked for.  This allows us not to report the same error more
7109 # than once.
7110 my %required_file_not_found = ();
7112 # &require_file_internal ($WHERE, $MYSTRICT, $DIRECTORY, @FILES)
7113 # --------------------------------------------------------------
7114 # Verify that the file must exist in $DIRECTORY, or install it.
7115 # $MYSTRICT is the strictness level at which this file becomes required.
7116 sub require_file_internal ($$$@)
7118   my ($where, $mystrict, $dir, @files) = @_;
7120   foreach my $file (@files)
7121     {
7122       my $fullfile = "$dir/$file";
7123       my $found_it = 0;
7124       my $dangling_sym = 0;
7126       if (-l $fullfile && ! -f $fullfile)
7127         {
7128           $dangling_sym = 1;
7129         }
7130       elsif (dir_has_case_matching_file ($dir, $file))
7131         {
7132           $found_it = 1;
7133           maybe_push_required_file ($dir, $file, $fullfile);
7134         }
7136       # `--force-missing' only has an effect if `--add-missing' is
7137       # specified.
7138       if ($found_it && (! $add_missing || ! $force_missing))
7139         {
7140           next;
7141         }
7142       else
7143         {
7144           # If we've already looked for it, we're done.  You might
7145           # wonder why we don't do this before searching for the
7146           # file.  If we do that, then something like
7147           # AC_OUTPUT(subdir/foo foo) will fail to put foo.in into
7148           # DIST_COMMON.
7149           if (! $found_it)
7150             {
7151               next if defined $required_file_not_found{$fullfile};
7152               $required_file_not_found{$fullfile} = 1;
7153             }
7155           if ($strictness >= $mystrict)
7156             {
7157               if ($dangling_sym && $add_missing)
7158                 {
7159                   unlink ($fullfile);
7160                 }
7162               my $trailer = '';
7163               my $suppress = 0;
7165               # Only install missing files according to our desired
7166               # strictness level.
7167               my $message = "required file `$fullfile' not found";
7168               if ($add_missing)
7169                 {
7170                   if (-f "$libdir/$file")
7171                     {
7172                       $suppress = 1;
7174                       # Install the missing file.  Symlink if we
7175                       # can, copy if we must.  Note: delete the file
7176                       # first, in case it is a dangling symlink.
7177                       $message = "installing `$fullfile'";
7178                       # Windows Perl will hang if we try to delete a
7179                       # file that doesn't exist.
7180                       unlink ($fullfile) if -f $fullfile;
7181                       if ($symlink_exists && ! $copy_missing)
7182                         {
7183                           if (! symlink ("$libdir/$file", $fullfile))
7184                             {
7185                               $suppress = 0;
7186                               $trailer = "; error while making link: $!";
7187                             }
7188                         }
7189                       elsif (system ('cp', "$libdir/$file", $fullfile))
7190                         {
7191                           $suppress = 0;
7192                           $trailer = "\n    error while copying";
7193                         }
7194                       reset_dir_cache ($dir);
7195                     }
7197                   if (! maybe_push_required_file (dirname ($fullfile),
7198                                                   $file, $fullfile))
7199                     {
7200                       if (! $found_it && ! $automake_will_process_aux_dir)
7201                         {
7202                           # We have added the file but could not push it
7203                           # into DIST_COMMON, probably because this is
7204                           # an auxiliary file and we are not processing
7205                           # the top level Makefile.  Furthermore Automake
7206                           # hasn't been asked to create the Makefile.in
7207                           # that distribute the aux dir files.
7208                           error ($where, 'Please make a full run of automake'
7209                                  . " so $fullfile gets distributed.");
7210                         }
7211                     }
7212                 }
7213               else
7214                 {
7215                   $trailer = "\n  `automake --add-missing' can install `$file'"
7216                     if -f "$libdir/$file";
7217                 }
7219               # If --force-missing was specified, and we have
7220               # actually found the file, then do nothing.
7221               next
7222                 if $found_it && $force_missing;
7224               # If we couldn' install the file, but it is a target in
7225               # the Makefile, don't print anything.  This allows files
7226               # like README, AUTHORS, or THANKS to be generated.
7227               next
7228                 if !$suppress && rule $file;
7230               msg ($suppress ? 'note' : 'error', $where, "$message$trailer");
7231             }
7232         }
7233     }
7236 # &require_file ($WHERE, $MYSTRICT, @FILES)
7237 # -----------------------------------------
7238 sub require_file ($$@)
7240     my ($where, $mystrict, @files) = @_;
7241     require_file_internal ($where, $mystrict, $relative_dir, @files);
7244 # &require_file_with_macro ($COND, $MACRO, $MYSTRICT, @FILES)
7245 # -----------------------------------------------------------
7246 sub require_file_with_macro ($$$@)
7248     my ($cond, $macro, $mystrict, @files) = @_;
7249     $macro = rvar ($macro) unless ref $macro;
7250     require_file ($macro->rdef ($cond)->location, $mystrict, @files);
7253 # &require_libsource_with_macro ($COND, $MACRO, $MYSTRICT, @FILES)
7254 # ----------------------------------------------------------------
7255 # Require an AC_LIBSOURCEd file.  If AC_CONFIG_LIBOBJ_DIR was called, it
7256 # must be in that directory.  Otherwise expect it in the current directory.
7257 sub require_libsource_with_macro ($$$@)
7259     my ($cond, $macro, $mystrict, @files) = @_;
7260     $macro = rvar ($macro) unless ref $macro;
7261     if ($config_libobj_dir)
7262       {
7263         require_file_internal ($macro->rdef ($cond)->location, $mystrict,
7264                                $config_libobj_dir, @files);
7265       }
7266     else
7267       {
7268         require_file ($macro->rdef ($cond)->location, $mystrict, @files);
7269       }
7272 # &require_conf_file ($WHERE, $MYSTRICT, @FILES)
7273 # ----------------------------------------------
7274 # Looks in configuration path, as specified by AC_CONFIG_AUX_DIR.
7275 sub require_conf_file ($$@)
7277     my ($where, $mystrict, @files) = @_;
7278     require_file_internal ($where, $mystrict, $config_aux_dir, @files);
7282 # &require_conf_file_with_macro ($COND, $MACRO, $MYSTRICT, @FILES)
7283 # ----------------------------------------------------------------
7284 sub require_conf_file_with_macro ($$$@)
7286     my ($cond, $macro, $mystrict, @files) = @_;
7287     require_conf_file (rvar ($macro)->rdef ($cond)->location,
7288                        $mystrict, @files);
7291 ################################################################
7293 # &require_build_directory ($DIRECTORY)
7294 # ------------------------------------
7295 # Emit rules to create $DIRECTORY if needed, and return
7296 # the file that any target requiring this directory should be made
7297 # dependent upon.
7298 # We don't want to emit the rule twice, and want to reuse it
7299 # for directories with equivalent names (e.g., `foo/bar' and `./foo//bar').
7300 sub require_build_directory ($)
7302   my $directory = shift;
7304   return $directory_map{$directory} if exists $directory_map{$directory};
7306   my $cdir = File::Spec->canonpath ($directory);
7308   if (exists $directory_map{$cdir})
7309     {
7310       my $stamp = $directory_map{$cdir};
7311       $directory_map{$directory} = $stamp;
7312       return $stamp;
7313     }
7315   my $dirstamp = "$cdir/\$(am__dirstamp)";
7317   $directory_map{$directory} = $dirstamp;
7318   $directory_map{$cdir} = $dirstamp;
7320   # Set a variable for the dirstamp basename.
7321   define_pretty_variable ('am__dirstamp', TRUE, INTERNAL,
7322                           '$(am__leading_dot)dirstamp');
7324   # Directory must be removed by `make distclean'.
7325   $clean_files{$dirstamp} = DIST_CLEAN;
7327   $output_rules .= ("$dirstamp:\n"
7328                     . "\t\@\$(mkdir_p) $directory\n"
7329                     . "\t\@: > $dirstamp\n");
7331   return $dirstamp;
7334 # &require_build_directory_maybe ($FILE)
7335 # --------------------------------------
7336 # If $FILE lies in a subdirectory, emit a rule to create this
7337 # directory and return the file that $FILE should be made
7338 # dependent upon.  Otherwise, just return the empty string.
7339 sub require_build_directory_maybe ($)
7341     my $file = shift;
7342     my $directory = dirname ($file);
7344     if ($directory ne '.')
7345     {
7346         return require_build_directory ($directory);
7347     }
7348     else
7349     {
7350         return '';
7351     }
7354 ################################################################
7356 # Push a list of files onto dist_common.
7357 sub push_dist_common
7359   prog_error "push_dist_common run after handle_dist"
7360     if $handle_dist_run;
7361   Automake::Variable::define ('DIST_COMMON', VAR_AUTOMAKE, '+', TRUE, "@_",
7362                               '', INTERNAL, VAR_PRETTY);
7366 ################################################################
7368 # generate_makefile ($MAKEFILE_AM, $MAKEFILE_IN)
7369 # ----------------------------------------------
7370 # Generate a Makefile.in given the name of the corresponding Makefile and
7371 # the name of the file output by config.status.
7372 sub generate_makefile ($$)
7374   my ($makefile_am, $makefile_in) = @_;
7376   # Reset all the Makefile.am related variables.
7377   initialize_per_input;
7379   # AUTOMAKE_OPTIONS can contains -W flags to disable or enable
7380   # warnings for this file.  So hold any warning issued before
7381   # we have processed AUTOMAKE_OPTIONS.
7382   buffer_messages ('warning');
7384   # Name of input file ("Makefile.am") and output file
7385   # ("Makefile.in").  These have no directory components.
7386   $am_file_name = basename ($makefile_am);
7387   $in_file_name = basename ($makefile_in);
7389   # $OUTPUT is encoded.  If it contains a ":" then the first element
7390   # is the real output file, and all remaining elements are input
7391   # files.  We don't scan or otherwise deal with these input files,
7392   # other than to mark them as dependencies.  See
7393   # &scan_autoconf_files for details.
7394   my ($makefile, @inputs) = split (/:/, $output_files{$makefile_in});
7396   $relative_dir = dirname ($makefile);
7397   $am_relative_dir = dirname ($makefile_am);
7398   $topsrcdir = backname ($relative_dir);
7400   read_main_am_file ($makefile_am);
7401   if (handle_options)
7402     {
7403       # Process buffered warnings.
7404       flush_messages;
7405       # Fatal error.  Just return, so we can continue with next file.
7406       return;
7407     }
7408   # Process buffered warnings.
7409   flush_messages;
7411   # There are a few install-related variables that you should not define.
7412   foreach my $var ('PRE_INSTALL', 'POST_INSTALL', 'NORMAL_INSTALL')
7413     {
7414       my $v = var $var;
7415       if ($v)
7416         {
7417           my $def = $v->def (TRUE);
7418           prog_error "$var not defined in condition TRUE"
7419             unless $def;
7420           reject_var $var, "`$var' should not be defined"
7421             if $def->owner != VAR_AUTOMAKE;
7422         }
7423     }
7425   # Catch some obsolete variables.
7426   msg_var ('obsolete', 'INCLUDES',
7427            "`INCLUDES' is the old name for `AM_CPPFLAGS' (or `*_CPPFLAGS')")
7428     if var ('INCLUDES');
7430   # Must do this after reading .am file.
7431   define_variable ('subdir', $relative_dir, INTERNAL);
7433   # If DIST_SUBDIRS is defined, make sure SUBDIRS is, so that
7434   # recursive rules are enabled.
7435   define_pretty_variable ('SUBDIRS', TRUE, INTERNAL, '')
7436     if var 'DIST_SUBDIRS' && ! var 'SUBDIRS';
7438   # Check first, because we might modify some state.
7439   check_cygnus;
7440   check_gnu_standards;
7441   check_gnits_standards;
7443   handle_configure ($makefile_am, $makefile_in, $makefile, @inputs);
7444   handle_gettext;
7445   handle_libraries;
7446   handle_ltlibraries;
7447   handle_programs;
7448   handle_scripts;
7450   # These must be run after all the sources are scanned.  They
7451   # use variables defined by &handle_libraries, &handle_ltlibraries,
7452   # or &handle_programs.
7453   handle_compile;
7454   handle_languages;
7455   handle_libtool;
7457   # Variables used by distdir.am and tags.am.
7458   define_pretty_variable ('SOURCES', TRUE, INTERNAL, @sources);
7459   if (! option 'no-dist')
7460     {
7461       define_pretty_variable ('DIST_SOURCES', TRUE, INTERNAL, @dist_sources);
7462     }
7464   handle_multilib;
7465   handle_texinfo;
7466   handle_emacs_lisp;
7467   handle_python;
7468   handle_java;
7469   handle_man_pages;
7470   handle_data;
7471   handle_headers;
7472   handle_subdirs;
7473   handle_tags;
7474   handle_minor_options;
7475   # Must come after handle_programs so that %known_programs is up-to-date.
7476   handle_tests;
7478   # This must come after most other rules.
7479   handle_dist;
7481   handle_footer;
7482   do_check_merge_target;
7483   handle_all ($makefile);
7485   # FIXME: Gross!
7486   if (var ('lib_LTLIBRARIES') && var ('bin_PROGRAMS'))
7487     {
7488       $output_rules .= "install-binPROGRAMS: install-libLTLIBRARIES\n\n";
7489     }
7491   handle_install;
7492   handle_clean ($makefile);
7493   handle_factored_dependencies;
7495   # Comes last, because all the above procedures may have
7496   # defined or overridden variables.
7497   $output_vars .= output_variables;
7499   check_typos;
7501   my ($out_file) = $output_directory . '/' . $makefile_in;
7503   if ($exit_code != 0)
7504     {
7505       verb "not writing $out_file because of earlier errors";
7506       return;
7507     }
7509   if (! -d ($output_directory . '/' . $am_relative_dir))
7510     {
7511       mkdir ($output_directory . '/' . $am_relative_dir, 0755);
7512     }
7514   # We make sure that `all:' is the first target.
7515   my $output =
7516     "$output_vars$output_all$output_header$output_rules$output_trailer";
7518   # Decide whether we must update the output file or not.
7519   # We have to update in the following situations.
7520   #  * $force_generation is set.
7521   #  * any of the output dependencies is younger than the output
7522   #  * the contents of the output is different (this can happen
7523   #    if the project has been populated with a file listed in
7524   #    @common_files since the last run).
7525   # Output's dependencies are split in two sets:
7526   #  * dependencies which are also configure dependencies
7527   #    These do not change between each Makefile.am
7528   #  * other dependencies, specific to the Makefile.am being processed
7529   #    (such as the Makefile.am itself, or any Makefile fragment
7530   #    it includes).
7531   my $timestamp = mtime $out_file;
7532   if (! $force_generation
7533       && $configure_deps_greatest_timestamp < $timestamp
7534       && $output_deps_greatest_timestamp < $timestamp
7535       && $output eq contents ($out_file))
7536     {
7537       verb "$out_file unchanged";
7538       # No need to update.
7539       return;
7540     }
7542   if (-e $out_file)
7543     {
7544       unlink ($out_file)
7545         or fatal "cannot remove $out_file: $!\n";
7546     }
7548   my $gm_file = new Automake::XFile "> $out_file";
7549   verb "creating $out_file";
7550   print $gm_file $output;
7553 ################################################################
7558 ################################################################
7560 # Print usage information.
7561 sub usage ()
7563     print "Usage: $0 [OPTION] ... [Makefile]...
7565 Generate Makefile.in for configure from Makefile.am.
7567 Operation modes:
7568       --help               print this help, then exit
7569       --version            print version number, then exit
7570   -v, --verbose            verbosely list files processed
7571       --no-force           only update Makefile.in's that are out of date
7572   -W, --warnings=CATEGORY  report the warnings falling in CATEGORY
7574 Dependency tracking:
7575   -i, --ignore-deps      disable dependency tracking code
7576       --include-deps     enable dependency tracking code
7578 Flavors:
7579       --cygnus           assume program is part of Cygnus-style tree
7580       --foreign          set strictness to foreign
7581       --gnits            set strictness to gnits
7582       --gnu              set strictness to gnu
7584 Library files:
7585   -a, --add-missing      add missing standard files to package
7586       --libdir=DIR       directory storing library files
7587   -c, --copy             with -a, copy missing files (default is symlink)
7588   -f, --force-missing    force update of standard files
7591     Automake::ChannelDefs::usage;
7593     my ($last, @lcomm);
7594     $last = '';
7595     foreach my $iter (sort ((@common_files, @common_sometimes)))
7596     {
7597         push (@lcomm, $iter) unless $iter eq $last;
7598         $last = $iter;
7599     }
7601     my @four;
7602     print "\nFiles which are automatically distributed, if found:\n";
7603     format USAGE_FORMAT =
7604   @<<<<<<<<<<<<<<<<   @<<<<<<<<<<<<<<<<   @<<<<<<<<<<<<<<<<   @<<<<<<<<<<<<<<<<
7605   $four[0],           $four[1],           $four[2],           $four[3]
7607     $~ = "USAGE_FORMAT";
7609     my $cols = 4;
7610     my $rows = int(@lcomm / $cols);
7611     my $rest = @lcomm % $cols;
7613     if ($rest)
7614     {
7615         $rows++;
7616     }
7617     else
7618     {
7619         $rest = $cols;
7620     }
7622     for (my $y = 0; $y < $rows; $y++)
7623     {
7624         @four = ("", "", "", "");
7625         for (my $x = 0; $x < $cols; $x++)
7626         {
7627             last if $y + 1 == $rows && $x == $rest;
7629             my $idx = (($x > $rest)
7630                        ?  ($rows * $rest + ($rows - 1) * ($x - $rest))
7631                        : ($rows * $x));
7633             $idx += $y;
7634             $four[$x] = $lcomm[$idx];
7635         }
7636         write;
7637     }
7639     print "\nReport bugs to <bug-automake\@gnu.org>.\n";
7641     # --help always returns 0 per GNU standards.
7642     exit 0;
7646 # &version ()
7647 # -----------
7648 # Print version information
7649 sub version ()
7651   print <<EOF;
7652 automake (GNU $PACKAGE) $VERSION
7653 Written by Tom Tromey <tromey\@redhat.com>
7654        and Alexandre Duret-Lutz <adl\@gnu.org>.
7656 Copyright 2006 Free Software Foundation, Inc.
7657 This is free software; see the source for copying conditions.  There is NO
7658 warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
7660   # --version always returns 0 per GNU standards.
7661   exit 0;
7664 ################################################################
7666 # Parse command line.
7667 sub parse_arguments ()
7669   # Start off as gnu.
7670   set_strictness ('gnu');
7672   my $cli_where = new Automake::Location;
7673   my %cli_options =
7674     (
7675      'libdir=s'         => \$libdir,
7676      'gnu'              => sub { set_strictness ('gnu'); },
7677      'gnits'            => sub { set_strictness ('gnits'); },
7678      'cygnus'           => sub { set_global_option ('cygnus', $cli_where); },
7679      'foreign'          => sub { set_strictness ('foreign'); },
7680      'include-deps'     => sub { unset_global_option ('no-dependencies'); },
7681      'i|ignore-deps'    => sub { set_global_option ('no-dependencies',
7682                                                     $cli_where); },
7683      'no-force'         => sub { $force_generation = 0; },
7684      'f|force-missing'  => \$force_missing,
7685      'o|output-dir=s'   => \$output_directory,
7686      'a|add-missing'    => \$add_missing,
7687      'c|copy'           => \$copy_missing,
7688      'v|verbose'        => sub { setup_channel 'verb', silent => 0; },
7689      'W|warnings=s'     => \&parse_warnings,
7690      # These long options (--Werror and --Wno-error) for backward
7691      # compatibility.  Use -Werror and -Wno-error today.
7692      'Werror'           => sub { parse_warnings 'W', 'error'; },
7693      'Wno-error'        => sub { parse_warnings 'W', 'no-error'; },
7694      );
7695   use Getopt::Long;
7696   Getopt::Long::config ("bundling", "pass_through");
7698   # See if --version or --help is used.  We want to process these before
7699   # anything else because the GNU Coding Standards require us to
7700   # `exit 0' after processing these options, and we can't guarantee this
7701   # if we treat other options first.  (Handling other options first
7702   # could produce error diagnostics, and in this condition it is
7703   # confusing if Automake does `exit 0'.)
7704   my %cli_options_1st_pass =
7705     (
7706      'version' => \&version,
7707      'help'    => \&usage,
7708      # Recognize all other options (and their arguments) but do nothing.
7709      map { $_ => sub {} } (keys %cli_options)
7710      );
7711   my @ARGV_backup = @ARGV;
7712   Getopt::Long::GetOptions %cli_options_1st_pass
7713     or exit 1;
7714   @ARGV = @ARGV_backup;
7716   # Now *really* process the options.  This time we know that --help
7717   # and --version are not present, but we specify them nonetheless so
7718   # that ambiguous abbreviation are diagnosed.
7719   Getopt::Long::GetOptions %cli_options, 'version' => sub {}, 'help' => sub {}
7720     or exit 1;
7722   if (defined $output_directory)
7723     {
7724       msg 'obsolete', "`--output-dir' is deprecated\n";
7725     }
7726   else
7727     {
7728       # In the next release we'll remove this entirely.
7729       $output_directory = '.';
7730     }
7732   return unless @ARGV;
7734   if ($ARGV[0] =~ /^-./)
7735     {
7736       my %argopts;
7737       for my $k (keys %cli_options)
7738         {
7739           if ($k =~ /(.*)=s$/)
7740             {
7741               map { $argopts{(length ($_) == 1)
7742                              ? "-$_" : "--$_" } = 1; } (split (/\|/, $1));
7743             }
7744         }
7745       if ($ARGV[0] eq '--')
7746         {
7747           shift @ARGV;
7748         }
7749       elsif (exists $argopts{$ARGV[0]})
7750         {
7751           fatal ("option `$ARGV[0]' requires an argument\n"
7752                  . "Try `$0 --help' for more information.");
7753         }
7754       else
7755         {
7756           fatal ("unrecognized option `$ARGV[0]'.\n"
7757                  . "Try `$0 --help' for more information.");
7758         }
7759     }
7761   my $errspec = 0;
7762   foreach my $arg (@ARGV)
7763     {
7764       fatal ("empty argument\nTry `$0 --help' for more information.")
7765         if ($arg eq '');
7767       # Handle $local:$input syntax.
7768       my ($local, @rest) = split (/:/, $arg);
7769       @rest = ("$local.in",) unless @rest;
7770       my $input = locate_am @rest;
7771       if ($input)
7772         {
7773           push @input_files, $input;
7774           $output_files{$input} = join (':', ($local, @rest));
7775         }
7776       else
7777         {
7778           error "no Automake input file found for `$arg'";
7779           $errspec = 1;
7780         }
7781     }
7782   fatal "no input file found among supplied arguments"
7783     if $errspec && ! @input_files;
7786 ################################################################
7788 # Parse the WARNINGS environment variable.
7789 parse_WARNINGS;
7791 # Parse command line.
7792 parse_arguments;
7794 $configure_ac = require_configure_ac;
7796 # Do configure.ac scan only once.
7797 scan_autoconf_files;
7799 if (! @input_files)
7800   {
7801     my $msg = '';
7802     $msg = "\nDid you forget AC_CONFIG_FILES([Makefile]) in $configure_ac?"
7803       if -f 'Makefile.am';
7804     fatal ("no `Makefile.am' found for any configure output$msg");
7805   }
7807 # Now do all the work on each file.
7808 foreach my $file (@input_files)
7809   {
7810     ($am_file = $file) =~ s/\.in$//;
7811     if (! -f ($am_file . '.am'))
7812       {
7813         error "`$am_file.am' does not exist";
7814       }
7815     else
7816       {
7817         # Any warning setting now local to this Makefile.am.
7818         dup_channel_setup;
7820         generate_makefile ($am_file . '.am', $file);
7822         # Back out any warning setting.
7823         drop_channel_setup;
7824       }
7825   }
7827 exit $exit_code;
7830 ### Setup "GNU" style for perl-mode and cperl-mode.
7831 ## Local Variables:
7832 ## perl-indent-level: 2
7833 ## perl-continued-statement-offset: 2
7834 ## perl-continued-brace-offset: 0
7835 ## perl-brace-offset: 0
7836 ## perl-brace-imaginary-offset: 0
7837 ## perl-label-offset: -2
7838 ## cperl-indent-level: 2
7839 ## cperl-brace-offset: 0
7840 ## cperl-continued-brace-offset: 0
7841 ## cperl-label-offset: -2
7842 ## cperl-extra-newline-before-brace: t
7843 ## cperl-merge-trailing-else: nil
7844 ## cperl-continued-statement-offset: 2
7845 ## End: