* automake.in (lang_c_rewrite): Print files and locations
[automake.git] / automake.in
blob6dd8d003421b4d7a994af8bb917eaaf3c5817641
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  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., 59 Temple Place - Suite 330, Boston, MA
25 # 02111-1307, USA.
27 # Originally written by David Mackenzie <djm@gnu.ai.mit.edu>.
28 # Perl reimplementation by Tom Tromey <tromey@redhat.com>.
30 package Language;
32 BEGIN
34   my $perllibdir = $ENV{'perllibdir'} || '@datadir@/@PACKAGE@-@APIVERSION@';
35   unshift @INC, (split '@PATH_SEPARATOR@', $perllibdir);
37   # Override SHELL.  This is required on DJGPP so that system() uses
38   # bash, not COMMAND.COM which doesn't quote arguments properly.
39   # Other systems aren't expected to use $SHELL when Automake
40   # runs, but it should be safe to drop the `if DJGPP' guard if
41   # it turns up other systems need the same thing.  After all,
42   # if SHELL is used, ./configure's SHELL is always better than
43   # the user's SHELL (which may be something like tcsh).
44   $ENV{'SHELL'} = '@SHELL@' if exists $ENV{'DJGPP'};
47 use Automake::Struct;
48 struct (# Short name of the language (c, f77...).
49         'name' => "\$",
50         # Nice name of the language (C, Fortran 77...).
51         'Name' => "\$",
53         # List of configure variables which must be defined.
54         'config_vars' => '@',
56         'ansi'    => "\$",
57         # `pure' is `1' or `'.  A `pure' language is one where, if
58         # all the files in a directory are of that language, then we
59         # do not require the C compiler or any code to call it.
60         'pure'   => "\$",
62         'autodep' => "\$",
64         # Name of the compiling variable (COMPILE).
65         'compiler'  => "\$",
66         # Content of the compiling variable.
67         'compile'  => "\$",
68         # Flag to require compilation without linking (-c).
69         'compile_flag' => "\$",
70         'extensions' => '@',
71         # A subroutine to compute a list of possible extensions of
72         # the product given the input extensions.
73         # (defaults to a subroutine which returns ('.$(OBJEXT)', '.lo'))
74         'output_extensions' => "\$",
75         # A list of flag variables used in 'compile'.
76         # (defaults to [])
77         'flags' => "@",
79         # Any tag to pass to libtool while compiling.
80         'libtool_tag' => "\$",
82         # The file to use when generating rules for this language.
83         # The default is 'depend2'.
84         'rule_file' => "\$",
86         # Name of the linking variable (LINK).
87         'linker' => "\$",
88         # Content of the linking variable.
89         'link' => "\$",
91         # Name of the linker variable (LD).
92         'lder' => "\$",
93         # Content of the linker variable ($(CC)).
94         'ld' => "\$",
96         # Flag to specify the output file (-o).
97         'output_flag' => "\$",
98         '_finish' => "\$",
100         # This is a subroutine which is called whenever we finally
101         # determine the context in which a source file will be
102         # compiled.
103         '_target_hook' => "\$",
105         # If TRUE, nodist_ sources will be compiled using specific rules
106         # (i.e. not inference rules).  The default is FALSE.
107         'nodist_specific' => "\$");
110 sub finish ($)
112   my ($self) = @_;
113   if (defined $self->_finish)
114     {
115       &{$self->_finish} ();
116     }
119 sub target_hook ($$$$%)
121     my ($self) = @_;
122     if (defined $self->_target_hook)
123     {
124         &{$self->_target_hook} (@_);
125     }
128 package Automake;
130 use strict;
131 use Automake::Config;
132 use Automake::General;
133 use Automake::XFile;
134 use Automake::Channels;
135 use Automake::ChannelDefs;
136 use Automake::Configure_ac;
137 use Automake::FileUtils;
138 use Automake::Location;
139 use Automake::Condition qw/TRUE FALSE/;
140 use Automake::DisjConditions;
141 use Automake::Options;
142 use Automake::Version;
143 use Automake::Variable;
144 use Automake::VarDef;
145 use Automake::Rule;
146 use Automake::RuleDef;
147 use Automake::Wrap 'makefile_wrap';
148 use File::Basename;
149 use Carp;
151 ## ----------- ##
152 ## Constants.  ##
153 ## ----------- ##
155 # Some regular expressions.  One reason to put them here is that it
156 # makes indentation work better in Emacs.
158 # Writing singled-quoted-$-terminated regexes is a pain because
159 # perl-mode thinks of $' as the ${'} variable (instead of a $ followed
160 # by a closing quote.  Letting perl-mode think the quote is not closed
161 # leads to all sort of misindentations.  On the other hand, defining
162 # regexes as double-quoted strings is far less readable.  So usually
163 # we will write:
165 #  $REGEX = '^regex_value' . "\$";
167 my $IGNORE_PATTERN = '^\s*##([^#\n].*)?\n';
168 my $WHITE_PATTERN = '^\s*' . "\$";
169 my $COMMENT_PATTERN = '^#';
170 my $TARGET_PATTERN='[$a-zA-Z_.@%][-.a-zA-Z0-9_(){}/$+@%]*';
171 # A rule has three parts: a list of targets, a list of dependencies,
172 # and optionally actions.
173 my $RULE_PATTERN =
174   "^($TARGET_PATTERN(?:(?:\\\\\n|\\s)+$TARGET_PATTERN)*) *:([^=].*|)\$";
176 # Only recognize leading spaces, not leading tabs.  If we recognize
177 # leading tabs here then we need to make the reader smarter, because
178 # otherwise it will think rules like `foo=bar; \' are errors.
179 my $ASSIGNMENT_PATTERN = '^ *([^ \t=:+]*)\s*([:+]?)=\s*(.*)' . "\$";
180 # This pattern recognizes a Gnits version id and sets $1 if the
181 # release is an alpha release.  We also allow a suffix which can be
182 # used to extend the version number with a "fork" identifier.
183 my $GNITS_VERSION_PATTERN = '\d+\.\d+([a-z]|\.\d+)?(-[A-Za-z0-9]+)?';
185 my $IF_PATTERN = '^if\s+(!?)\s*([A-Za-z][A-Za-z0-9_]*)\s*(?:#.*)?' . "\$";
186 my $ELSE_PATTERN =
187   '^else(?:\s+(!?)\s*([A-Za-z][A-Za-z0-9_]*))?\s*(?:#.*)?' . "\$";
188 my $ENDIF_PATTERN =
189   '^endif(?:\s+(!?)\s*([A-Za-z][A-Za-z0-9_]*))?\s*(?:#.*)?' . "\$";
190 my $PATH_PATTERN = '(\w|[+/.-])+';
191 # This will pass through anything not of the prescribed form.
192 my $INCLUDE_PATTERN = ('^include\s+'
193                        . '((\$\(top_srcdir\)/' . $PATH_PATTERN . ')'
194                        . '|(\$\(srcdir\)/' . $PATH_PATTERN . ')'
195                        . '|([^/\$]' . $PATH_PATTERN . '))\s*(#.*)?' . "\$");
197 # Match `-d' as a command-line argument in a string.
198 my $DASH_D_PATTERN = "(^|\\s)-d(\\s|\$)";
199 # Directories installed during 'install-exec' phase.
200 my $EXEC_DIR_PATTERN =
201   '^(?:bin|sbin|libexec|sysconf|localstate|lib|pkglib|.*exec.*)' . "\$";
203 # Values for AC_CANONICAL_*
204 use constant AC_CANONICAL_BUILD  => 1;
205 use constant AC_CANONICAL_HOST   => 2;
206 use constant AC_CANONICAL_TARGET => 3;
208 # Values indicating when something should be cleaned.
209 use constant MOSTLY_CLEAN     => 0;
210 use constant CLEAN            => 1;
211 use constant DIST_CLEAN       => 2;
212 use constant MAINTAINER_CLEAN => 3;
214 # Libtool files.
215 my @libtool_files = qw(ltmain.sh config.guess config.sub);
216 # ltconfig appears here for compatibility with old versions of libtool.
217 my @libtool_sometimes = qw(ltconfig ltcf-c.sh ltcf-cxx.sh ltcf-gcj.sh);
219 # Commonly found files we look for and automatically include in
220 # DISTFILES.
221 my @common_files =
222     (qw(ABOUT-GNU ABOUT-NLS AUTHORS BACKLOG COPYING COPYING.DOC COPYING.LIB
223         COPYING.LESSER ChangeLog INSTALL NEWS README THANKS TODO
224         ansi2knr.1 ansi2knr.c compile config.guess config.rpath config.sub
225         depcomp elisp-comp install-sh libversion.in mdate-sh missing
226         mkinstalldirs py-compile texinfo.tex ylwrap),
227      @libtool_files, @libtool_sometimes);
229 # Commonly used files we auto-include, but only sometimes.  This list
230 # is used for the --help output only.
231 my @common_sometimes =
232   qw(aclocal.m4 acconfig.h config.h.top config.h.bot configure
233      configure.ac configure.in stamp-vti);
235 # Standard directories from the GNU Coding Standards, and additional
236 # pkg* directories from Automake.  Stored in a hash for fast member check.
237 my %standard_prefix =
238     map { $_ => 1 } (qw(bin data exec include info lib libexec lisp
239                         localstate man man1 man2 man3 man4 man5 man6
240                         man7 man8 man9 oldinclude pkgdatadir
241                         pkgincludedir pkglibdir sbin sharedstate
242                         sysconf));
244 # Copyright on generated Makefile.ins.
245 my $gen_copyright = "\
246 # Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002,
247 # 2003, 2004  Free Software Foundation, Inc.
248 # This Makefile.in is free software; the Free Software Foundation
249 # gives unlimited permission to copy and/or distribute it,
250 # with or without modifications, as long as this notice is preserved.
252 # This program is distributed in the hope that it will be useful,
253 # but WITHOUT ANY WARRANTY, to the extent permitted by law; without
254 # even the implied warranty of MERCHANTABILITY or FITNESS FOR A
255 # PARTICULAR PURPOSE.
258 # These constants are returned by lang_*_rewrite functions.
259 # LANG_SUBDIR means that the resulting object file should be in a
260 # subdir if the source file is.  In this case the file name cannot
261 # have `..' components.
262 use constant LANG_IGNORE  => 0;
263 use constant LANG_PROCESS => 1;
264 use constant LANG_SUBDIR  => 2;
266 # These are used when keeping track of whether an object can be built
267 # by two different paths.
268 use constant COMPILE_LIBTOOL  => 1;
269 use constant COMPILE_ORDINARY => 2;
271 # We can't always associate a location to a variable or a rule,
272 # when its defined by Automake.  We use INTERNAL in this case.
273 use constant INTERNAL => new Automake::Location;
276 ## ---------------------------------- ##
277 ## Variables related to the options.  ##
278 ## ---------------------------------- ##
280 # TRUE if we should always generate Makefile.in.
281 my $force_generation = 1;
283 # From the Perl manual.
284 my $symlink_exists = (eval 'symlink ("", "");', $@ eq '');
286 # TRUE if missing standard files should be installed.
287 my $add_missing = 0;
289 # TRUE if we should copy missing files; otherwise symlink if possible.
290 my $copy_missing = 0;
292 # TRUE if we should always update files that we know about.
293 my $force_missing = 0;
296 ## ---------------------------------------- ##
297 ## Variables filled during files scanning.  ##
298 ## ---------------------------------------- ##
300 # Name of the configure.ac file.
301 my $configure_ac;
303 # Files found by scanning configure.ac for LIBOBJS.
304 my %libsources = ();
306 # Names used in AC_CONFIG_HEADER call.
307 my @config_headers = ();
309 # Names used in AC_CONFIG_LINKS call.
310 my @config_links = ();
312 # Directory where output files go.  Actually, output files are
313 # relative to this directory.
314 my $output_directory;
316 # List of Makefile.am's to process, and their corresponding outputs.
317 my @input_files = ();
318 my %output_files = ();
320 # Complete list of Makefile.am's that exist.
321 my @configure_input_files = ();
323 # List of files in AC_CONFIG_FILES/AC_OUTPUT without Makefile.am's,
324 # and their outputs.
325 my @other_input_files = ();
326 # Where each AC_CONFIG_FILES/AC_OUTPUT/AC_CONFIG_LINK/AC_CONFIG_HEADER appears.
327 # The keys are the files created by these macros.
328 my %ac_config_files_location = ();
330 # Directory to search for configure-required files.  This
331 # will be computed by &locate_aux_dir and can be set using
332 # AC_CONFIG_AUX_DIR in configure.ac.
333 # $CONFIG_AUX_DIR is the `raw' directory, valid only in the source-tree.
334 my $config_aux_dir = '';
335 my $config_aux_dir_set_in_configure_ac = 0;
336 # $AM_CONFIG_AUX_DIR is prefixed with $(top_srcdir), so it can be used
337 # in Makefiles.
338 my $am_config_aux_dir = '';
340 # Whether AM_GNU_GETTEXT has been seen in configure.ac.
341 my $seen_gettext = 0;
342 # Whether AM_GNU_GETTEXT([external]) is used.
343 my $seen_gettext_external = 0;
344 # Where AM_GNU_GETTEXT appears.
345 my $ac_gettext_location;
347 # Lists of tags supported by Libtool.
348 my %libtool_tags = ();
349 # 1 if Libtool uses LT_SUPPORTED_TAG.  If it does, then it also
350 # use AC_REQUIRE_AUX_FILE.
351 my $libtool_new_api = 0;
353 # Most important AC_CANONICAL_* macro seen so far.
354 my $seen_canonical = 0;
355 # Location of that macro.
356 my $canonical_location;
358 # Where AM_MAINTAINER_MODE appears.
359 my $seen_maint_mode;
361 # Actual version we've seen.
362 my $package_version = '';
364 # Where version is defined.
365 my $package_version_location;
367 # TRUE if we've seen AC_ENABLE_MULTILIB.
368 my $seen_multilib = 0;
370 # TRUE if we've seen AM_PROG_CC_C_O
371 my $seen_cc_c_o = 0;
373 # Location of AC_REQUIRE_AUX_FILE calls, indexed by their argument.
374 my %required_aux_file = ();
376 # Where AM_INIT_AUTOMAKE is called;
377 my $seen_init_automake = 0;
379 # TRUE if we've seen AM_AUTOMAKE_VERSION.
380 my $seen_automake_version = 0;
382 # Hash table of discovered configure substitutions.  Keys are names,
383 # values are `FILE:LINE' strings which are used by error message
384 # generation.
385 my %configure_vars = ();
387 # Files included by $configure_ac.
388 my @configure_deps = ();
390 # Greatest timestamp of configure's dependencies.
391 my $configure_deps_greatest_timestamp = 0;
393 # Hash table of AM_CONDITIONAL variables seen in configure.
394 my %configure_cond = ();
396 # This maps extensions onto language names.
397 my %extension_map = ();
399 # List of the DIST_COMMON files we discovered while reading
400 # configure.in
401 my $configure_dist_common = '';
403 # This maps languages names onto objects.
404 my %languages = ();
406 # List of targets we must always output.
407 # FIXME: Complete, and remove falsely required targets.
408 my %required_targets =
409   (
410    'all'          => 1,
411    'dvi'          => 1,
412    'pdf'          => 1,
413    'ps'           => 1,
414    'info'         => 1,
415    'install-info' => 1,
416    'install'      => 1,
417    'install-data' => 1,
418    'install-exec' => 1,
419    'uninstall'    => 1,
421    # FIXME: Not required, temporary hacks.
422    # Well, actually they are sort of required: the -recursive
423    # targets will run them anyway...
424    'dvi-am'          => 1,
425    'pdf-am'          => 1,
426    'ps-am'           => 1,
427    'info-am'         => 1,
428    'install-data-am' => 1,
429    'install-exec-am' => 1,
430    'installcheck-am' => 1,
431    'uninstall-am' => 1,
433    'install-man' => 1,
434   );
436 # Set to 1 if this run will create the Makefile.in that distribute
437 # the files in config_aux_dir.
438 my $automake_will_process_aux_dir = 0;
440 # The name of the Makefile currently being processed.
441 my $am_file = 'BUG';
444 ################################################################
446 ## ------------------------------------------ ##
447 ## Variables reset by &initialize_per_input.  ##
448 ## ------------------------------------------ ##
450 # Basename and relative dir of the input file.
451 my $am_file_name;
452 my $am_relative_dir;
454 # Same but wrt Makefile.in.
455 my $in_file_name;
456 my $relative_dir;
458 # Greatest timestamp of the output's dependencies (excluding
459 # configure's dependencies).
460 my $output_deps_greatest_timestamp;
462 # These two variables are used when generating each Makefile.in.
463 # They hold the Makefile.in until it is ready to be printed.
464 my $output_rules;
465 my $output_vars;
466 my $output_trailer;
467 my $output_all;
468 my $output_header;
470 # This is the conditional stack, updated on if/else/endif, and
471 # used to build Condition objects.
472 my @cond_stack;
474 # This holds the set of included files.
475 my @include_stack;
477 # This holds a list of directories which we must create at `dist'
478 # time.  This is used in some strange scenarios involving weird
479 # AC_OUTPUT commands.
480 my %dist_dirs;
482 # List of dependencies for the obvious targets.
483 my @all;
484 my @check;
485 my @check_tests;
487 # Keys in this hash table are files to delete.  The associated
488 # value tells when this should happen (MOSTLY_CLEAN, DIST_CLEAN, etc.)
489 my %clean_files;
491 # Keys in this hash table are object files or other files in
492 # subdirectories which need to be removed.  This only holds files
493 # which are created by compilations.  The value in the hash indicates
494 # when the file should be removed.
495 my %compile_clean_files;
497 # Keys in this hash table are directories where we expect to build a
498 # libtool object.  We use this information to decide what directories
499 # to delete.
500 my %libtool_clean_directories;
502 # Value of `$(SOURCES)', used by tags.am.
503 my @sources;
504 # Sources which go in the distribution.
505 my @dist_sources;
507 # This hash maps object file names onto their corresponding source
508 # file names.  This is used to ensure that each object is created
509 # by a single source file.
510 my %object_map;
512 # This hash maps object file names onto an integer value representing
513 # whether this object has been built via ordinary compilation or
514 # libtool compilation (the COMPILE_* constants).
515 my %object_compilation_map;
518 # This keeps track of the directories for which we've already
519 # created dirstamp code.
520 my %directory_map;
522 # All .P files.
523 my %dep_files;
525 # This is a list of all targets to run during "make dist".
526 my @dist_targets;
528 # Keys in this hash are the basenames of files which must depend on
529 # ansi2knr.  Values are either the empty string, or the directory in
530 # which the ANSI source file appears; the directory must have a
531 # trailing `/'.
532 my %de_ansi_files;
534 # This is the name of the redirect `all' target to use.
535 my $all_target;
537 # This keeps track of which extensions we've seen (that we care
538 # about).
539 my %extension_seen;
541 # This is random scratch space for the language finish functions.
542 # Don't randomly overwrite it; examine other uses of keys first.
543 my %language_scratch;
545 # We keep track of which objects need special (per-executable)
546 # handling on a per-language basis.
547 my %lang_specific_files;
549 # This is set when `handle_dist' has finished.  Once this happens,
550 # we should no longer push on dist_common.
551 my $handle_dist_run;
553 # Used to store a set of linkers needed to generate the sources currently
554 # under consideration.
555 my %linkers_used;
557 # True if we need `LINK' defined.  This is a hack.
558 my $need_link;
560 # Was get_object_extension run?
561 # FIXME: This is a hack. a better switch should be found.
562 my $get_object_extension_was_run;
564 # Record each file processed by make_paragraphs.
565 my %transformed_files;
567 # Cache each file processed by make_paragraphs.
568 # (This is different from %transformed_files because
569 # %transformed_files is reset for each file while %am_file_cache
570 # it global to the run.)
571 my %am_file_cache;
573 ################################################################
575 # var_SUFFIXES_trigger ($TYPE, $VALUE)
576 # ------------------------------------
577 # This is called by Automake::Variable::define() when SUFFIXES
578 # is defined ($TYPE eq '') or appended ($TYPE eq '+').
579 # The work here needs to be performed as a side-effect of the
580 # macro_define() call because SUFFIXES definitions impact
581 # on $KNOWN_EXTENSIONS_PATTERN which is used used when parsing
582 # the input am file.
583 sub var_SUFFIXES_trigger ($$)
585     my ($type, $value) = @_;
586     accept_extensions (split (' ', $value));
588 Automake::Variable::hook ('SUFFIXES', \&var_SUFFIXES_trigger);
590 ################################################################
592 ## --------------------------------- ##
593 ## Forward subroutine declarations.  ##
594 ## --------------------------------- ##
595 sub register_language (%);
596 sub file_contents_internal ($$$%);
597 sub define_files_variable ($\@$$);
600 # &initialize_per_input ()
601 # ------------------------
602 # (Re)-Initialize per-Makefile.am variables.
603 sub initialize_per_input ()
605     reset_local_duplicates ();
607     $am_file_name = '';
608     $am_relative_dir = '';
610     $in_file_name = '';
611     $relative_dir = '';
613     $output_deps_greatest_timestamp = 0;
615     $output_rules = '';
616     $output_vars = '';
617     $output_trailer = '';
618     $output_all = '';
619     $output_header = '';
621     Automake::Options::reset;
622     Automake::Variable::reset;
623     Automake::Rule::reset;
625     @cond_stack = ();
627     @include_stack = ();
629     %dist_dirs = ();
631     @all = ();
632     @check = ();
633     @check_tests = ();
635     %clean_files = ();
637     @sources = ();
638     @dist_sources = ();
640     %object_map = ();
641     %object_compilation_map = ();
643     %directory_map = ();
645     %dep_files = ();
647     @dist_targets = ();
649     %de_ansi_files = ();
651     $all_target = '';
653     %extension_seen = ();
655     %language_scratch = ();
657     %lang_specific_files = ();
659     $handle_dist_run = 0;
661     $need_link = 0;
663     $get_object_extension_was_run = 0;
665     %compile_clean_files = ();
667     # We always include `.'.  This isn't strictly correct.
668     %libtool_clean_directories = ('.' => 1);
670     %transformed_files = ();
674 ################################################################
676 # Initialize our list of languages that are internally supported.
678 # C.
679 register_language ('name' => 'c',
680                    'Name' => 'C',
681                    'config_vars' => ['CC'],
682                    'ansi' => 1,
683                    'autodep' => '',
684                    'flags' => ['CFLAGS', 'CPPFLAGS'],
685                    'compiler' => 'COMPILE',
686                    'compile' => '$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS)',
687                    'lder' => 'CCLD',
688                    'ld' => '$(CC)',
689                    'linker' => 'LINK',
690                    'link' => '$(CCLD) $(AM_CFLAGS) $(CFLAGS) $(AM_LDFLAGS) $(LDFLAGS) -o $@',
691                    'compile_flag' => '-c',
692                    'libtool_tag' => 'CC',
693                    'extensions' => ['.c'],
694                    '_finish' => \&lang_c_finish);
696 # C++.
697 register_language ('name' => 'cxx',
698                    'Name' => 'C++',
699                    'config_vars' => ['CXX'],
700                    'linker' => 'CXXLINK',
701                    'link' => '$(CXXLD) $(AM_CXXFLAGS) $(CXXFLAGS) $(AM_LDFLAGS) $(LDFLAGS) -o $@',
702                    'autodep' => 'CXX',
703                    'flags' => ['CXXFLAGS', 'CPPFLAGS'],
704                    'compile' => '$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS)',
705                    'compiler' => 'CXXCOMPILE',
706                    'compile_flag' => '-c',
707                    'output_flag' => '-o',
708                    'libtool_tag' => 'CXX',
709                    'lder' => 'CXXLD',
710                    'ld' => '$(CXX)',
711                    'pure' => 1,
712                    'extensions' => ['.c++', '.cc', '.cpp', '.cxx', '.C']);
714 # Objective C.
715 register_language ('name' => 'objc',
716                    'Name' => 'Objective C',
717                    'config_vars' => ['OBJC'],
718                    'linker' => 'OBJCLINK',,
719                    'link' => '$(OBJCLD) $(AM_OBJCFLAGS) $(OBJCFLAGS) $(AM_LDFLAGS) $(LDFLAGS) -o $@',
720                    'autodep' => 'OBJC',
721                    'flags' => ['OBJCFLAGS', 'CPPFLAGS'],
722                    'compile' => '$(OBJC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_OBJCFLAGS) $(OBJCFLAGS)',
723                    'compiler' => 'OBJCCOMPILE',
724                    'compile_flag' => '-c',
725                    'output_flag' => '-o',
726                    'lder' => 'OBJCLD',
727                    'ld' => '$(OBJC)',
728                    'pure' => 1,
729                    'extensions' => ['.m']);
731 # Headers.
732 register_language ('name' => 'header',
733                    'Name' => 'Header',
734                    'extensions' => ['.h', '.H', '.hxx', '.h++', '.hh',
735                                     '.hpp', '.inc'],
736                    # No output.
737                    'output_extensions' => sub { return () },
738                    # Nothing to do.
739                    '_finish' => sub { });
741 # Yacc (C & C++).
742 register_language ('name' => 'yacc',
743                    'Name' => 'Yacc',
744                    'config_vars' => ['YACC'],
745                    'flags' => ['YFLAGS'],
746                    'compile' => '$(YACC) $(YFLAGS) $(AM_YFLAGS)',
747                    'compiler' => 'YACCCOMPILE',
748                    'extensions' => ['.y'],
749                    'output_extensions' => sub { (my $ext = $_[0]) =~ tr/y/c/;
750                                                 return ($ext,) },
751                    'rule_file' => 'yacc',
752                    '_finish' => \&lang_yacc_finish,
753                    '_target_hook' => \&lang_yacc_target_hook,
754                    'nodist_specific' => 1);
755 register_language ('name' => 'yaccxx',
756                    'Name' => 'Yacc (C++)',
757                    'config_vars' => ['YACC'],
758                    'rule_file' => 'yacc',
759                    'flags' => ['YFLAGS'],
760                    'compiler' => 'YACCCOMPILE',
761                    'compile' => '$(YACC) $(YFLAGS) $(AM_YFLAGS)',
762                    'extensions' => ['.y++', '.yy', '.yxx', '.ypp'],
763                    'output_extensions' => sub { (my $ext = $_[0]) =~ tr/y/c/;
764                                                 return ($ext,) },
765                    '_finish' => \&lang_yacc_finish,
766                    '_target_hook' => \&lang_yacc_target_hook,
767                    'nodist_specific' => 1);
769 # Lex (C & C++).
770 register_language ('name' => 'lex',
771                    'Name' => 'Lex',
772                    'config_vars' => ['LEX'],
773                    'rule_file' => 'lex',
774                    'flags' => ['LFLAGS'],
775                    'compile' => '$(LEX) $(LFLAGS) $(AM_LFLAGS)',
776                    'compiler' => 'LEXCOMPILE',
777                    'extensions' => ['.l'],
778                    'output_extensions' => sub { (my $ext = $_[0]) =~ tr/l/c/;
779                                                 return ($ext,) },
780                    '_finish' => \&lang_lex_finish,
781                    '_target_hook' => \&lang_lex_target_hook,
782                    'nodist_specific' => 1);
783 register_language ('name' => 'lexxx',
784                    'Name' => 'Lex (C++)',
785                    'config_vars' => ['LEX'],
786                    'rule_file' => 'lex',
787                    'flags' => ['LFLAGS'],
788                    'compile' => '$(LEX) $(LFLAGS) $(AM_LFLAGS)',
789                    'compiler' => 'LEXCOMPILE',
790                    'extensions' => ['.l++', '.ll', '.lxx', '.lpp'],
791                    'output_extensions' => sub { (my $ext = $_[0]) =~ tr/l/c/;
792                                                 return ($ext,) },
793                    '_finish' => \&lang_lex_finish,
794                    '_target_hook' => \&lang_lex_target_hook,
795                    'nodist_specific' => 1);
797 # Assembler.
798 register_language ('name' => 'asm',
799                    'Name' => 'Assembler',
800                    'config_vars' => ['CCAS', 'CCASFLAGS'],
802                    'flags' => ['CCASFLAGS'],
803                    # Users can set AM_ASFLAGS to includes DEFS, INCLUDES,
804                    # or anything else required.  They can also set AS.
805                    'compile' => '$(CCAS) $(AM_CCASFLAGS) $(CCASFLAGS)',
806                    'compiler' => 'CCASCOMPILE',
807                    'compile_flag' => '-c',
808                    'extensions' => ['.s', '.S'],
810                    # With assembly we still use the C linker.
811                    '_finish' => \&lang_c_finish);
813 # Fortran 77
814 register_language ('name' => 'f77',
815                    'Name' => 'Fortran 77',
816                    'linker' => 'F77LINK',
817                    'link' => '$(F77LD) $(AM_FFLAGS) $(FFLAGS) $(AM_LDFLAGS) $(LDFLAGS) -o $@',
818                    'flags' => ['FFLAGS'],
819                    'compile' => '$(F77) $(AM_FFLAGS) $(FFLAGS)',
820                    'compiler' => 'F77COMPILE',
821                    'compile_flag' => '-c',
822                    'output_flag' => '-o',
823                    'libtool_tag' => 'F77',
824                    'lder' => 'F77LD',
825                    'ld' => '$(F77)',
826                    'pure' => 1,
827                    'extensions' => ['.f', '.for']);
829 # Fortran
830 register_language ('name' => 'fc',
831                    'Name' => 'Fortran',
832                    'linker' => 'FCLINK',
833                    'link' => '$(FCLD) $(AM_FCFLAGS) $(FCFLAGS) $(AM_LDFLAGS) $(LDFLAGS) -o $@',
834                    'flags' => ['FCFLAGS'],
835                    'compile' => '$(FC) $(AM_FCFLAGS) $(FCFLAGS)',
836                    'compiler' => 'FCCOMPILE',
837                    'compile_flag' => '-c',
838                    'output_flag' => '-o',
839                    'lder' => 'FCLD',
840                    'ld' => '$(FC)',
841                    'pure' => 1,
842                    'extensions' => ['.f90', '.f95']);
844 # Preprocessed Fortran
845 register_language ('name' => 'ppfc',
846                    'Name' => 'Preprocessed Fortran',
847                    'config_vars' => ['FC'],
848                    'linker' => 'FCLINK',
849                    'link' => '$(FCLD) $(AM_FFLAGS) $(FCFLAGS) $(AM_LDFLAGS) $(LDFLAGS) -o $@',
850                    'lder' => 'FCLD',
851                    'ld' => '$(FC)',
852                    'flags' => ['FCFLAGS', 'CPPFLAGS'],
853                    'compiler' => 'PPFCCOMPILE',
854                    'compile' => '$(FC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_FCFLAGS) $(FCFLAGS)',
855                    'compile_flag' => '-c',
856                    'output_flag' => '-o',
857                    'libtool_tag' => 'FC',
858                    'pure' => 1,
859                    'extensions' => ['.F90','.F95']);
861 # Preprocessed Fortran 77
863 # The current support for preprocessing Fortran 77 just involves
864 # passing `$(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS)
865 # $(CPPFLAGS)' as additional flags to the Fortran 77 compiler, since
866 # this is how GNU Make does it; see the `GNU Make Manual, Edition 0.51
867 # for `make' Version 3.76 Beta' (specifically, from info file
868 # `(make)Catalogue of Rules').
870 # A better approach would be to write an Autoconf test
871 # (i.e. AC_PROG_FPP) for a Fortran 77 preprocessor, because not all
872 # Fortran 77 compilers know how to do preprocessing.  The Autoconf
873 # macro AC_PROG_FPP should test the Fortran 77 compiler first for
874 # preprocessing capabilities, and then fall back on cpp (if cpp were
875 # available).
876 register_language ('name' => 'ppf77',
877                    'Name' => 'Preprocessed Fortran 77',
878                    'config_vars' => ['F77'],
879                    'linker' => 'F77LINK',
880                    'link' => '$(F77LD) $(AM_FFLAGS) $(FFLAGS) $(AM_LDFLAGS) $(LDFLAGS) -o $@',
881                    'lder' => 'F77LD',
882                    'ld' => '$(F77)',
883                    'flags' => ['FFLAGS', 'CPPFLAGS'],
884                    'compiler' => 'PPF77COMPILE',
885                    'compile' => '$(F77) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_FFLAGS) $(FFLAGS)',
886                    'compile_flag' => '-c',
887                    'output_flag' => '-o',
888                    'libtool_tag' => 'F77',
889                    'pure' => 1,
890                    'extensions' => ['.F']);
892 # Ratfor.
893 register_language ('name' => 'ratfor',
894                    'Name' => 'Ratfor',
895                    'config_vars' => ['F77'],
896                    'linker' => 'F77LINK',
897                    'link' => '$(F77LD) $(AM_FFLAGS) $(FFLAGS) $(AM_LDFLAGS) $(LDFLAGS) -o $@',
898                    'lder' => 'F77LD',
899                    'ld' => '$(F77)',
900                    'flags' => ['RFLAGS', 'FFLAGS'],
901                    # FIXME also FFLAGS.
902                    'compile' => '$(F77) $(AM_FFLAGS) $(FFLAGS) $(AM_RFLAGS) $(RFLAGS)',
903                    'compiler' => 'RCOMPILE',
904                    'compile_flag' => '-c',
905                    'output_flag' => '-o',
906                    'libtool_tag' => 'F77',
907                    'pure' => 1,
908                    'extensions' => ['.r']);
910 # Java via gcj.
911 register_language ('name' => 'java',
912                    'Name' => 'Java',
913                    'config_vars' => ['GCJ'],
914                    'linker' => 'GCJLINK',
915                    'link' => '$(GCJLD) $(AM_GCJFLAGS) $(GCJFLAGS) $(AM_LDFLAGS) $(LDFLAGS) -o $@',
916                    'autodep' => 'GCJ',
917                    'flags' => ['GCJFLAGS'],
918                    'compile' => '$(GCJ) $(AM_GCJFLAGS) $(GCJFLAGS)',
919                    'compiler' => 'GCJCOMPILE',
920                    'compile_flag' => '-c',
921                    'output_flag' => '-o',
922                    'libtool_tag' => 'GCJ',
923                    'lder' => 'GCJLD',
924                    'ld' => '$(GCJ)',
925                    'pure' => 1,
926                    'extensions' => ['.java', '.class', '.zip', '.jar']);
928 ################################################################
930 # Error reporting functions.
932 # err_am ($MESSAGE, [%OPTIONS])
933 # -----------------------------
934 # Uncategorized errors about the current Makefile.am.
935 sub err_am ($;%)
937   msg_am ('error', @_);
940 # err_ac ($MESSAGE, [%OPTIONS])
941 # -----------------------------
942 # Uncategorized errors about configure.ac.
943 sub err_ac ($;%)
945   msg_ac ('error', @_);
948 # msg_am ($CHANNEL, $MESSAGE, [%OPTIONS])
949 # ---------------------------------------
950 # Messages about about the current Makefile.am.
951 sub msg_am ($$;%)
953   my ($channel, $msg, %opts) = @_;
954   msg $channel, "${am_file}.am", $msg, %opts;
957 # msg_ac ($CHANNEL, $MESSAGE, [%OPTIONS])
958 # ---------------------------------------
959 # Messages about about configure.ac.
960 sub msg_ac ($$;%)
962   my ($channel, $msg, %opts) = @_;
963   msg $channel, $configure_ac, $msg, %opts;
966 ################################################################
968 # subst ($TEXT)
969 # -------------
970 # Return a configure-style substitution using the indicated text.
971 # We do this to avoid having the substitutions directly in automake.in;
972 # when we do that they are sometimes removed and this causes confusion
973 # and bugs.
974 sub subst ($)
976     my ($text) = @_;
977     return '@' . $text . '@';
980 ################################################################
983 # $BACKPATH
984 # &backname ($REL-DIR)
985 # --------------------
986 # If I `cd $REL-DIR', then to come back, I should `cd $BACKPATH'.
987 # For instance `src/foo' => `../..'.
988 # Works with non strictly increasing paths, i.e., `src/../lib' => `..'.
989 sub backname ($)
991     my ($file) = @_;
992     my @res;
993     foreach (split (/\//, $file))
994     {
995         next if $_ eq '.' || $_ eq '';
996         if ($_ eq '..')
997         {
998             pop @res;
999         }
1000         else
1001         {
1002             push (@res, '..');
1003         }
1004     }
1005     return join ('/', @res) || '.';
1008 ################################################################
1011 # Handle AUTOMAKE_OPTIONS variable.  Return 1 on error, 0 otherwise.
1012 sub handle_options
1014   my $var = var ('AUTOMAKE_OPTIONS');
1015   if ($var)
1016     {
1017       # FIXME: We should disallow conditional definitions of AUTOMAKE_OPTIONS.
1018       if (process_option_list ($var->rdef (TRUE)->location,
1019                                $var->value_as_list_recursive (cond_filter =>
1020                                                               TRUE)))
1021         {
1022           return 1;
1023         }
1024     }
1026   if ($strictness == GNITS)
1027     {
1028       set_option ('readme-alpha', INTERNAL);
1029       set_option ('std-options', INTERNAL);
1030       set_option ('check-news', INTERNAL);
1031     }
1033   return 0;
1036 # shadow_unconditionally ($varname, $where)
1037 # -----------------------------------------
1038 # Return a $(variable) that contains all possible values
1039 # $varname can take.
1040 # If the VAR wasn't defined conditionally, return $(VAR).
1041 # Otherwise we create a am__VAR_DIST variable which contains
1042 # all possible values, and return $(am__VAR_DIST).
1043 sub shadow_unconditionally ($$)
1045   my ($varname, $where) = @_;
1046   my $var = var $varname;
1047   if ($var->has_conditional_contents)
1048     {
1049       $varname = "am__${varname}_DIST";
1050       my @files = uniq ($var->value_as_list_recursive);
1051       define_pretty_variable ($varname, TRUE, $where, @files);
1052     }
1053   return "\$($varname)"
1056 # get_object_extension ($OUT)
1057 # ---------------------------
1058 # Return object extension.  Just once, put some code into the output.
1059 # OUT is the name of the output file
1060 sub get_object_extension
1062     my ($out) = @_;
1064     # Maybe require libtool library object files.
1065     my $extension = '.$(OBJEXT)';
1066     $extension = '.lo' if ($out =~ /\.la$/);
1068     # Check for automatic de-ANSI-fication.
1069     $extension = '$U' . $extension
1070       if option 'ansi2knr';
1072     $get_object_extension_was_run = 1;
1074     return $extension;
1078 # Call finish function for each language that was used.
1079 sub handle_languages
1081     if (! option 'no-dependencies')
1082     {
1083         # Include auto-dep code.  Don't include it if DEP_FILES would
1084         # be empty.
1085         if (&saw_sources_p (0) && keys %dep_files)
1086         {
1087             # Set location of depcomp.
1088             &define_variable ('depcomp',
1089                               "\$(SHELL) $am_config_aux_dir/depcomp",
1090                               INTERNAL);
1091             &define_variable ('am__depfiles_maybe', 'depfiles', INTERNAL);
1093             require_conf_file ("$am_file.am", FOREIGN, 'depcomp');
1095             my @deplist = sort keys %dep_files;
1096             # Generate each `include' individually.  Irix 6 make will
1097             # not properly include several files resulting from a
1098             # variable expansion; generating many separate includes
1099             # seems safest.
1100             $output_rules .= "\n";
1101             foreach my $iter (@deplist)
1102             {
1103                 $output_rules .= (subst ('AMDEP_TRUE')
1104                                   . subst ('am__include')
1105                                   . ' '
1106                                   . subst ('am__quote')
1107                                   . $iter
1108                                   . subst ('am__quote')
1109                                   . "\n");
1110             }
1112             # Compute the set of directories to remove in distclean-depend.
1113             my @depdirs = uniq (map { dirname ($_) } @deplist);
1114             $output_rules .= &file_contents ('depend',
1115                                              new Automake::Location,
1116                                              DEPDIRS => "@depdirs");
1117         }
1118     }
1119     else
1120     {
1121         &define_variable ('depcomp', '', INTERNAL);
1122         &define_variable ('am__depfiles_maybe', '', INTERNAL);
1123     }
1125     my %done;
1127     # Is the c linker needed?
1128     my $needs_c = 0;
1129     foreach my $ext (sort keys %extension_seen)
1130     {
1131         next unless $extension_map{$ext};
1133         my $lang = $languages{$extension_map{$ext}};
1135         my $rule_file = $lang->rule_file || 'depend2';
1137         # Get information on $LANG.
1138         my $pfx = $lang->autodep;
1139         my $fpfx = ($pfx eq '') ? 'CC' : $pfx;
1141         my ($AMDEP, $FASTDEP) =
1142           (option 'no-dependencies' || $lang->autodep eq 'no')
1143           ? ('FALSE', 'FALSE') : ('AMDEP', "am__fastdep$fpfx");
1145         my %transform = ('EXT'     => $ext,
1146                          'PFX'     => $pfx,
1147                          'FPFX'    => $fpfx,
1148                          'AMDEP'   => $AMDEP,
1149                          'FASTDEP' => $FASTDEP,
1150                          '-c'      => $lang->compile_flag || '',
1151                          'MORE-THAN-ONE'
1152                                    => (count_files_for_language ($lang->name) > 1),
1153                          # These are not used, but they need to be defined
1154                          # so &transform do not complain.
1155                          SUBDIROBJ     => 0,
1156                          'DERIVED-EXT' => 'BUG',
1157                          DIST_SOURCE   => 1,
1158                         );
1160         # Generate the appropriate rules for this extension.
1161         if (((! option 'no-dependencies') && $lang->autodep ne 'no')
1162             || defined $lang->compile)
1163         {
1164             # Some C compilers don't support -c -o.  Use it only if really
1165             # needed.
1166             my $output_flag = $lang->output_flag || '';
1167             $output_flag = '-o'
1168               if (! $output_flag
1169                   && $lang->name eq 'c'
1170                   && option 'subdir-objects');
1172             # Compute a possible derived extension.
1173             # This is not used by depend2.am.
1174             my $der_ext = (&{$lang->output_extensions} ($ext))[0];
1176             # When we output an inference rule like `.c.o:' we
1177             # have two cases to consider: either subdir-objects
1178             # is used, or it is not.
1179             #
1180             # In the latter case the rule is used to build objects
1181             # in the current directory, and dependencies always
1182             # go into `./$(DEPDIR)/'.  We can hard-code this value.
1183             #
1184             # In the former case the rule can be used to build
1185             # objects in sub-directories too.  Dependencies should
1186             # go into the appropriate sub-directories, e.g.,
1187             # `sub/$(DEPDIR)/'.  The value of this directory
1188             # need the be computed on-the-fly.
1189             #
1190             # DEPBASE holds the name of this directory, plus the
1191             # basename part of the object file (extensions Po, TPo,
1192             # Plo, TPlo will be added later as appropriate).  It is
1193             # either hardcoded, or a shell variable (`$depbase') that
1194             # will be computed by the rule.
1195             my $depbase =
1196               option ('subdir-objects') ? '$$depbase' : '$(DEPDIR)/$*';
1197             $output_rules .=
1198               file_contents ($rule_file,
1199                              new Automake::Location,
1200                              %transform,
1201                              GENERIC   => 1,
1203                              'DERIVED-EXT' => $der_ext,
1205                              DEPBASE   => $depbase,
1206                              BASE      => '$*',
1207                              SOURCE    => '$<',
1208                              OBJ       => '$@',
1209                              OBJOBJ    => '$@',
1210                              LTOBJ     => '$@',
1212                              COMPILE   => '$(' . $lang->compiler . ')',
1213                              LTCOMPILE => '$(LT' . $lang->compiler . ')',
1214                              -o        => $output_flag,
1215                              SUBDIROBJ => !! option 'subdir-objects');
1216         }
1218         # Now include code for each specially handled object with this
1219         # language.
1220         my %seen_files = ();
1221         foreach my $file (@{$lang_specific_files{$lang->name}})
1222         {
1223             my ($derived, $source, $obj, $myext, %file_transform) = @$file;
1225             # We might see a given object twice, for instance if it is
1226             # used under different conditions.
1227             next if defined $seen_files{$obj};
1228             $seen_files{$obj} = 1;
1230             prog_error ("found " . $lang->name .
1231                         " in handle_languages, but compiler not defined")
1232               unless defined $lang->compile;
1234             my $obj_compile = $lang->compile;
1236             # Rewrite each occurrence of `AM_$flag' in the compile
1237             # rule into `${derived}_$flag' if it exists.
1238             for my $flag (@{$lang->flags})
1239               {
1240                 my $val = "${derived}_$flag";
1241                 $obj_compile =~ s/\(AM_$flag\)/\($val\)/
1242                   if set_seen ($val);
1243               }
1245             my $libtool_tag = '';
1246             if ($lang->libtool_tag && exists $libtool_tags{$lang->libtool_tag})
1247               {
1248                 $libtool_tag = '--tag=' . $lang->libtool_tag . ' '
1249               }
1251             my $obj_ltcompile =
1252               '$(LIBTOOL) --mode=compile ' . $libtool_tag . $obj_compile;
1254             # We _need_ `-o' for per object rules.
1255             my $output_flag = $lang->output_flag || '-o';
1257             my $depbase = dirname ($obj);
1258             $depbase = ''
1259                 if $depbase eq '.';
1260             $depbase .= '/'
1261                 unless $depbase eq '';
1262             $depbase .= '$(DEPDIR)/' . basename ($obj);
1264             # Support for deansified files in subdirectories is ugly
1265             # enough to deserve an explanation.
1266             #
1267             # A Note about normal ansi2knr processing first.  On
1268             #
1269             #   AUTOMAKE_OPTIONS = ansi2knr
1270             #   bin_PROGRAMS = foo
1271             #   foo_SOURCES = foo.c
1272             #
1273             # we generate rules similar to:
1274             #
1275             #   foo: foo$U.o; link ...
1276             #   foo$U.o: foo$U.c; compile ...
1277             #   foo_.c: foo.c; ansi2knr ...
1278             #
1279             # this is fairly compact, and will call ansi2knr depending
1280             # on the value of $U (`' or `_').
1281             #
1282             # It's harder with subdir sources. On
1283             #
1284             #   AUTOMAKE_OPTIONS = ansi2knr
1285             #   bin_PROGRAMS = foo
1286             #   foo_SOURCES = sub/foo.c
1287             #
1288             # we have to create foo_.c in the current directory.
1289             # (Unless the user asks 'subdir-objects'.)  This is important
1290             # in case the same file (`foo.c') is compiled from other
1291             # directories with different cpp options: foo_.c would
1292             # be preprocessed for only one set of options if it were
1293             # put in the subdirectory.
1294             #
1295             # Because foo$U.o must be built from either foo_.c or
1296             # sub/foo.c we can't be as concise as in the first example.
1297             # Instead we output
1298             #
1299             #   foo: foo$U.o; link ...
1300             #   foo_.o: foo_.c; compile ...
1301             #   foo.o: sub/foo.c; compile ...
1302             #   foo_.c: foo.c; ansi2knr ...
1303             #
1304             # This is why we'll now transform $rule_file twice
1305             # if we detect this case.
1306             # A first time we output the compile rule with `$U'
1307             # replaced by `_' and the source directory removed,
1308             # and another time we simply remove `$U'.
1309             #
1310             # Note that at this point $source (as computed by
1311             # &handle_single_transform) is `sub/foo$U.c'.
1312             # This can be confusing: it can be used as-is when
1313             # subdir-objects is set, otherwise you have to know
1314             # it really means `foo_.c' or `sub/foo.c'.
1315             my $objdir = dirname ($obj);
1316             my $srcdir = dirname ($source);
1317             if ($lang->ansi && $obj =~ /\$U/)
1318               {
1319                 prog_error "`$obj' contains \$U, but `$source' doesn't."
1320                   if $source !~ /\$U/;
1322                 (my $source_ = $source) =~ s/\$U/_/g;
1323                 # Output an additional rule if _.c and .c are not in
1324                 # the same directory.  (_.c is always in $objdir.)
1325                 if ($objdir ne $srcdir)
1326                   {
1327                     (my $obj_ = $obj) =~ s/\$U/_/g;
1328                     (my $depbase_ = $depbase) =~ s/\$U/_/g;
1329                     $source_ = basename ($source_);
1331                     $output_rules .=
1332                       file_contents ($rule_file,
1333                                      new Automake::Location,
1334                                      %transform,
1335                                      GENERIC   => 0,
1337                                      DEPBASE   => $depbase_,
1338                                      BASE      => $obj_,
1339                                      SOURCE    => $source_,
1340                                      OBJ       => "$obj_$myext",
1341                                      OBJOBJ    => "$obj_.obj",
1342                                      LTOBJ     => "$obj_.lo",
1344                                      COMPILE   => $obj_compile,
1345                                      LTCOMPILE => $obj_ltcompile,
1346                                      -o        => $output_flag,
1347                                      %file_transform);
1348                     $obj =~ s/\$U//g;
1349                     $depbase =~ s/\$U//g;
1350                     $source =~ s/\$U//g;
1351                   }
1352               }
1354             $output_rules .=
1355               file_contents ($rule_file,
1356                              new Automake::Location,
1357                              %transform,
1358                              GENERIC   => 0,
1360                              DEPBASE   => $depbase,
1361                              BASE      => $obj,
1362                              SOURCE    => $source,
1363                              # Use $myext and not `.o' here, in case
1364                              # we are actually building a new source
1365                              # file -- e.g. via yacc.
1366                              OBJ       => "$obj$myext",
1367                              OBJOBJ    => "$obj.obj",
1368                              LTOBJ     => "$obj.lo",
1370                              COMPILE   => $obj_compile,
1371                              LTCOMPILE => $obj_ltcompile,
1372                              -o        => $output_flag,
1373                              %file_transform);
1374         }
1376         # The rest of the loop is done once per language.
1377         next if defined $done{$lang};
1378         $done{$lang} = 1;
1380         # Load the language dependent Makefile chunks.
1381         my %lang = map { uc ($_) => 0 } keys %languages;
1382         $lang{uc ($lang->name)} = 1;
1383         $output_rules .= file_contents ('lang-compile',
1384                                         new Automake::Location,
1385                                         %transform, %lang);
1387         # If the source to a program consists entirely of code from a
1388         # `pure' language, for instance C++ for Fortran 77, then we
1389         # don't need the C compiler code.  However if we run into
1390         # something unusual then we do generate the C code.  There are
1391         # probably corner cases here that do not work properly.
1392         # People linking Java code to Fortran code deserve pain.
1393         $needs_c ||= ! $lang->pure;
1395         define_compiler_variable ($lang)
1396           if ($lang->compile);
1398         define_linker_variable ($lang)
1399           if ($lang->link);
1401         require_variables ("$am_file.am", $lang->Name . " source seen",
1402                            TRUE, @{$lang->config_vars});
1404         # Call the finisher.
1405         $lang->finish;
1407         # Flags listed in `->flags' are user variables (per GNU Standards),
1408         # they should not be overridden in the Makefile...
1409         my @dont_override = @{$lang->flags};
1410         # ... and so is LDFLAGS.
1411         push @dont_override, 'LDFLAGS' if $lang->link;
1413         foreach my $flag (@dont_override)
1414           {
1415             my $var = var $flag;
1416             if ($var)
1417               {
1418                 for my $cond ($var->conditions->conds)
1419                   {
1420                     if ($var->rdef ($cond)->owner == VAR_MAKEFILE)
1421                       {
1422                         msg_cond_var ('gnu', $cond, $flag,
1423                                       "`$flag' is a user variable, "
1424                                       . "you should not override it;\n"
1425                                       . "use `AM_$flag' instead.");
1426                       }
1427                   }
1428               }
1429           }
1430     }
1432     # If the project is entirely C++ or entirely Fortran 77 (i.e., 1
1433     # suffix rule was learned), don't bother with the C stuff.  But if
1434     # anything else creeps in, then use it.
1435     $needs_c = 1
1436       if $need_link || suffix_rules_count > 1;
1438     if ($needs_c)
1439       {
1440         &define_compiler_variable ($languages{'c'})
1441           unless defined $done{$languages{'c'}};
1442         define_linker_variable ($languages{'c'});
1443       }
1446 # Check to make sure a source defined in LIBOBJS is not explicitly
1447 # mentioned.  This is a separate function (as opposed to being inlined
1448 # in handle_source_transform) because it isn't always appropriate to
1449 # do this check.
1450 sub check_libobjs_sources
1452   my ($one_file, $unxformed) = @_;
1454   foreach my $prefix ('', 'EXTRA_', 'dist_', 'nodist_',
1455                       'dist_EXTRA_', 'nodist_EXTRA_')
1456     {
1457       my @files;
1458       my $varname = $prefix . $one_file . '_SOURCES';
1459       my $var = var ($varname);
1460       if ($var)
1461         {
1462           @files = $var->value_as_list_recursive;
1463         }
1464       elsif ($prefix eq '')
1465         {
1466           @files = ($unxformed . '.c');
1467         }
1468       else
1469         {
1470           next;
1471         }
1473       foreach my $file (@files)
1474         {
1475           err_var ($prefix . $one_file . '_SOURCES',
1476                    "automatically discovered file `$file' should not" .
1477                    " be explicitly mentioned")
1478             if defined $libsources{$file};
1479         }
1480     }
1484 # @OBJECTS
1485 # handle_single_transform ($VAR, $TOPPARENT, $DERIVED, $OBJ, $FILE, %TRANSFORM)
1486 # -----------------------------------------------------------------------------
1487 # Does much of the actual work for handle_source_transform.
1488 # Arguments are:
1489 #   $VAR is the name of the variable that the source filenames come from
1490 #   $TOPPARENT is the name of the _SOURCES variable which is being processed
1491 #   $DERIVED is the name of resulting executable or library
1492 #   $OBJ is the object extension (e.g., `$U.lo')
1493 #   $FILE the source file to transform
1494 #   %TRANSFORM contains extras arguments to pass to file_contents
1495 #     when producing explicit rules
1496 # Result is a list of the names of objects
1497 # %linkers_used will be updated with any linkers needed
1498 sub handle_single_transform ($$$$$%)
1500     my ($var, $topparent, $derived, $obj, $_file, %transform) = @_;
1501     my @files = ($_file);
1502     my @result = ();
1503     my $nonansi_obj = $obj;
1504     $nonansi_obj =~ s/\$U//g;
1506     # Turn sources into objects.  We use a while loop like this
1507     # because we might add to @files in the loop.
1508     while (scalar @files > 0)
1509     {
1510         $_ = shift @files;
1512         # Configure substitutions in _SOURCES variables are errors.
1513         if (/^\@.*\@$/)
1514         {
1515           my $parent_msg = '';
1516           $parent_msg = "\nand is referred to from `$topparent'"
1517             if $topparent ne $var->name;
1518           err_var ($var,
1519                    "`" . $var->name . "' includes configure substitution `$_'"
1520                    . $parent_msg . ";\nconfigure " .
1521                    "substitutions are not allowed in _SOURCES variables");
1522           next;
1523         }
1525         # If the source file is in a subdirectory then the `.o' is put
1526         # into the current directory, unless the subdir-objects option
1527         # is in effect.
1529         # Split file name into base and extension.
1530         next if ! /^(?:(.*)\/)?([^\/]*)($KNOWN_EXTENSIONS_PATTERN)$/;
1531         my $full = $_;
1532         my $directory = $1 || '';
1533         my $base = $2;
1534         my $extension = $3;
1536         # We must generate a rule for the object if it requires its own flags.
1537         my $renamed = 0;
1538         my ($linker, $object);
1540         # This records whether we've seen a derived source file (e.g.
1541         # yacc output).
1542         my $derived_source = 0;
1544         # This holds the `aggregate context' of the file we are
1545         # currently examining.  If the file is compiled with
1546         # per-object flags, then it will be the name of the object.
1547         # Otherwise it will be `AM'.  This is used by the target hook
1548         # language function.
1549         my $aggregate = 'AM';
1551         $extension = &derive_suffix ($extension, $nonansi_obj);
1552         my $lang;
1553         if ($extension_map{$extension} &&
1554             ($lang = $languages{$extension_map{$extension}}))
1555         {
1556             # Found the language, so see what it says.
1557             &saw_extension ($extension);
1559             # Do we have per-executable flags for this executable?
1560             my $have_per_exec_flags = 0;
1561             foreach my $flag (@{$lang->flags})
1562               {
1563                 if (set_seen ("${derived}_$flag"))
1564                   {
1565                     $have_per_exec_flags = 1;
1566                     last;
1567                   }
1568               }
1570             # Note: computed subr call.  The language rewrite function
1571             # should return one of the LANG_* constants.  It could
1572             # also return a list whose first value is such a constant
1573             # and whose second value is a new source extension which
1574             # should be applied.  This means this particular language
1575             # generates another source file which we must then process
1576             # further.
1577             my $subr = \&{'lang_' . $lang->name . '_rewrite'};
1578             my ($r, $source_extension)
1579                 = &$subr ($directory, $base, $extension,
1580                           $nonansi_obj, $have_per_exec_flags, $var);
1581             # Skip this entry if we were asked not to process it.
1582             next if $r == LANG_IGNORE;
1584             # Now extract linker and other info.
1585             $linker = $lang->linker;
1587             my $this_obj_ext;
1588             if (defined $source_extension)
1589             {
1590                 $this_obj_ext = $source_extension;
1591                 $derived_source = 1;
1592             }
1593             elsif ($lang->ansi)
1594             {
1595                 $this_obj_ext = $obj;
1596             }
1597             else
1598             {
1599                 $this_obj_ext = $nonansi_obj;
1600             }
1601             $object = $base . $this_obj_ext;
1603             if ($have_per_exec_flags)
1604             {
1605                 # We have a per-executable flag in effect for this
1606                 # object.  In this case we rewrite the object's
1607                 # name to ensure it is unique.
1609                 # We choose the name `DERIVED_OBJECT' to ensure
1610                 # (1) uniqueness, and (2) continuity between
1611                 # invocations.  However, this will result in a
1612                 # name that is too long for losing systems, in
1613                 # some situations.  So we provide _SHORTNAME to
1614                 # override.
1616                 my $dname = $derived;
1617                 my $var = var ($derived . '_SHORTNAME');
1618                 if ($var)
1619                 {
1620                     # FIXME: should use the same Condition as
1621                     # the _SOURCES variable.  But this is really
1622                     # silly overkill -- nobody should have
1623                     # conditional shortnames.
1624                     $dname = $var->variable_value;
1625                 }
1626                 $object = $dname . '-' . $object;
1628                 prog_error ($lang->name . " flags defined without compiler")
1629                   if ! defined $lang->compile;
1631                 $renamed = 1;
1632             }
1634             # If rewrite said it was ok, put the object into a
1635             # subdir.
1636             if ($r == LANG_SUBDIR && $directory ne '')
1637             {
1638                 $object = $directory . '/' . $object;
1639             }
1641             # If the object file has been renamed (because per-target
1642             # flags are used) we cannot compile the file with an
1643             # inference rule: we need an explicit rule.
1644             #
1645             # If the source is in a subdirectory and the object is in
1646             # the current directory, we also need an explicit rule.
1647             #
1648             # If both source and object files are in a subdirectory
1649             # (this happens when the subdir-objects option is used),
1650             # then the inference will work.
1651             #
1652             # The latter case deserves a historical note.  When the
1653             # subdir-objects option was added on 1999-04-11 it was
1654             # thought that inferences rules would work for
1655             # subdirectory objects too.  Later, on 1999-11-22,
1656             # automake was changed to output explicit rules even for
1657             # subdir-objects.  Nobody remembers why, but this occured
1658             # soon after the merge of the user-dep-gen-branch so it
1659             # might be related.  In late 2003 people complained about
1660             # the size of the generated Makefile.ins (libgcj, with
1661             # 2200+ subdir objects was reported to have a 9MB
1662             # Makefile), so we now rely on inference rules again.
1663             # Maybe we'll run across the same issue as in the past,
1664             # but at least this time we can document it.  However since
1665             # dependency tracking has evolved it is possible that
1666             # our old problem no longer exists.
1667             # Using inference rules for subdir-objects has been tested
1668             # with GNU make, Solaris make, Ultrix make, BSD make,
1669             # HP-UX make, and OSF1 make successfully.
1670             if ($renamed
1671                 || ($directory ne '' && ! option 'subdir-objects')
1672                 # We must also use specific rules for a nodist_ source
1673                 # if its language requests it.
1674                 || ($lang->nodist_specific && ! $transform{'DIST_SOURCE'}))
1675             {
1676                 my $obj_sans_ext = substr ($object, 0,
1677                                            - length ($this_obj_ext));
1678                 my $full_ansi = $full;
1679                 if ($lang->ansi && option 'ansi2knr')
1680                   {
1681                     $full_ansi =~ s/$KNOWN_EXTENSIONS_PATTERN$/\$U$&/;
1682                     $obj_sans_ext .= '$U';
1683                   }
1685                 my @specifics = ($full_ansi, $obj_sans_ext,
1686                                  # Only use $this_obj_ext in the derived
1687                                  # source case because in the other case we
1688                                  # *don't* want $(OBJEXT) to appear here.
1689                                  ($derived_source ? $this_obj_ext : '.o'));
1691                 # If we renamed the object then we want to use the
1692                 # per-executable flag name.  But if this is simply a
1693                 # subdir build then we still want to use the AM_ flag
1694                 # name.
1695                 if ($renamed)
1696                   {
1697                     unshift @specifics, $derived;
1698                     $aggregate = $derived;
1699                   }
1700                 else
1701                   {
1702                     unshift @specifics, 'AM';
1703                   }
1705                 # Each item on this list is a reference to a list consisting
1706                 # of four values followed by additional transform flags for
1707                 # file_contents.   The four values are the derived flag prefix
1708                 # (e.g. for `foo_CFLAGS', it is `foo'), the name of the
1709                 # source file, the base name of the output file, and
1710                 # the extension for the object file.
1711                 push (@{$lang_specific_files{$lang->name}},
1712                       [@specifics, %transform]);
1713             }
1714         }
1715         elsif ($extension eq $nonansi_obj)
1716         {
1717             # This is probably the result of a direct suffix rule.
1718             # In this case we just accept the rewrite.
1719             $object = "$base$extension";
1720             $linker = '';
1721         }
1722         else
1723         {
1724             # No error message here.  Used to have one, but it was
1725             # very unpopular.
1726             # FIXME: we could potentially do more processing here,
1727             # perhaps treating the new extension as though it were a
1728             # new source extension (as above).  This would require
1729             # more restructuring than is appropriate right now.
1730             next;
1731         }
1733         err_am "object `$object' created by `$full' and `$object_map{$object}'"
1734           if (defined $object_map{$object}
1735               && $object_map{$object} ne $full);
1737         my $comp_val = (($object =~ /\.lo$/)
1738                         ? COMPILE_LIBTOOL : COMPILE_ORDINARY);
1739         (my $comp_obj = $object) =~ s/\.lo$/.\$(OBJEXT)/;
1740         if (defined $object_compilation_map{$comp_obj}
1741             && $object_compilation_map{$comp_obj} != 0
1742             # Only see the error once.
1743             && ($object_compilation_map{$comp_obj}
1744                 != (COMPILE_LIBTOOL | COMPILE_ORDINARY))
1745             && $object_compilation_map{$comp_obj} != $comp_val)
1746           {
1747             err_am "object `$comp_obj' created both with libtool and without";
1748           }
1749         $object_compilation_map{$comp_obj} |= $comp_val;
1751         if (defined $lang)
1752         {
1753             # Let the language do some special magic if required.
1754             $lang->target_hook ($aggregate, $object, $full, %transform);
1755         }
1757         if ($derived_source)
1758           {
1759             prog_error ($lang->name . " has automatic dependency tracking")
1760               if $lang->autodep ne 'no';
1761             # Make sure this new source file is handled next.  That will
1762             # make it appear to be at the right place in the list.
1763             unshift (@files, $object);
1764             # Distribute derived sources unless the source they are
1765             # derived from is not.
1766             &push_dist_common ($object)
1767               unless ($topparent =~ /^(?:nobase_)?nodist_/);
1768             next;
1769           }
1771         $linkers_used{$linker} = 1;
1773         push (@result, $object);
1775         if (! defined $object_map{$object})
1776         {
1777             my @dep_list = ();
1778             $object_map{$object} = $full;
1780             # If resulting object is in subdir, we need to make
1781             # sure the subdir exists at build time.
1782             if ($object =~ /\//)
1783             {
1784                 # FIXME: check that $DIRECTORY is somewhere in the
1785                 # project
1787                 # For Java, the way we're handling it right now, a
1788                 # `..' component doesn't make sense.
1789                 if ($lang->name eq 'java' && $object =~ /(\/|^)\.\.\//)
1790                   {
1791                     err_am "`$full' should not contain a `..' component";
1792                   }
1794                 # Make sure object is removed by `make mostlyclean'.
1795                 $compile_clean_files{$object} = MOSTLY_CLEAN;
1796                 # If we have a libtool object then we also must remove
1797                 # the ordinary .o.
1798                 if ($object =~ /\.lo$/)
1799                 {
1800                     (my $xobj = $object) =~ s,lo$,\$(OBJEXT),;
1801                     $compile_clean_files{$xobj} = MOSTLY_CLEAN;
1803                     # Remove any libtool object in this directory.
1804                     $libtool_clean_directories{$directory} = 1;
1805                 }
1807                 push (@dep_list, require_build_directory ($directory));
1809                 # If we're generating dependencies, we also want
1810                 # to make sure that the appropriate subdir of the
1811                 # .deps directory is created.
1812                 push (@dep_list,
1813                       require_build_directory ($directory . '/$(DEPDIR)'))
1814                   unless option 'no-dependencies';
1815             }
1817             &pretty_print_rule ($object . ':', "\t", @dep_list)
1818                 if scalar @dep_list > 0;
1819         }
1821         # Transform .o or $o file into .P file (for automatic
1822         # dependency code).
1823         if ($lang && $lang->autodep ne 'no')
1824         {
1825             my $depfile = $object;
1826             $depfile =~ s/\.([^.]*)$/.P$1/;
1827             $depfile =~ s/\$\(OBJEXT\)$/o/;
1828             $dep_files{dirname ($depfile) . '/$(DEPDIR)/'
1829                            . basename ($depfile)} = 1;
1830         }
1831     }
1833     return @result;
1837 # $LINKER
1838 # define_objects_from_sources ($VAR, $OBJVAR, $NODEFINE, $ONE_FILE,
1839 #                              $OBJ, $PARENT, $TOPPARENT, $WHERE, %TRANSFORM)
1840 # ---------------------------------------------------------------------------
1841 # Define an _OBJECTS variable for a _SOURCES variable (or subvariable)
1843 # Arguments are:
1844 #   $VAR is the name of the _SOURCES variable
1845 #   $OBJVAR is the name of the _OBJECTS variable if known (otherwise
1846 #     it will be generated and returned).
1847 #   $NODEFINE is a boolean: if true, $OBJVAR will not be defined (but
1848 #     work done to determine the linker will be).
1849 #   $ONE_FILE is the canonical (transformed) name of object to build
1850 #   $OBJ is the object extension (i.e. either `.o' or `.lo').
1851 #   $TOPPARENT is the _SOURCES variable being processed.
1852 #   $WHERE context into which this definition is done
1853 #   %TRANSFORM extra arguments to pass to file_contents when producing
1854 #     rules
1856 # Result is a pair ($LINKER, $OBJVAR):
1857 #    $LINKER is a boolean, true if a linker is needed to deal with the objects
1858 sub define_objects_from_sources ($$$$$$$%)
1860   my ($var, $objvar, $nodefine, $one_file,
1861       $obj, $topparent, $where, %transform) = @_;
1863   my $needlinker = "";
1865   transform_variable_recursively
1866     ($var, $objvar, 'am__objects', $nodefine, $where,
1867      # The transform code to run on each filename.
1868      sub {
1869        my ($subvar, $val, $cond, $full_cond) = @_;
1870        my @trans = handle_single_transform ($subvar, $topparent,
1871                                             $one_file, $obj, $val,
1872                                             %transform);
1873        $needlinker = "true" if @trans;
1874        return @trans;
1875      });
1877   return $needlinker;
1881 # handle_source_transform ($CANON_TARGET, $TARGET, $OBJEXT, $WHERE, %TRANSFORM)
1882 # -----------------------------------------------------------------------------
1883 # Handle SOURCE->OBJECT transform for one program or library.
1884 # Arguments are:
1885 #   canonical (transformed) name of target to build
1886 #   actual target of object to build
1887 #   object extension (i.e. either `.o' or `$o'.
1888 #   location of the source variable
1889 #   extra arguments to pass to file_contents when producing rules
1890 # Return result is name of linker variable that must be used.
1891 # Empty return means just use `LINK'.
1892 sub handle_source_transform ($$$$%)
1894     # one_file is canonical name.  unxformed is given name.  obj is
1895     # object extension.
1896     my ($one_file, $unxformed, $obj, $where, %transform) = @_;
1898     my ($linker) = '';
1900     # No point in continuing if _OBJECTS is defined.
1901     return if reject_var ($one_file . '_OBJECTS',
1902                           $one_file . '_OBJECTS should not be defined');
1904     my %used_pfx = ();
1905     my $needlinker;
1906     %linkers_used = ();
1907     foreach my $prefix ('', 'EXTRA_', 'dist_', 'nodist_',
1908                         'dist_EXTRA_', 'nodist_EXTRA_')
1909     {
1910         my $varname = $prefix . $one_file . "_SOURCES";
1911         my $var = var $varname;
1912         next unless $var;
1914         # We are going to define _OBJECTS variables using the prefix.
1915         # Then we glom them all together.  So we can't use the null
1916         # prefix here as we need it later.
1917         my $xpfx = ($prefix eq '') ? 'am_' : $prefix;
1919         # Keep track of which prefixes we saw.
1920         $used_pfx{$xpfx} = 1
1921           unless $prefix =~ /EXTRA_/;
1923         push @sources, "\$($varname)";
1924         push @dist_sources, shadow_unconditionally ($varname, $where)
1925           unless (option ('no-dist') || $prefix =~ /^nodist_/);
1927         $needlinker |=
1928             define_objects_from_sources ($varname,
1929                                          $xpfx . $one_file . '_OBJECTS',
1930                                          $prefix =~ /EXTRA_/,
1931                                          $one_file, $obj, $varname, $where,
1932                                          DIST_SOURCE => ($prefix !~ /^nodist_/),
1933                                          %transform);
1934     }
1935     if ($needlinker)
1936     {
1937         $linker ||= &resolve_linker (%linkers_used);
1938     }
1940     my @keys = sort keys %used_pfx;
1941     if (scalar @keys == 0)
1942     {
1943         # The default source for libfoo.la is libfoo.c, but for
1944         # backward compatibility we first look at libfoo_la.c
1945         my $old_default_source = "$one_file.c";
1946         (my $default_source = $unxformed) =~ s,(\.[^./\\]*)?$,.c,;
1947         if ($old_default_source ne $default_source
1948             && (rule $old_default_source
1949                 || rule '$(srcdir)/' . $old_default_source
1950                 || rule '${srcdir}/' . $old_default_source
1951                 || -f $old_default_source))
1952           {
1953             my $loc = $where->clone;
1954             $loc->pop_context;
1955             msg ('obsolete', $loc,
1956                  "the default source for `$unxformed' has been changed "
1957                  . "to `$default_source'.\n(Using `$old_default_source' for "
1958                  . "backward compatibility.)");
1959             $default_source = $old_default_source;
1960           }
1961         # If a rule exists to build this source with a $(srcdir)
1962         # prefix, use that prefix in our variables too.  This is for
1963         # the sake of BSD Make.
1964         if (rule '$(srcdir)/' . $default_source
1965             || rule '${srcdir}/' . $default_source)
1966           {
1967             $default_source = '$(srcdir)/' . $default_source;
1968           }
1970         &define_variable ($one_file . "_SOURCES", $default_source, $where);
1971         push (@sources, $default_source);
1972         push (@dist_sources, $default_source);
1974         %linkers_used = ();
1975         my (@result) =
1976           handle_single_transform ($one_file . '_SOURCES',
1977                                    $one_file . '_SOURCES',
1978                                    $one_file, $obj,
1979                                    $default_source, %transform);
1980         $linker ||= &resolve_linker (%linkers_used);
1981         define_pretty_variable ($one_file . '_OBJECTS', TRUE, $where, @result);
1982     }
1983     else
1984     {
1985         @keys = map { '$(' . $_ . $one_file . '_OBJECTS)' } @keys;
1986         define_pretty_variable ($one_file . '_OBJECTS', TRUE, $where, @keys);
1987     }
1989     # If we want to use `LINK' we must make sure it is defined.
1990     if ($linker eq '')
1991     {
1992         $need_link = 1;
1993     }
1995     return $linker;
1999 # handle_lib_objects ($XNAME, $VAR)
2000 # ---------------------------------
2001 # Special-case ALLOCA and LIBOBJS substitutions in _LDADD or _LIBADD variables.
2002 # Also, generate _DEPENDENCIES variable if appropriate.
2003 # Arguments are:
2004 #   transformed name of object being built, or empty string if no object
2005 #   name of _LDADD/_LIBADD-type variable to examine
2006 # Returns 1 if LIBOBJS seen, 0 otherwise.
2007 sub handle_lib_objects
2009   my ($xname, $varname) = @_;
2011   my $var = var ($varname);
2012   prog_error "handle_lib_objects: `$varname' undefined"
2013     unless $var;
2014   prog_error "handle_lib_objects: unexpected variable name `$varname'"
2015     unless $varname =~ /^(.*)(?:LIB|LD)ADD$/;
2016   my $prefix = $1 || 'AM_';
2018   my $seen_libobjs = 0;
2019   my $flagvar = 0;
2021   transform_variable_recursively
2022     ($varname, $xname . '_DEPENDENCIES', 'am__DEPENDENCIES',
2023      ! $xname, INTERNAL,
2024      # Transformation function, run on each filename.
2025      sub {
2026        my ($subvar, $val, $cond, $full_cond) = @_;
2028        if ($val =~ /^-/)
2029          {
2030            # Skip -lfoo and -Ldir silently; these are explicitly allowed.
2031            if ($val !~ /^-[lL]/ &&
2032                # Skip -dlopen and -dlpreopen; these are explicitly allowed
2033                # for Libtool libraries or programs.  (Actually we are a bit
2034                # laxest here since this code also applies to non-libtool
2035                # libraries or programs, for which -dlopen and -dlopreopen
2036                # are pure non-sence.  Diagnosting this doesn't seems very
2037                # important: the developer will quickly get complaints from
2038                # the linker.)
2039                $val !~ /^-dl(?:pre)?open$/ &&
2040                # Only get this error once.
2041                ! $flagvar)
2042              {
2043                $flagvar = 1;
2044                # FIXME: should display a stack of nested variables
2045                # as context when $var != $subvar.
2046                err_var ($var, "linker flags such as `$val' belong in "
2047                         . "`${prefix}LDFLAGS");
2048              }
2049            return ();
2050          }
2051        elsif ($val !~ /^\@.*\@$/)
2052          {
2053            # Assume we have a file of some sort, and output it into the
2054            # dependency variable.  Autoconf substitutions are not output;
2055            # rarely is a new dependency substituted into e.g. foo_LDADD
2056            # -- but bad things (e.g. -lX11) are routinely substituted.
2057            # Note that LIBOBJS and ALLOCA are exceptions to this rule,
2058            # and handled specially below.
2059            return $val;
2060          }
2061        elsif ($val =~ /^\@(LT)?LIBOBJS\@$/)
2062          {
2063            handle_LIBOBJS ($subvar, $cond, $1);
2064            $seen_libobjs = 1;
2065            return $val;
2066          }
2067        elsif ($val =~ /^\@(LT)?ALLOCA\@$/)
2068          {
2069            handle_ALLOCA ($subvar, $cond, $1);
2070            return $val;
2071          }
2072        else
2073          {
2074            return ();
2075          }
2076      });
2078   return $seen_libobjs;
2081 sub handle_LIBOBJS ($$$)
2083   my ($var, $cond, $lt) = @_;
2084   $lt ||= '';
2085   my $myobjext = ($1 ? 'l' : '') . 'o';
2087   $var->requires_variables ("\@${lt}LIBOBJS\@ used", $lt . 'LIBOBJS')
2088     if ! keys %libsources;
2090   foreach my $iter (keys %libsources)
2091     {
2092       if ($iter =~ /\.[cly]$/)
2093         {
2094           &saw_extension ($&);
2095           &saw_extension ('.c');
2096         }
2098       if ($iter =~ /\.h$/)
2099         {
2100           require_file_with_macro ($cond, $var, FOREIGN, $iter);
2101         }
2102       elsif ($iter ne 'alloca.c')
2103         {
2104           my $rewrite = $iter;
2105           $rewrite =~ s/\.c$/.P$myobjext/;
2106           $dep_files{'$(DEPDIR)/' . $rewrite} = 1;
2107           $rewrite = "^" . quotemeta ($iter) . "\$";
2108           # Only require the file if it is not a built source.
2109           my $bs = var ('BUILT_SOURCES');
2110           if (! $bs || ! grep (/$rewrite/, $bs->value_as_list_recursive))
2111             {
2112               require_file_with_macro ($cond, $var, FOREIGN, $iter);
2113             }
2114         }
2115     }
2118 sub handle_ALLOCA ($$$)
2120   my ($var, $cond, $lt) = @_;
2121   my $myobjext = ($lt ? 'l' : '') . 'o';
2122   $lt ||= '';
2123   $var->requires_variables ("\@${lt}ALLOCA\@ used", $lt . 'ALLOCA');
2124   $dep_files{'$(DEPDIR)/alloca.P' . $myobjext} = 1;
2125   require_file_with_macro ($cond, $var, FOREIGN, 'alloca.c');
2126   &saw_extension ('c');
2129 # Canonicalize the input parameter
2130 sub canonicalize
2132     my ($string) = @_;
2133     $string =~ tr/A-Za-z0-9_\@/_/c;
2134     return $string;
2137 # Canonicalize a name, and check to make sure the non-canonical name
2138 # is never used.  Returns canonical name.  Arguments are name and a
2139 # list of suffixes to check for.
2140 sub check_canonical_spelling
2142   my ($name, @suffixes) = @_;
2144   my $xname = &canonicalize ($name);
2145   if ($xname ne $name)
2146     {
2147       foreach my $xt (@suffixes)
2148         {
2149           reject_var ("$name$xt", "use `$xname$xt', not `$name$xt'");
2150         }
2151     }
2153   return $xname;
2157 # handle_compile ()
2158 # -----------------
2159 # Set up the compile suite.
2160 sub handle_compile ()
2162     return
2163       unless $get_object_extension_was_run;
2165     # Boilerplate.
2166     my $default_includes = '';
2167     if (! option 'nostdinc')
2168       {
2169         $default_includes = ' -I. -I$(srcdir)';
2171         my $var = var 'CONFIG_HEADER';
2172         if ($var)
2173           {
2174             foreach my $hdr (split (' ', $var->variable_value))
2175               {
2176                 $default_includes .= ' -I' . dirname ($hdr);
2177               }
2178           }
2179       }
2181     my (@mostly_rms, @dist_rms);
2182     foreach my $item (sort keys %compile_clean_files)
2183     {
2184         if ($compile_clean_files{$item} == MOSTLY_CLEAN)
2185         {
2186             push (@mostly_rms, "\t-rm -f $item");
2187         }
2188         elsif ($compile_clean_files{$item} == DIST_CLEAN)
2189         {
2190             push (@dist_rms, "\t-rm -f $item");
2191         }
2192         else
2193         {
2194           prog_error 'invalid entry in %compile_clean_files';
2195         }
2196     }
2198     my ($coms, $vars, $rules) =
2199       &file_contents_internal (1, "$libdir/am/compile.am",
2200                                new Automake::Location,
2201                                ('DEFAULT_INCLUDES' => $default_includes,
2202                                 'MOSTLYRMS' => join ("\n", @mostly_rms),
2203                                 'DISTRMS' => join ("\n", @dist_rms)));
2204     $output_vars .= $vars;
2205     $output_rules .= "$coms$rules";
2207     # Check for automatic de-ANSI-fication.
2208     if (option 'ansi2knr')
2209       {
2210         my ($ansi2knr_filename, $ansi2knr_where) = @{option 'ansi2knr'};
2211         my $ansi2knr_dir = '';
2213         require_variables ($ansi2knr_where, "option `ansi2knr' is used",
2214                            TRUE, "ANSI2KNR", "U");
2216         # topdir is where ansi2knr should be.
2217         if ($ansi2knr_filename eq 'ansi2knr')
2218           {
2219             # Only require ansi2knr files if they should appear in
2220             # this directory.
2221             require_file ($ansi2knr_where, FOREIGN,
2222                           'ansi2knr.c', 'ansi2knr.1');
2224             # ansi2knr needs to be built before subdirs, so unshift it.
2225             unshift (@all, '$(ANSI2KNR)');
2226           }
2227         else
2228           {
2229             $ansi2knr_dir = dirname ($ansi2knr_filename);
2230           }
2232         $output_rules .= &file_contents ('ansi2knr',
2233                                          new Automake::Location,
2234                                          'ANSI2KNR-DIR' => $ansi2knr_dir);
2236     }
2239 # handle_libtool ()
2240 # -----------------
2241 # Handle libtool rules.
2242 sub handle_libtool
2244   return unless var ('LIBTOOL');
2246   # Libtool requires some files, but only at top level.
2247   # (Starting with Libtool 2.0 we do not have to bother.  These
2248   # requirements are done with AC_REQUIRE_AUX_FILE.)
2249   require_conf_file_with_macro (TRUE, 'LIBTOOL', FOREIGN, @libtool_files)
2250     if $relative_dir eq '.' && ! $libtool_new_api;
2252   my @libtool_rms;
2253   foreach my $item (sort keys %libtool_clean_directories)
2254     {
2255       my $dir = ($item eq '.') ? '' : "$item/";
2256       # .libs is for Unix, _libs for DOS.
2257       push (@libtool_rms, "\t-rm -rf ${dir}.libs ${dir}_libs");
2258     }
2260   # Output the libtool compilation rules.
2261   $output_rules .= &file_contents ('libtool',
2262                                    new Automake::Location,
2263                                    LTRMS => join ("\n", @libtool_rms));
2266 # handle_programs ()
2267 # ------------------
2268 # Handle C programs.
2269 sub handle_programs
2271   my @proglist = &am_install_var ('progs', 'PROGRAMS',
2272                                   'bin', 'sbin', 'libexec', 'pkglib',
2273                                   'noinst', 'check');
2274   return if ! @proglist;
2276   my $seen_global_libobjs =
2277     var ('LDADD') && &handle_lib_objects ('', 'LDADD');
2279   foreach my $pair (@proglist)
2280     {
2281       my ($where, $one_file) = @$pair;
2283       my $seen_libobjs = 0;
2284       my $obj = &get_object_extension ($one_file);
2286       # Strip any $(EXEEXT) suffix the user might have added, or this
2287       # will confuse &handle_source_transform and &check_canonical_spelling.
2288       # We'll add $(EXEEXT) back later anyway.
2289       $one_file =~ s/\$\(EXEEXT\)$//;
2291       # Canonicalize names and check for misspellings.
2292       my $xname = &check_canonical_spelling ($one_file, '_LDADD', '_LDFLAGS',
2293                                              '_SOURCES', '_OBJECTS',
2294                                              '_DEPENDENCIES');
2296       $where->push_context ("while processing program `$one_file'");
2297       $where->set (INTERNAL->get);
2299       my $linker = &handle_source_transform ($xname, $one_file, $obj, $where,
2300                                              NONLIBTOOL => 1, LIBTOOL => 0);
2302       if (var ($xname . "_LDADD"))
2303         {
2304           $seen_libobjs = &handle_lib_objects ($xname, $xname . '_LDADD');
2305         }
2306       else
2307         {
2308           # User didn't define prog_LDADD override.  So do it.
2309           &define_variable ($xname . '_LDADD', '$(LDADD)', $where);
2311           # This does a bit too much work.  But we need it to
2312           # generate _DEPENDENCIES when appropriate.
2313           if (var ('LDADD'))
2314             {
2315               $seen_libobjs = &handle_lib_objects ($xname, 'LDADD');
2316             }
2317         }
2319       reject_var ($xname . '_LIBADD',
2320                   "use `${xname}_LDADD', not `${xname}_LIBADD'");
2322       set_seen ($xname . '_DEPENDENCIES');
2323       set_seen ($xname . '_LDFLAGS');
2325       # Determine program to use for link.
2326       my $xlink;
2327       if (var ($xname . '_LINK'))
2328         {
2329           $xlink = $xname . '_LINK';
2330         }
2331       else
2332         {
2333           $xlink = $linker ? $linker : 'LINK';
2334         }
2336       # If the resulting program lies into a subdirectory,
2337       # make sure this directory will exist.
2338       my $dirstamp = require_build_directory_maybe ($one_file);
2340       $output_rules .= &file_contents ('program',
2341                                        $where,
2342                                        PROGRAM  => $one_file,
2343                                        XPROGRAM => $xname,
2344                                        XLINK    => $xlink,
2345                                        DIRSTAMP => $dirstamp,
2346                                        EXEEXT   => '$(EXEEXT)');
2348       if ($seen_libobjs || $seen_global_libobjs)
2349         {
2350           if (var ($xname . '_LDADD'))
2351             {
2352               &check_libobjs_sources ($xname, $xname . '_LDADD');
2353             }
2354           elsif (var ('LDADD'))
2355             {
2356               &check_libobjs_sources ($xname, 'LDADD');
2357             }
2358         }
2359     }
2363 # handle_libraries ()
2364 # -------------------
2365 # Handle libraries.
2366 sub handle_libraries
2368   my @liblist = &am_install_var ('libs', 'LIBRARIES',
2369                                  'lib', 'pkglib', 'noinst', 'check');
2370   return if ! @liblist;
2372   my @prefix = am_primary_prefixes ('LIBRARIES', 0, 'lib', 'pkglib',
2373                                     'noinst', 'check');
2375   if (@prefix)
2376     {
2377       my $var = rvar ($prefix[0] . '_LIBRARIES');
2378       $var->requires_variables ('library used', 'RANLIB');
2379     }
2381   &define_variable ('AR', 'ar', INTERNAL);
2382   &define_variable ('ARFLAGS', 'cru', INTERNAL);
2384   foreach my $pair (@liblist)
2385     {
2386       my ($where, $onelib) = @$pair;
2388       my $seen_libobjs = 0;
2389       # Check that the library fits the standard naming convention.
2390       my $bn = basename ($onelib);
2391       if ($bn !~ /^lib.*\.a$/)
2392         {
2393           $bn =~ s/^(?:lib)?(.*?)(?:\.[^.]*)?$/lib$1.a/;
2394           my $suggestion = dirname ($onelib) . "/$bn";
2395           $suggestion =~ s|^\./||g;
2396           msg ('error-gnu/warn', $where,
2397                "`$onelib' is not a standard library name\n"
2398                . "did you mean `$suggestion'?")
2399         }
2401       $where->push_context ("while processing library `$onelib'");
2402       $where->set (INTERNAL->get);
2404       my $obj = &get_object_extension ($onelib);
2406       # Canonicalize names and check for misspellings.
2407       my $xlib = &check_canonical_spelling ($onelib, '_LIBADD', '_SOURCES',
2408                                             '_OBJECTS', '_DEPENDENCIES',
2409                                             '_AR');
2411       if (! var ($xlib . '_AR'))
2412         {
2413           &define_variable ($xlib . '_AR', '$(AR) $(ARFLAGS)', $where);
2414         }
2416       # Generate support for conditional object inclusion in
2417       # libraries.
2418       if (var ($xlib . '_LIBADD'))
2419         {
2420           if (&handle_lib_objects ($xlib, $xlib . '_LIBADD'))
2421             {
2422               $seen_libobjs = 1;
2423             }
2424         }
2425       else
2426         {
2427           &define_variable ($xlib . "_LIBADD", '', $where);
2428         }
2430       reject_var ($xlib . '_LDADD',
2431                   "use `${xlib}_LIBADD', not `${xlib}_LDADD'");
2433       # Make sure we at look at this.
2434       set_seen ($xlib . '_DEPENDENCIES');
2436       &handle_source_transform ($xlib, $onelib, $obj, $where,
2437                                 NONLIBTOOL => 1, LIBTOOL => 0);
2439       # If the resulting library lies into a subdirectory,
2440       # make sure this directory will exist.
2441       my $dirstamp = require_build_directory_maybe ($onelib);
2443       $output_rules .= &file_contents ('library',
2444                                        $where,
2445                                        LIBRARY  => $onelib,
2446                                        XLIBRARY => $xlib,
2447                                        DIRSTAMP => $dirstamp);
2449       if ($seen_libobjs)
2450         {
2451           if (var ($xlib . '_LIBADD'))
2452             {
2453               &check_libobjs_sources ($xlib, $xlib . '_LIBADD');
2454             }
2455         }
2456     }
2460 # handle_ltlibraries ()
2461 # ---------------------
2462 # Handle shared libraries.
2463 sub handle_ltlibraries
2465   my @liblist = &am_install_var ('ltlib', 'LTLIBRARIES',
2466                                  'noinst', 'lib', 'pkglib', 'check');
2467   return if ! @liblist;
2469   my @prefix = am_primary_prefixes ('LTLIBRARIES', 0, 'lib', 'pkglib',
2470                                     'noinst', 'check');
2472   if (@prefix)
2473     {
2474       my $var = rvar ($prefix[0] . '_LTLIBRARIES');
2475       $var->requires_variables ('Libtool library used', 'LIBTOOL');
2476     }
2478   my %instdirs = ();
2479   my %instconds = ();
2480   my %liblocations = ();        # Location (in Makefile.am) of each library.
2482   foreach my $key (@prefix)
2483     {
2484       # Get the installation directory of each library.
2485       (my $dir = $key) =~ s/^nobase_//;
2486       my $var = rvar ($key . '_LTLIBRARIES');
2488       # We reject libraries which are installed in several places
2489       # in the same condition, because we can only specify one
2490       # `-rpath' option.
2491       $var->traverse_recursively
2492         (sub
2493          {
2494            my ($var, $val, $cond, $full_cond) = @_;
2495            my $hcond = $full_cond->human;
2496            my $where = $var->rdef ($cond)->location;
2497            # A library cannot be installed in different directory
2498            # in overlapping conditions.
2499            if (exists $instconds{$val})
2500              {
2501                my ($msg, $acond) =
2502                  $instconds{$val}->ambiguous_p ($val, $full_cond);
2504                if ($msg)
2505                  {
2506                    error ($where, $msg, partial => 1);
2508                    my $dirtxt = "installed in `$dir'";
2509                    $dirtxt = "built for `$dir'"
2510                      if $dir eq 'EXTRA' || $dir eq 'noinst' || $dir eq 'check';
2511                    my $dircond =
2512                      $full_cond->true ? "" : " in condition $hcond";
2514                    error ($where, "`$val' should be $dirtxt$dircond ...",
2515                           partial => 1);
2517                    my $hacond = $acond->human;
2518                    my $adir = $instdirs{$val}{$acond};
2519                    my $adirtxt = "installed in `$adir'";
2520                    $adirtxt = "built for `$adir'"
2521                      if ($adir eq 'EXTRA' || $adir eq 'noinst'
2522                          || $adir eq 'check');
2523                    my $adircond = $acond->true ? "" : " in condition $hacond";
2525                    my $onlyone = ($dir ne $adir) ?
2526                      ("\nLibtool libraries can be built for only one "
2527                       . "destination.") : "";
2529                    error ($liblocations{$val}{$acond},
2530                           "... and should also be $adirtxt$adircond.$onlyone");
2531                    return;
2532                  }
2533              }
2534            else
2535              {
2536                $instconds{$val} = new Automake::DisjConditions;
2537              }
2538            $instdirs{$val}{$full_cond} = $dir;
2539            $liblocations{$val}{$full_cond} = $where;
2540            $instconds{$val} = $instconds{$val}->merge ($full_cond);
2541          },
2542          sub
2543          {
2544            return ();
2545          },
2546          skip_ac_subst => 1);
2547     }
2549   foreach my $pair (@liblist)
2550     {
2551       my ($where, $onelib) = @$pair;
2553       my $seen_libobjs = 0;
2554       my $obj = &get_object_extension ($onelib);
2556       # Canonicalize names and check for misspellings.
2557       my $xlib = &check_canonical_spelling ($onelib, '_LIBADD', '_LDFLAGS',
2558                                             '_SOURCES', '_OBJECTS',
2559                                             '_DEPENDENCIES');
2561       # Check that the library fits the standard naming convention.
2562       my $libname_rx = '^lib.*\.la';
2563       my $ldvar = var ("${xlib}_LDFLAGS") || var ('AM_LDFLAGS');
2564       my $ldvar2 = var ('LDFLAGS');
2565       if (($ldvar && grep (/-module/, $ldvar->value_as_list_recursive))
2566           || ($ldvar2 && grep (/-module/, $ldvar2->value_as_list_recursive)))
2567         {
2568           # Relax name checking for libtool modules.
2569           $libname_rx = '\.la';
2570         }
2572       my $bn = basename ($onelib);
2573       if ($bn !~ /$libname_rx$/)
2574         {
2575           my $type = 'library';
2576           if ($libname_rx eq '\.la')
2577             {
2578               $bn =~ s/^(lib|)(.*?)(?:\.[^.]*)?$/$1$2.la/;
2579               $type = 'module';
2580             }
2581           else
2582             {
2583               $bn =~ s/^(?:lib)?(.*?)(?:\.[^.]*)?$/lib$1.la/;
2584             }
2585           my $suggestion = dirname ($onelib) . "/$bn";
2586           $suggestion =~ s|^\./||g;
2587           msg ('error-gnu/warn', $where,
2588                "`$onelib' is not a standard libtool $type name\n"
2589                . "did you mean `$suggestion'?")
2590         }
2592       $where->push_context ("while processing Libtool library `$onelib'");
2593       $where->set (INTERNAL->get);
2595       # Make sure we look at these.
2596       set_seen ($xlib . '_LDFLAGS');
2597       set_seen ($xlib . '_DEPENDENCIES');
2599       # Generate support for conditional object inclusion in
2600       # libraries.
2601       if (var ($xlib . '_LIBADD'))
2602         {
2603           if (&handle_lib_objects ($xlib, $xlib . '_LIBADD'))
2604             {
2605               $seen_libobjs = 1;
2606             }
2607         }
2608       else
2609         {
2610           &define_variable ($xlib . "_LIBADD", '', $where);
2611         }
2613       reject_var ("${xlib}_LDADD",
2614                   "use `${xlib}_LIBADD', not `${xlib}_LDADD'");
2617       my $linker = &handle_source_transform ($xlib, $onelib, $obj, $where,
2618                                              NONLIBTOOL => 0, LIBTOOL => 1);
2620       # Determine program to use for link.
2621       my $xlink;
2622       if (var ($xlib . '_LINK'))
2623         {
2624           $xlink = $xlib . '_LINK';
2625         }
2626       else
2627         {
2628           $xlink = $linker ? $linker : 'LINK';
2629         }
2631       my $rpathvar = "am_${xlib}_rpath";
2632       my $rpath = "\$($rpathvar)";
2633       foreach my $rcond ($instconds{$onelib}->conds)
2634         {
2635           my $val;
2636           if ($instdirs{$onelib}{$rcond} eq 'EXTRA'
2637               || $instdirs{$onelib}{$rcond} eq 'noinst'
2638               || $instdirs{$onelib}{$rcond} eq 'check')
2639             {
2640               # It's an EXTRA_ library, so we can't specify -rpath,
2641               # because we don't know where the library will end up.
2642               # The user probably knows, but generally speaking automake
2643               # doesn't -- and in fact configure could decide
2644               # dynamically between two different locations.
2645               $val = '';
2646             }
2647           else
2648             {
2649               $val = ('-rpath $(' . $instdirs{$onelib}{$rcond} . 'dir)');
2650             }
2651           if ($rcond->true)
2652             {
2653               # If $rcond is true there is only one condition and
2654               # there is no point defining an helper variable.
2655               $rpath = $val;
2656             }
2657           else
2658             {
2659               define_pretty_variable ($rpathvar, $rcond, INTERNAL, $val);
2660             }
2661         }
2663       # If the resulting library lies into a subdirectory,
2664       # make sure this directory will exist.
2665       my $dirstamp = require_build_directory_maybe ($onelib);
2667       # Remember to cleanup .libs/ in this directory.
2668       my $dirname = dirname $onelib;
2669       $libtool_clean_directories{$dirname} = 1;
2671       $output_rules .= &file_contents ('ltlibrary',
2672                                        $where,
2673                                        LTLIBRARY  => $onelib,
2674                                        XLTLIBRARY => $xlib,
2675                                        RPATH      => $rpath,
2676                                        XLINK      => $xlink,
2677                                        DIRSTAMP   => $dirstamp);
2678       if ($seen_libobjs)
2679         {
2680           if (var ($xlib . '_LIBADD'))
2681             {
2682               &check_libobjs_sources ($xlib, $xlib . '_LIBADD');
2683             }
2684         }
2685     }
2688 # See if any _SOURCES variable were misspelled.
2689 sub check_typos ()
2691   # It is ok if the user sets this particular variable.
2692   set_seen 'AM_LDFLAGS';
2694   foreach my $primary ('SOURCES', 'LIBADD', 'LDADD', 'LDFLAGS', 'DEPENDENCIES')
2695     {
2696       foreach my $var (variables $primary)
2697         {
2698           my $varname = $var->name;
2699           # A configure variable is always legitimate.
2700           next if exists $configure_vars{$varname};
2702           for my $cond ($var->conditions->conds)
2703             {
2704               $varname =~ /^(?:nobase_)?(?:dist_|nodist_)?(.*)_[[:alnum:]]+$/;
2705               msg_var ('syntax', $var, "variable `$varname' is defined but no"
2706                        . " program or\nlibrary has `$1' as canonic name"
2707                        . " (possible typo)")
2708                 unless $var->rdef ($cond)->seen;
2709             }
2710         }
2711     }
2715 # Handle scripts.
2716 sub handle_scripts
2718     # NOTE we no longer automatically clean SCRIPTS, because it is
2719     # useful to sometimes distribute scripts verbatim.  This happens
2720     # e.g. in Automake itself.
2721     &am_install_var ('-candist', 'scripts', 'SCRIPTS',
2722                      'bin', 'sbin', 'libexec', 'pkgdata',
2723                      'noinst', 'check');
2729 ## ------------------------ ##
2730 ## Handling Texinfo files.  ##
2731 ## ------------------------ ##
2733 # ($OUTFILE, $VFILE, @CLEAN_FILES)
2734 # &scan_texinfo_file ($FILENAME)
2735 # ------------------------------
2736 # $OUTFILE     - name of the info file produced by $FILENAME.
2737 # $VFILE       - name of the version.texi file used (undef if none).
2738 # @CLEAN_FILES - list of byproducts (indexes etc.)
2739 sub scan_texinfo_file ($)
2741   my ($filename) = @_;
2743   # Some of the following extensions are always created, no matter
2744   # whether indexes are used or not.  Other (like cps, fns, ... pgs)
2745   # are only created when they are used.  We used to scan $FILENAME
2746   # for their use, but that is not enough: they could be used in
2747   # included files.  We can't scan included files because we don't
2748   # know the include path.  Therefore we always erase these files, no
2749   # matter whether they are used or not.
2750   #
2751   # (tmp is only created if an @macro is used and a certain e-TeX
2752   # feature is not available.)
2753   my %clean_suffixes =
2754     map { $_ => 1 } (qw(aux log toc tmp
2755                         cp cps
2756                         fn fns
2757                         ky kys
2758                         vr vrs
2759                         tp tps
2760                         pg pgs)); # grep 'new.*index' texinfo.tex
2762   my $texi = new Automake::XFile "< $filename";
2763   verb "reading $filename";
2765   my ($outfile, $vfile);
2766   while ($_ = $texi->getline)
2767     {
2768       if (/^\@setfilename +(\S+)/)
2769         {
2770           # Honor only the first @setfilename.  (It's possible to have
2771           # more occurrences later if the manual shows examples of how
2772           # to use @setfilename...)
2773           next if $outfile;
2775           $outfile = $1;
2776           if ($outfile =~ /\.(.+)$/ && $1 ne 'info')
2777             {
2778               error ("$filename:$.",
2779                      "output `$outfile' has unrecognized extension");
2780               return;
2781             }
2782         }
2783       # A "version.texi" file is actually any file whose name matches
2784       # "vers*.texi".
2785       elsif (/^\@include\s+(vers[^.]*\.texi)\s*$/)
2786         {
2787           $vfile = $1;
2788         }
2790       # Try to find new or unused indexes.
2792       # Creating a new category of index.
2793       elsif (/^\@def(code)?index (\w+)/)
2794         {
2795           $clean_suffixes{$2} = 1;
2796           $clean_suffixes{"$2s"} = 1;
2797         }
2799       # Merging an index into an another.
2800       elsif (/^\@syn(code)?index (\w+) (\w+)/)
2801         {
2802           delete $clean_suffixes{"$2s"};
2803           $clean_suffixes{"$3s"} = 1;
2804         }
2806     }
2808   if (! $outfile)
2809     {
2810       err_am "`$filename' missing \@setfilename";
2811       return;
2812     }
2814   my $infobase = basename ($filename);
2815   $infobase =~ s/\.te?xi(nfo)?$//;
2816   return ($outfile, $vfile,
2817           map { "$infobase.$_" } (sort keys %clean_suffixes));
2821 # ($DIRSTAMP, @CLEAN_FILES)
2822 # output_texinfo_build_rules ($SOURCE, $DEST, $INSRC, @DEPENDENCIES)
2823 # ------------------------------------------------------------------
2824 # SOURCE - the source Texinfo file
2825 # DEST - the destination Info file
2826 # INSRC - wether DEST should be built in the source tree
2827 # DEPENDENCIES - known dependencies
2828 sub output_texinfo_build_rules ($$$@)
2830   my ($source, $dest, $insrc, @deps) = @_;
2832   # Split `a.texi' into `a' and `.texi'.
2833   my ($spfx, $ssfx) = ($source =~ /^(.*?)(\.[^.]*)?$/);
2834   my ($dpfx, $dsfx) = ($dest =~ /^(.*?)(\.[^.]*)?$/);
2836   $ssfx ||= "";
2837   $dsfx ||= "";
2839   # We can output two kinds of rules: the "generic" rules use Make
2840   # suffix rules and are appropriate when $source and $dest do not lie
2841   # in a sub-directory; the "specific" rules are needed in the other
2842   # case.
2843   #
2844   # The former are output only once (this is not really apparent here,
2845   # but just remember that some logic deeper in Automake will not
2846   # output the same rule twice); while the later need to be output for
2847   # each Texinfo source.
2848   my $generic;
2849   my $makeinfoflags;
2850   my $sdir = dirname $source;
2851   if ($sdir eq '.' && dirname ($dest) eq '.')
2852     {
2853       $generic = 1;
2854       $makeinfoflags = '-I $(srcdir)';
2855     }
2856   else
2857     {
2858       $generic = 0;
2859       $makeinfoflags = "-I $sdir -I \$(srcdir)/$sdir";
2860     }
2862   # A directory can contain two kinds of info files: some built in the
2863   # source tree, and some built in the build tree.  The rules are
2864   # different in each case.  However we cannot output two different
2865   # set of generic rules.  Because in-source builds are more usual, we
2866   # use generic rules in this case and fall back to "specific" rules
2867   # for build-dir builds.  (It should not be a problem to invert this
2868   # if needed.)
2869   $generic = 0 unless $insrc;
2871   # We cannot use a suffix rule to build info files with an empty
2872   # extension.  Otherwise we would output a single suffix inference
2873   # rule, with separate dependencies, as in
2874   #
2875   #    .texi:
2876   #             $(MAKEINFO) ...
2877   #    foo.info: foo.texi
2878   #
2879   # which confuse Solaris make.  (See the Autoconf manual for
2880   # details.)  Therefore we use a specific rule in this case.  This
2881   # applies to info files only (dvi and pdf files always have an
2882   # extension).
2883   my $generic_info = ($generic && $dsfx) ? 1 : 0;
2885   # If the resulting file lie into a subdirectory,
2886   # make sure this directory will exist.
2887   my $dirstamp = require_build_directory_maybe ($dest);
2889   my $dipfx = ($insrc ? '$(srcdir)/' : '') . $dpfx;
2891   $output_rules .= file_contents ('texibuild',
2892                                   new Automake::Location,
2893                                   DEPS             => "@deps",
2894                                   DEST_PREFIX      => $dpfx,
2895                                   DEST_INFO_PREFIX => $dipfx,
2896                                   DEST_SUFFIX      => $dsfx,
2897                                   DIRSTAMP         => $dirstamp,
2898                                   GENERIC          => $generic,
2899                                   GENERIC_INFO     => $generic_info,
2900                                   INSRC            => $insrc,
2901                                   MAKEINFOFLAGS    => $makeinfoflags,
2902                                   SOURCE           => ($generic
2903                                                        ? '$<' : $source),
2904                                   SOURCE_INFO      => ($generic_info
2905                                                        ? '$<' : $source),
2906                                   SOURCE_REAL      => $source,
2907                                   SOURCE_SUFFIX    => $ssfx,
2908                                   );
2909   return ($dirstamp, "$dpfx.dvi", "$dpfx.pdf", "$dpfx.ps", "$dpfx.html");
2913 # $TEXICLEANS
2914 # handle_texinfo_helper ($info_texinfos)
2915 # --------------------------------------
2916 # Handle all Texinfo source; helper for handle_texinfo.
2917 sub handle_texinfo_helper ($)
2919   my ($info_texinfos) = @_;
2920   my (@infobase, @info_deps_list, @texi_deps);
2921   my %versions;
2922   my $done = 0;
2923   my @texi_cleans;
2925   # Build a regex matching user-cleaned files.
2926   my $d = var 'DISTCLEANFILES';
2927   my $c = var 'CLEANFILES';
2928   my @f = ();
2929   push @f, $d->value_as_list_recursive (inner_expand => 1) if $d;
2930   push @f, $c->value_as_list_recursive (inner_expand => 1) if $c;
2931   @f = map { s|[^A-Za-z_0-9*\[\]\-]|\\$&|g; s|\*|[^/]*|g; $_; } @f;
2932   my $user_cleaned_files = '^(?:' . join ('|', @f) . ')$';
2934   foreach my $texi
2935       ($info_texinfos->value_as_list_recursive (inner_expand => 1))
2936     {
2937       my $infobase = $texi;
2938       $infobase =~ s/\.(txi|texinfo|texi)$//;
2940       if ($infobase eq $texi)
2941         {
2942           # FIXME: report line number.
2943           err_am "texinfo file `$texi' has unrecognized extension";
2944           next;
2945         }
2947       push @infobase, $infobase;
2949       # If 'version.texi' is referenced by input file, then include
2950       # automatic versioning capability.
2951       my ($out_file, $vtexi, @clean_files) =
2952         scan_texinfo_file ("$relative_dir/$texi")
2953         or next;
2954       push (@texi_cleans, @clean_files);
2956       # If the Texinfo source is in a subdirectory, create the
2957       # resulting info in this subdirectory.  If it is in the current
2958       # directory, try hard to not prefix "./" because it breaks the
2959       # generic rules.
2960       my $outdir = dirname ($texi) . '/';
2961       $outdir = "" if $outdir eq './';
2962       $out_file =  $outdir . $out_file;
2964       # Until Automake 1.6.3, .info files were built in the
2965       # source tree.  This was an obstacle to the support of
2966       # non-distributed .info files, and non-distributed .texi
2967       # files.
2968       #
2969       # * Non-distributed .texi files is important in some packages
2970       #   where .texi files are built at make time, probably using
2971       #   other binaries built in the package itself, maybe using
2972       #   tools or information found on the build host.  Because
2973       #   these files are not distributed they are always rebuilt
2974       #   at make time; they should therefore not lie in the source
2975       #   directory.  One plan was to support this using
2976       #   nodist_info_TEXINFOS or something similar.  (Doing this
2977       #   requires some sanity checks.  For instance Automake should
2978       #   not allow:
2979       #      dist_info_TEXINFO = foo.texi
2980       #      nodist_foo_TEXINFO = included.texi
2981       #   because a distributed file should never depend on a
2982       #   non-distributed file.)
2983       #
2984       # * If .texi files are not distributed, then .info files should
2985       #   not be distributed either.  There are also cases where one
2986       #   want to distribute .texi files, but do not want to
2987       #   distribute the .info files.  For instance the Texinfo package
2988       #   distributes the tool used to build these files; it would
2989       #   be a waste of space to distribute them.  It's not clear
2990       #   which syntax we should use to indicate that .info files should
2991       #   not be distributed.  Akim Demaille suggested that eventually
2992       #   we switch to a new syntax:
2993       #   |  Maybe we should take some inspiration from what's already
2994       #   |  done in the rest of Automake.  Maybe there is too much
2995       #   |  syntactic sugar here, and you want
2996       #   |     nodist_INFO = bar.info
2997       #   |     dist_bar_info_SOURCES = bar.texi
2998       #   |     bar_texi_DEPENDENCIES = foo.texi
2999       #   |  with a bit of magic to have bar.info represent the whole
3000       #   |  bar*info set.  That's a lot more verbose that the current
3001       #   |  situation, but it is # not new, hence the user has less
3002       #   |  to learn.
3003       #   |
3004       #   |  But there is still too much room for meaningless specs:
3005       #   |     nodist_INFO = bar.info
3006       #   |     dist_bar_info_SOURCES = bar.texi
3007       #   |     dist_PS = bar.ps something-written-by-hand.ps
3008       #   |     nodist_bar_ps_SOURCES = bar.texi
3009       #   |     bar_texi_DEPENDENCIES = foo.texi
3010       #   |  here bar.texi is dist_ in line 2, and nodist_ in 4.
3011       #
3012       # Back to the point, it should be clear that in order to support
3013       # non-distributed .info files, we need to build them in the
3014       # build tree, not in the source tree (non-distributed .texi
3015       # files are less of a problem, because we do not output build
3016       # rules for them).  In Automake 1.7 .info build rules have been
3017       # largely cleaned up so that .info files get always build in the
3018       # build tree, even when distributed.  The idea was that
3019       #   (1) if during a VPATH build the .info file was found to be
3020       #       absent or out-of-date (in the source tree or in the
3021       #       build tree), Make would rebuild it in the build tree.
3022       #       If an up-to-date source-tree of the .info file existed,
3023       #       make would not rebuild it in the build tree.
3024       #   (2) having two copies of .info files, one in the source tree
3025       #       and one (newer) in the build tree is not a problem
3026       #       because `make dist' always pick files in the build tree
3027       #       first.
3028       # However it turned out the be a bad idea for several reasons:
3029       #   * Tru64, OpenBSD, and FreeBSD (not NetBSD) Make do not behave
3030       #     like GNU Make on point (1) above.  These implementations
3031       #     of Make would always rebuild .info files in the build
3032       #     tree, even if such files were up to date in the source
3033       #     tree.  Consequently, it was impossible to perform a VPATH
3034       #     build of a package containing Texinfo files using these
3035       #     Make implementations.
3036       #     (Refer to the Autoconf Manual, section "Limitation of
3037       #     Make", paragraph "VPATH", item "target lookup", for
3038       #     an account of the differences between these
3039       #     implementations.)
3040       #   * The GNU Coding Standards require these files to be built
3041       #     in the source-tree (when they are distributed, that is).
3042       #   * Keeping a fresher copy of distributed files in the
3043       #     build tree can be annoying during development because
3044       #     - if the files is kept under CVS, you really want it
3045       #       to be updated in the source tree
3046       #     - it is confusing that `make distclean' does not erase
3047       #       all files in the build tree.
3048       #
3049       # Consequently, starting with Automake 1.8, .info files are
3050       # built in the source tree again.  Because we still plan to
3051       # support non-distributed .info files at some point, we
3052       # have a single variable ($INSRC) that controls whether
3053       # the current .info file must be built in the source tree
3054       # or in the build tree.  Actually this variable is switched
3055       # off for .info files that appear to be cleaned; this is
3056       # for backward compatibility with package such as Texinfo,
3057       # which do things like
3058       #   info_TEXINFOS = texinfo.txi info-stnd.texi info.texi
3059       #   DISTCLEANFILES = texinfo texinfo-* info*.info*
3060       #   # Do not create info files for distribution.
3061       #   dist-info:
3062       # in order not to distribute .info files.
3063       my $insrc = ($out_file =~ $user_cleaned_files) ? 0 : 1;
3065       my $soutdir = '$(srcdir)/' . $outdir;
3066       $outdir = $soutdir if $insrc;
3068       # If user specified file_TEXINFOS, then use that as explicit
3069       # dependency list.
3070       @texi_deps = ();
3071       push (@texi_deps, "$soutdir$vtexi") if $vtexi;
3073       my $canonical = canonicalize ($infobase);
3074       if (var ($canonical . "_TEXINFOS"))
3075         {
3076           push (@texi_deps, '$(' . $canonical . '_TEXINFOS)');
3077           push_dist_common ('$(' . $canonical . '_TEXINFOS)');
3078         }
3080       my ($dirstamp, @cfiles) =
3081         output_texinfo_build_rules ($texi, $out_file, $insrc, @texi_deps);
3082       push (@texi_cleans, @cfiles);
3084       push (@info_deps_list, $out_file);
3086       # If a vers*.texi file is needed, emit the rule.
3087       if ($vtexi)
3088         {
3089           err_am ("`$vtexi', included in `$texi', "
3090                   . "also included in `$versions{$vtexi}'")
3091             if defined $versions{$vtexi};
3092           $versions{$vtexi} = $texi;
3094           # We number the stamp-vti files.  This is doable since the
3095           # actual names don't matter much.  We only number starting
3096           # with the second one, so that the common case looks nice.
3097           my $vti = ($done ? $done : 'vti');
3098           ++$done;
3100           # This is ugly, but it is our historical practice.
3101           if ($config_aux_dir_set_in_configure_ac)
3102             {
3103               require_conf_file_with_macro (TRUE, 'info_TEXINFOS', FOREIGN,
3104                                             'mdate-sh');
3105             }
3106           else
3107             {
3108               require_file_with_macro (TRUE, 'info_TEXINFOS',
3109                                        FOREIGN, 'mdate-sh');
3110             }
3112           my $conf_dir;
3113           if ($config_aux_dir_set_in_configure_ac)
3114             {
3115               $conf_dir = "$am_config_aux_dir/";
3116             }
3117           else
3118             {
3119               $conf_dir = '$(srcdir)/';
3120             }
3121           $output_rules .= file_contents ('texi-vers',
3122                                           new Automake::Location,
3123                                           TEXI     => $texi,
3124                                           VTI      => $vti,
3125                                           STAMPVTI => "${soutdir}stamp-$vti",
3126                                           VTEXI    => "$soutdir$vtexi",
3127                                           MDDIR    => $conf_dir,
3128                                           DIRSTAMP => $dirstamp);
3129         }
3130     }
3132   # Handle location of texinfo.tex.
3133   my $need_texi_file = 0;
3134   my $texinfodir;
3135   if (var ('TEXINFO_TEX'))
3136     {
3137       # The user defined TEXINFO_TEX so assume he knows what he is
3138       # doing.
3139       $texinfodir = ('$(srcdir)/'
3140                      . dirname (variable_value ('TEXINFO_TEX')));
3141     }
3142   elsif (option 'cygnus')
3143     {
3144       $texinfodir = '$(top_srcdir)/../texinfo';
3145       define_variable ('TEXINFO_TEX', "$texinfodir/texinfo.tex", INTERNAL);
3146     }
3147   elsif ($config_aux_dir_set_in_configure_ac)
3148     {
3149       $texinfodir = $am_config_aux_dir;
3150       define_variable ('TEXINFO_TEX', "$texinfodir/texinfo.tex", INTERNAL);
3151       $need_texi_file = 2; # so that we require_conf_file later
3152     }
3153   else
3154     {
3155       $texinfodir = '$(srcdir)';
3156       $need_texi_file = 1;
3157     }
3158   define_variable ('am__TEXINFO_TEX_DIR', $texinfodir, INTERNAL);
3160   push (@dist_targets, 'dist-info');
3162   if (! option 'no-installinfo')
3163     {
3164       # Make sure documentation is made and installed first.  Use
3165       # $(INFO_DEPS), not 'info', because otherwise recursive makes
3166       # get run twice during "make all".
3167       unshift (@all, '$(INFO_DEPS)');
3168     }
3170   define_files_variable ("DVIS", @infobase, 'dvi', INTERNAL);
3171   define_files_variable ("PDFS", @infobase, 'pdf', INTERNAL);
3172   define_files_variable ("PSS", @infobase, 'ps', INTERNAL);
3173   define_files_variable ("HTMLS", @infobase, 'html', INTERNAL);
3175   # This next isn't strictly needed now -- the places that look here
3176   # could easily be changed to look in info_TEXINFOS.  But this is
3177   # probably better, in case noinst_TEXINFOS is ever supported.
3178   define_variable ("TEXINFOS", variable_value ('info_TEXINFOS'), INTERNAL);
3180   # Do some error checking.  Note that this file is not required
3181   # when in Cygnus mode; instead we defined TEXINFO_TEX explicitly
3182   # up above.
3183   if ($need_texi_file && ! option 'no-texinfo.tex')
3184     {
3185       if ($need_texi_file > 1)
3186         {
3187           require_conf_file_with_macro (TRUE, 'info_TEXINFOS', FOREIGN,
3188                                         'texinfo.tex');
3189         }
3190       else
3191         {
3192           require_file_with_macro (TRUE, 'info_TEXINFOS', FOREIGN,
3193                                    'texinfo.tex');
3194         }
3195     }
3197   return makefile_wrap ("", "\t  ", @texi_cleans);
3201 # handle_texinfo ()
3202 # -----------------
3203 # Handle all Texinfo source.
3204 sub handle_texinfo ()
3206   reject_var 'TEXINFOS', "`TEXINFOS' is an anachronism; use `info_TEXINFOS'";
3207   # FIXME: I think this is an obsolete future feature name.
3208   reject_var 'html_TEXINFOS', "HTML generation not yet supported";
3210   my $info_texinfos = var ('info_TEXINFOS');
3211   my $texiclean = "";
3212   if ($info_texinfos)
3213     {
3214       $texiclean = handle_texinfo_helper ($info_texinfos);
3215     }
3216   $output_rules .=  file_contents ('texinfos',
3217                                    new Automake::Location,
3218                                    TEXICLEAN     => $texiclean,
3219                                    'LOCAL-TEXIS' => !!$info_texinfos);
3223 # Handle any man pages.
3224 sub handle_man_pages
3226   reject_var 'MANS', "`MANS' is an anachronism; use `man_MANS'";
3228   # Find all the sections in use.  We do this by first looking for
3229   # "standard" sections, and then looking for any additional
3230   # sections used in man_MANS.
3231   my (%sections, %vlist);
3232   # We handle nodist_ for uniformity.  man pages aren't distributed
3233   # by default so it isn't actually very important.
3234   foreach my $pfx ('', 'dist_', 'nodist_')
3235     {
3236       # Add more sections as needed.
3237       foreach my $section ('0'..'9', 'n', 'l')
3238         {
3239           my $varname = $pfx . 'man' . $section . '_MANS';
3240           if (var ($varname))
3241             {
3242               $sections{$section} = 1;
3243               $varname = '$(' . $varname . ')';
3244               $vlist{$varname} = 1;
3246               &push_dist_common ($varname)
3247                 if $pfx eq 'dist_';
3248             }
3249         }
3251       my $varname = $pfx . 'man_MANS';
3252       my $var = var ($varname);
3253       if ($var)
3254         {
3255           foreach ($var->value_as_list_recursive)
3256             {
3257               # A page like `foo.1c' goes into man1dir.
3258               if (/\.([0-9a-z])([a-z]*)$/)
3259                 {
3260                   $sections{$1} = 1;
3261                 }
3262             }
3264           $varname = '$(' . $varname . ')';
3265           $vlist{$varname} = 1;
3266           &push_dist_common ($varname)
3267             if $pfx eq 'dist_';
3268         }
3269     }
3271   return unless %sections;
3273   # Now for each section, generate an install and uninstall rule.
3274   # Sort sections so output is deterministic.
3275   foreach my $section (sort keys %sections)
3276     {
3277       $output_rules .= &file_contents ('mans',
3278                                        new Automake::Location,
3279                                        SECTION => $section);
3280     }
3282   my @mans = sort keys %vlist;
3283   $output_vars .= file_contents ('mans-vars',
3284                                  new Automake::Location,
3285                                  MANS => "@mans");
3287   push (@all, '$(MANS)')
3288     unless option 'no-installman';
3291 # Handle DATA variables.
3292 sub handle_data
3294     &am_install_var ('-noextra', '-candist', 'data', 'DATA',
3295                      'data', 'sysconf', 'sharedstate', 'localstate',
3296                      'pkgdata', 'lisp', 'noinst', 'check');
3299 # Handle TAGS.
3300 sub handle_tags
3302     my @tag_deps = ();
3303     my @ctag_deps = ();
3304     if (var ('SUBDIRS'))
3305     {
3306         $output_rules .= ("tags-recursive:\n"
3307                           . "\tlist=\'\$(SUBDIRS)\'; for subdir in \$\$list; do \\\n"
3308                           # Never fail here if a subdir fails; it
3309                           # isn't important.
3310                           . "\t  test \"\$\$subdir\" = . || (cd \$\$subdir"
3311                           . " && \$(MAKE) \$(AM_MAKEFLAGS) tags); \\\n"
3312                           . "\tdone\n");
3313         push (@tag_deps, 'tags-recursive');
3314         &depend ('.PHONY', 'tags-recursive');
3316         $output_rules .= ("ctags-recursive:\n"
3317                           . "\tlist=\'\$(SUBDIRS)\'; for subdir in \$\$list; do \\\n"
3318                           # Never fail here if a subdir fails; it
3319                           # isn't important.
3320                           . "\t  test \"\$\$subdir\" = . || (cd \$\$subdir"
3321                           . " && \$(MAKE) \$(AM_MAKEFLAGS) ctags); \\\n"
3322                           . "\tdone\n");
3323         push (@ctag_deps, 'ctags-recursive');
3324         &depend ('.PHONY', 'ctags-recursive');
3325     }
3327     if (&saw_sources_p (1)
3328         || var ('ETAGS_ARGS')
3329         || @tag_deps)
3330     {
3331         my @config;
3332         foreach my $spec (@config_headers)
3333         {
3334             my ($out, @ins) = split_config_file_spec ($spec);
3335             foreach my $in (@ins)
3336               {
3337                 # If the config header source is in this directory,
3338                 # require it.
3339                 push @config, basename ($in)
3340                   if $relative_dir eq dirname ($in);
3341               }
3342         }
3343         $output_rules .= &file_contents ('tags',
3344                                          new Automake::Location,
3345                                          CONFIG    => "@config",
3346                                          TAGSDIRS  => "@tag_deps",
3347                                          CTAGSDIRS => "@ctag_deps");
3349         set_seen 'TAGS_DEPENDENCIES';
3350     }
3351     elsif (reject_var ('TAGS_DEPENDENCIES',
3352                        "doesn't make sense to define `TAGS_DEPENDENCIES'"
3353                        . "without\nsources or `ETAGS_ARGS'"))
3354     {
3355     }
3356     else
3357     {
3358         # Every Makefile must define some sort of TAGS rule.
3359         # Otherwise, it would be possible for a top-level "make TAGS"
3360         # to fail because some subdirectory failed.
3361         $output_rules .= "tags: TAGS\nTAGS:\n\n";
3362         # Ditto ctags.
3363         $output_rules .= "ctags: CTAGS\nCTAGS:\n\n";
3364     }
3367 # Handle multilib support.
3368 sub handle_multilib
3370   if ($seen_multilib && $relative_dir eq '.')
3371     {
3372       $output_rules .= &file_contents ('multilib', new Automake::Location);
3373       push (@all, 'all-multi');
3374     }
3378 # user_phony_rule ($NAME)
3379 # -----------------------
3380 # Return false if rule $NAME does not exist.  Otherwise,
3381 # declare it as phony, complete its definition (in case it is
3382 # conditional), and return its Automake::Rule instance.
3383 sub user_phony_rule ($)
3385   my ($name) = @_;
3386   my $rule = rule $name;
3387   if ($rule)
3388     {
3389       depend ('.PHONY', $name);
3390       # Define $NAME in all condition where it is not already defined,
3391       # so that it is always OK to depend on $NAME.
3392       for my $c ($rule->not_always_defined_in_cond (TRUE)->conds)
3393         {
3394           Automake::Rule::define ($name, 'internal', RULE_AUTOMAKE,
3395                                   $c, INTERNAL);
3396           $output_rules .= $c->subst_string . "$name:\n";
3397         }
3398     }
3399   return $rule;
3403 # $BOOLEAN
3404 # &for_dist_common ($A, $B)
3405 # -------------------------
3406 # Subroutine for &handle_dist: sort files to dist.
3408 # We put README first because it then becomes easier to make a
3409 # Usenet-compliant shar file (in these, README must be first).
3411 # FIXME: do more ordering of files here.
3412 sub for_dist_common
3414     return 0
3415         if $a eq $b;
3416     return -1
3417         if $a eq 'README';
3418     return 1
3419         if $b eq 'README';
3420     return $a cmp $b;
3424 # handle_dist
3425 # -----------
3426 # Handle 'dist' target.
3427 sub handle_dist ()
3429   # Substutions for distdit.am
3430   my %transform;
3432   # Define DIST_SUBDIRS.  This must always be done, regardless of the
3433   # no-dist setting: target like `distclean' or `maintainer-clean' use it.
3434   my $subdirs = var ('SUBDIRS');
3435   if ($subdirs)
3436     {
3437       # If SUBDIRS is conditionally defined, then set DIST_SUBDIRS
3438       # to all possible directories, and use it.  If DIST_SUBDIRS is
3439       # defined, just use it.
3441       # Note that we check DIST_SUBDIRS first on purpose, so that
3442       # we don't call has_conditional_contents for now reason.
3443       # (In the past one project used so many conditional subdirectories
3444       # that calling has_conditional_contents on SUBDIRS caused
3445       # automake to grow to 150Mb -- this should not happen with
3446       # the current implementation of has_conditional_contents,
3447       # but it's more efficient to avoid the call anyway.)
3448       if (var ('DIST_SUBDIRS'))
3449         {
3450         }
3451       elsif ($subdirs->has_conditional_contents)
3452         {
3453           define_pretty_variable
3454             ('DIST_SUBDIRS', TRUE, INTERNAL,
3455              uniq ($subdirs->value_as_list_recursive));
3456         }
3457       else
3458         {
3459           # We always define this because that is what `distclean'
3460           # wants.
3461           define_pretty_variable ('DIST_SUBDIRS', TRUE, INTERNAL,
3462                                   '$(SUBDIRS)');
3463         }
3464     }
3466   # The remaining definitions are only required when a dist target is used.
3467   return if option 'no-dist';
3469   # At least one of the archive formats must be enabled.
3470   if ($relative_dir eq '.')
3471     {
3472       my $archive_defined = option 'no-dist-gzip' ? 0 : 1;
3473       $archive_defined ||=
3474         grep { option "dist-$_" } ('shar', 'zip', 'tarZ', 'bzip2');
3475       error (option 'no-dist-gzip',
3476              "no-dist-gzip specified but no dist-* specified, "
3477              . "at least one archive format must be enabled")
3478         unless $archive_defined;
3479     }
3481   # Look for common files that should be included in distribution.
3482   # If the aux dir is set, and it does not have a Makefile.am, then
3483   # we check for these files there as well.
3484   my $check_aux = 0;
3485   if ($relative_dir eq '.'
3486       && $config_aux_dir_set_in_configure_ac)
3487     {
3488       if (! &is_make_dir ($config_aux_dir))
3489         {
3490           $check_aux = 1;
3491         }
3492     }
3493   foreach my $cfile (@common_files)
3494     {
3495       if (-f ($relative_dir . "/" . $cfile)
3496           # The file might be absent, but if it can be built it's ok.
3497           || rule $cfile)
3498         {
3499           &push_dist_common ($cfile);
3500         }
3502       # Don't use `elsif' here because a file might meaningfully
3503       # appear in both directories.
3504       if ($check_aux && -f "$config_aux_dir/$cfile")
3505         {
3506           &push_dist_common ("$config_aux_dir/$cfile")
3507         }
3508     }
3510   # We might copy elements from $configure_dist_common to
3511   # %dist_common if we think we need to.  If the file appears in our
3512   # directory, we would have discovered it already, so we don't
3513   # check that.  But if the file is in a subdir without a Makefile,
3514   # we want to distribute it here if we are doing `.'.  Ugly!
3515   if ($relative_dir eq '.')
3516     {
3517       foreach my $file (split (' ' , $configure_dist_common))
3518         {
3519           push_dist_common ($file)
3520             unless is_make_dir (dirname ($file));
3521         }
3522     }
3524   # Files to distributed.  Don't use ->value_as_list_recursive
3525   # as it recursively expands `$(dist_pkgdata_DATA)' etc.
3526   my @dist_common = split (' ', rvar ('DIST_COMMON')->variable_value);
3527   @dist_common = uniq (sort for_dist_common (@dist_common));
3528   variable_delete 'DIST_COMMON';
3529   define_pretty_variable ('DIST_COMMON', TRUE, INTERNAL, @dist_common);
3531   # Now that we've processed DIST_COMMON, disallow further attempts
3532   # to set it.
3533   $handle_dist_run = 1;
3535   # Scan EXTRA_DIST to see if we need to distribute anything from a
3536   # subdir.  If so, add it to the list.  I didn't want to do this
3537   # originally, but there were so many requests that I finally
3538   # relented.
3539   my $extra_dist = var ('EXTRA_DIST');
3540   if ($extra_dist)
3541     {
3542       # FIXME: This should be fixed to work with conditions.  That
3543       # will require only making the entries in %dist_dirs under the
3544       # appropriate condition.  This is meaningful if the nature of
3545       # the distribution should depend upon the configure options
3546       # used.
3547       foreach ($extra_dist->value_as_list_recursive (skip_ac_subst => 1))
3548         {
3549           next unless s,/+[^/]+$,,;
3550           $dist_dirs{$_} = 1
3551             unless $_ eq '.';
3552         }
3553     }
3555   # We have to check DIST_COMMON for extra directories in case the
3556   # user put a source used in AC_OUTPUT into a subdir.
3557   my $topsrcdir = backname ($relative_dir);
3558   foreach (rvar ('DIST_COMMON')->value_as_list_recursive (skip_ac_subst => 1))
3559     {
3560       s/\$\(top_srcdir\)/$topsrcdir/;
3561       s/\$\(srcdir\)/./;
3562       # Strip any leading `./'.
3563       s,^(:?\./+)*,,;
3564       next unless s,/+[^/]+$,,;
3565       $dist_dirs{$_} = 1
3566         unless $_ eq '.';
3567     }
3569   $transform{'DISTCHECK-HOOK'} = !! rule 'distcheck-hook';
3570   $transform{'GETTEXT'} = $seen_gettext && !$seen_gettext_external;
3572   # Prepend $(distdir) to each directory given.
3573   my %rewritten = map { '$(distdir)/' . "$_" => 1 } keys %dist_dirs;
3574   $transform{'DISTDIRS'} = join (' ', sort keys %rewritten);
3576   # If the target `dist-hook' exists, make sure it is run.  This
3577   # allows users to do random weird things to the distribution
3578   # before it is packaged up.
3579   push (@dist_targets, 'dist-hook')
3580     if user_phony_rule 'dist-hook';
3581   $transform{'DIST-TARGETS'} = join (' ', @dist_targets);
3583   my $flm = option ('filename-length-max');
3584   my $filename_filter = $flm ? '.' x $flm->[1] : '';
3586   $output_rules .= &file_contents ('distdir',
3587                                    new Automake::Location,
3588                                    %transform,
3589                                    FILENAME_FILTER => $filename_filter);
3593 # check_directory ($NAME, $WHERE)
3594 # -------------------------------
3595 # Ensure $NAME is a directory, and that it uses sane name.
3596 # Use $WHERE as a location in the diagnostic, if any.
3597 sub check_directory ($$)
3599   my ($dir, $where) = @_;
3601   error $where, "required directory $relative_dir/$dir does not exist"
3602     unless -d "$relative_dir/$dir";
3604   # If an `obj/' directory exists, BSD make will enter it before
3605   # reading `Makefile'.  Hence the `Makefile' in the current directory
3606   # will not be read.
3607   #
3608   #  % cat Makefile
3609   #  all:
3610   #          echo Hello
3611   #  % cat obj/Makefile
3612   #  all:
3613   #          echo World
3614   #  % make      # GNU make
3615   #  echo Hello
3616   #  Hello
3617   #  % pmake     # BSD make
3618   #  echo World
3619   #  World
3620   msg ('portability', $where,
3621        "naming a subdirectory `obj' causes troubles with BSD make")
3622     if $dir eq 'obj';
3624   # `aux' is probably the most important of the following forbidden name,
3625   # since it's tempting to use it as an AC_CONFIG_AUX_DIR.
3626   msg ('portability', $where,
3627        "name `$dir' is reserved on W32 and DOS platforms")
3628     if grep (/^\Q$dir\E$/i, qw/aux lpt1 lpt2 lpt3 com1 com2 com3 com4 con prn/);
3631 # check_directories_in_var ($VARIABLE)
3632 # ------------------------------------
3633 # Recursively check all items in variables $VARIABLE as directories
3634 sub check_directories_in_var ($)
3636   my ($var) = @_;
3637   $var->traverse_recursively
3638     (sub
3639      {
3640        my ($var, $val, $cond, $full_cond) = @_;
3641        check_directory ($val, $var->rdef ($cond)->location);
3642        return ();
3643      },
3644      undef,
3645      skip_ac_subst => 1);
3648 # &handle_subdirs ()
3649 # ------------------
3650 # Handle subdirectories.
3651 sub handle_subdirs ()
3653   my $subdirs = var ('SUBDIRS');
3654   return
3655     unless $subdirs;
3657   check_directories_in_var $subdirs;
3659   my $dsubdirs = var ('DIST_SUBDIRS');
3660   check_directories_in_var $dsubdirs
3661     if $dsubdirs;
3663   $output_rules .= &file_contents ('subdirs', new Automake::Location);
3664   rvar ('RECURSIVE_TARGETS')->rdef (TRUE)->{'pretty'} = VAR_SORTED; # Gross!
3668 # ($REGEN, @DEPENDENCIES)
3669 # &scan_aclocal_m4
3670 # ----------------
3671 # If aclocal.m4 creation is automated, return the list of its dependencies.
3672 sub scan_aclocal_m4 ()
3674   my $regen_aclocal = 0;
3676   set_seen 'CONFIG_STATUS_DEPENDENCIES';
3677   set_seen 'CONFIGURE_DEPENDENCIES';
3679   if (-f 'aclocal.m4')
3680     {
3681       &define_variable ("ACLOCAL_M4", '$(top_srcdir)/aclocal.m4', INTERNAL);
3683       my $aclocal = new Automake::XFile "< aclocal.m4";
3684       my $line = $aclocal->getline;
3685       $regen_aclocal = $line =~ 'generated automatically by aclocal';
3686     }
3688   my @ac_deps = ();
3690   if (set_seen ('ACLOCAL_M4_SOURCES'))
3691     {
3692       push (@ac_deps, '$(ACLOCAL_M4_SOURCES)');
3693       msg_var ('obsolete', 'ACLOCAL_M4_SOURCES',
3694                "`ACLOCAL_M4_SOURCES' is obsolete.\n"
3695                . "It should be safe to simply remove it.");
3696     }
3698   # Note that it might be possible that aclocal.m4 doesn't exist but
3699   # should be auto-generated.  This case probably isn't very
3700   # important.
3702   return ($regen_aclocal, @ac_deps);
3706 # @DEPENDENCIES
3707 # &prepend_srcdir (@INPUTS)
3708 # -------------------------
3709 # Prepend $(srcdir) or $(top_srcdir) to all @INPUTS.  The idea is that
3710 # if an input file has a directory part the same as the current
3711 # directory, then the directory part is simply replaced by $(srcdir).
3712 # But if the directory part is different, then $(top_srcdir) is
3713 # prepended.
3714 sub prepend_srcdir (@)
3716   my (@inputs) = @_;
3717   my @newinputs;
3719   foreach my $single (@inputs)
3720     {
3721       if (dirname ($single) eq $relative_dir)
3722         {
3723           push (@newinputs, '$(srcdir)/' . basename ($single));
3724         }
3725       else
3726         {
3727           push (@newinputs, '$(top_srcdir)/' . $single);
3728         }
3729     }
3730   return @newinputs;
3733 # @DEPENDENCIES
3734 # rewrite_inputs_into_dependencies ($OUTPUT, @INPUTS)
3735 # ---------------------------------------------------
3736 # Compute a list of dependencies appropriate for the rebuild
3737 # rule of
3738 #   AC_CONFIG_FILES($OUTPUT:$INPUT[0]:$INPUTS[1]:...)
3739 # Also distribute $INPUTs which are not build by another AC_CONFIG_FILES.
3740 sub rewrite_inputs_into_dependencies ($@)
3742   my ($file, @inputs) = @_;
3743   my @res = ();
3745   for my $i (@inputs)
3746     {
3747       if (exists $ac_config_files_location{$i})
3748         {
3749           my $di = dirname $i;
3750           if ($di eq $relative_dir)
3751             {
3752               $i = basename $i;
3753             }
3754           # In the top-level Makefile we do not use $(top_builddir), because
3755           # we are already there, and since the targets are built without
3756           # a $(top_builddir), it helps BSD Make to match them with
3757           # dependencies.
3758           elsif ($relative_dir ne '.')
3759             {
3760               $i = '$(top_builddir)/' . $i;
3761             }
3762         }
3763       else
3764         {
3765           msg ('error', $ac_config_files_location{$file},
3766                "required file `$i' not found")
3767             unless exists $output_files{$i} || -f $i;
3768           ($i) = prepend_srcdir ($i);
3769           push_dist_common ($i);
3770         }
3771       push @res, $i;
3772     }
3773   return @res;
3778 # &handle_configure ($MAKEFILE_AM, $MAKEFILE_IN, $MAKEFILE, @INPUTS)
3779 # ------------------------------------------------------------------
3780 # Handle remaking and configure stuff.
3781 # We need the name of the input file, to do proper remaking rules.
3782 sub handle_configure ($$$@)
3784   my ($makefile_am, $makefile_in, $makefile, @inputs) = @_;
3786   prog_error 'empty @inputs'
3787     unless @inputs;
3789   my ($rel_makefile_am, $rel_makefile_in) = prepend_srcdir ($makefile_am,
3790                                                             $makefile_in);
3791   my $rel_makefile = basename $makefile;
3793   my $colon_infile = ':' . join (':', @inputs);
3794   $colon_infile = '' if $colon_infile eq ":$makefile.in";
3795   my @rewritten = rewrite_inputs_into_dependencies ($makefile, @inputs);
3796   my ($regen_aclocal_m4, @aclocal_m4_deps) = scan_aclocal_m4;
3797   define_pretty_variable ('am__aclocal_m4_deps', TRUE, INTERNAL,
3798                           @configure_deps, @aclocal_m4_deps,
3799                           '$(top_srcdir)/' . $configure_ac);
3800   my @configuredeps = ('$(am__aclocal_m4_deps)', '$(CONFIGURE_DEPENDENCIES)');
3801   push @configuredeps, '$(ACLOCAL_M4)' if -f 'aclocal.m4';
3802   define_pretty_variable ('am__configure_deps', TRUE, INTERNAL,
3803                           @configuredeps);
3805   $output_rules .= file_contents
3806     ('configure',
3807      new Automake::Location,
3808      MAKEFILE              => $rel_makefile,
3809      'MAKEFILE-DEPS'       => "@rewritten",
3810      'CONFIG-MAKEFILE'     => ($relative_dir eq '.') ? '$@' : '$(subdir)/$@',
3811      'MAKEFILE-IN'         => $rel_makefile_in,
3812      'MAKEFILE-IN-DEPS'    => "@include_stack",
3813      'MAKEFILE-AM'         => $rel_makefile_am,
3814      STRICTNESS            => global_option 'cygnus'
3815                                 ? 'cygnus' : $strictness_name,
3816      'USE-DEPS'            => global_option 'no-dependencies'
3817                                 ? ' --ignore-deps' : '',
3818      'MAKEFILE-AM-SOURCES' => "$makefile$colon_infile",
3819      'REGEN-ACLOCAL-M4'    => $regen_aclocal_m4);
3821   if ($relative_dir eq '.')
3822     {
3823       &push_dist_common ('acconfig.h')
3824         if -f 'acconfig.h';
3825     }
3827   # If we have a configure header, require it.
3828   my $hdr_index = 0;
3829   my @distclean_config;
3830   foreach my $spec (@config_headers)
3831     {
3832       $hdr_index += 1;
3833       # $CONFIG_H_PATH: config.h from top level.
3834       my ($config_h_path, @ins) = split_config_file_spec ($spec);
3835       my $config_h_dir = dirname ($config_h_path);
3837       # If the header is in the current directory we want to build
3838       # the header here.  Otherwise, if we're at the topmost
3839       # directory and the header's directory doesn't have a
3840       # Makefile, then we also want to build the header.
3841       if ($relative_dir eq $config_h_dir
3842           || ($relative_dir eq '.' && ! &is_make_dir ($config_h_dir)))
3843         {
3844           my ($cn_sans_dir, $stamp_dir);
3845           if ($relative_dir eq $config_h_dir)
3846             {
3847               $cn_sans_dir = basename ($config_h_path);
3848               $stamp_dir = '';
3849             }
3850           else
3851             {
3852               $cn_sans_dir = $config_h_path;
3853               if ($config_h_dir eq '.')
3854                 {
3855                   $stamp_dir = '';
3856                 }
3857               else
3858                 {
3859                   $stamp_dir = $config_h_dir . '/';
3860                 }
3861             }
3863           # This will also distribute all inputs.
3864           @ins = rewrite_inputs_into_dependencies ($config_h_path, @ins);
3866           # Header defined and in this directory.
3867           my @files;
3868           if (-f $config_h_path . '.top')
3869             {
3870               push (@files, "$cn_sans_dir.top");
3871             }
3872           if (-f $config_h_path . '.bot')
3873             {
3874               push (@files, "$cn_sans_dir.bot");
3875             }
3877           push_dist_common (@files);
3879           # For now, acconfig.h can only appear in the top srcdir.
3880           if (-f 'acconfig.h')
3881             {
3882               push (@files, '$(top_srcdir)/acconfig.h');
3883             }
3885           my $stamp = "${stamp_dir}stamp-h${hdr_index}";
3886           $output_rules .=
3887             file_contents ('remake-hdr',
3888                            new Automake::Location,
3889                            FILES            => "@files",
3890                            CONFIG_H         => $cn_sans_dir,
3891                            CONFIG_HIN       => $ins[0],
3892                            CONFIG_H_DEPS    => "@ins",
3893                            CONFIG_H_PATH    => $config_h_path,
3894                            STAMP            => "$stamp");
3896           push @distclean_config, $cn_sans_dir, $stamp;
3897         }
3898     }
3900   $output_rules .= file_contents ('clean-hdr',
3901                                   new Automake::Location,
3902                                   FILES => "@distclean_config")
3903     if @distclean_config;
3905   # Distribute and define mkinstalldirs only if it is already present
3906   # in the package, for backward compatibility (some people may still
3907   # use $(mkinstalldirs)).
3908   my $mkidpath = "$config_aux_dir/mkinstalldirs";
3909   if (-f $mkidpath)
3910     {
3911       # Use require_file so that any existing script gets updated
3912       # by --force-missing.
3913       require_conf_file ($mkidpath, FOREIGN, 'mkinstalldirs');
3914       define_variable ('mkinstalldirs',
3915                        "\$(SHELL) $am_config_aux_dir/mkinstalldirs", INTERNAL);
3916     }
3917   else
3918     {
3919       # Use $(install_sh), not $(mkdir_p) because the latter requires
3920       # at least one argument, and $(mkinstalldirs) used to work
3921       # even without arguments (e.g. $(mkinstalldirs) $(conditional_dir)).
3922       define_variable ('mkinstalldirs', '$(install_sh) -d', INTERNAL);
3923     }
3925   reject_var ('CONFIG_HEADER',
3926               "`CONFIG_HEADER' is an anachronism; now determined "
3927               . "automatically\nfrom `$configure_ac'");
3929   my @config_h;
3930   foreach my $spec (@config_headers)
3931     {
3932       my ($out, @ins) = split_config_file_spec ($spec);
3933       # Generate CONFIG_HEADER define.
3934       if ($relative_dir eq dirname ($out))
3935         {
3936           push @config_h, basename ($out);
3937         }
3938       else
3939         {
3940           push @config_h, "\$(top_builddir)/$out";
3941         }
3942     }
3943   define_variable ("CONFIG_HEADER", "@config_h", INTERNAL)
3944     if @config_h;
3946   # Now look for other files in this directory which must be remade
3947   # by config.status, and generate rules for them.
3948   my @actual_other_files = ();
3949   foreach my $lfile (@other_input_files)
3950     {
3951       my $file;
3952       my @inputs;
3953       if ($lfile =~ /^([^:]*):(.*)$/)
3954         {
3955           # This is the ":" syntax of AC_OUTPUT.
3956           $file = $1;
3957           @inputs = split (':', $2);
3958         }
3959       else
3960         {
3961           # Normal usage.
3962           $file = $lfile;
3963           @inputs = $file . '.in';
3964         }
3966       # Automake files should not be stored in here, but in %MAKE_LIST.
3967       prog_error ("$lfile in \@other_input_files\n"
3968                   . "\@other_input_files = (@other_input_files)")
3969         if -f $file . '.am';
3971       my $local = basename ($file);
3973       # Make sure the dist directory for each input file is created.
3974       # We only have to do this at the topmost level though.  This
3975       # is a bit ugly but it easier than spreading out the logic,
3976       # especially in cases like AC_OUTPUT(foo/out:bar/in), where
3977       # there is no Makefile in bar/.
3978       if ($relative_dir eq '.')
3979         {
3980           foreach (@inputs)
3981             {
3982               $dist_dirs{dirname ($_)} = 1;
3983             }
3984         }
3986       # We skip files that aren't in this directory.  However, if
3987       # the file's directory does not have a Makefile, and we are
3988       # currently doing `.', then we create a rule to rebuild the
3989       # file in the subdir.
3990       my $fd = dirname ($file);
3991       if ($fd ne $relative_dir)
3992         {
3993           if ($relative_dir eq '.' && ! &is_make_dir ($fd))
3994             {
3995               $local = $file;
3996             }
3997           else
3998             {
3999               next;
4000             }
4001         }
4003       my @rewritten_inputs = rewrite_inputs_into_dependencies ($file, @inputs);
4005       $output_rules .= ($local . ': '
4006                         . '$(top_builddir)/config.status '
4007                         . "@rewritten_inputs\n"
4008                         . "\t"
4009                         . 'cd $(top_builddir) && '
4010                         . '$(SHELL) ./config.status '
4011                         . ($relative_dir eq '.' ? '' : '$(subdir)/')
4012                         . '$@'
4013                         . "\n");
4014       push (@actual_other_files, $local);
4015     }
4017   # For links we should clean destinations and distribute sources.
4018   foreach my $spec (@config_links)
4019     {
4020       my ($link, $file) = split /:/, $spec;
4021       # Some people do AC_CONFIG_LINKS($computed).  We only handle
4022       # the DEST:SRC form.
4023       next unless $file;
4024       my $where = $ac_config_files_location{$link};
4026       # Skip destinations that contain shell variables.
4027       if ($link !~ /\$/)
4028         {
4029           # We skip links that aren't in this directory.  However, if
4030           # the link's directory does not have a Makefile, and we are
4031           # currently doing `.', then we add the link to CONFIG_CLEAN_FILES
4032           # in `.'s Makefile.in.
4033           my $local = basename ($link);
4034           my $fd = dirname ($link);
4035           if ($fd ne $relative_dir)
4036             {
4037               if ($relative_dir eq '.' && ! &is_make_dir ($fd))
4038                 {
4039                   $local = $link;
4040                 }
4041               else
4042                 {
4043                   $local = undef;
4044                 }
4045             }
4046           push @actual_other_files, $local if $local;
4047         }
4049       # Do not process sources that contain shell variables.
4050       if ($file !~ /\$/)
4051         {
4052           my $fd = dirname ($file);
4054           # Make sure the dist directory for each input file is created.
4055           # We only have to do this at the topmost level though.
4056           if ($relative_dir eq '.')
4057             {
4058               $dist_dirs{$fd} = 1;
4059             }
4061           # We distribute files that are in this directory.
4062           # At the top-level (`.') we also distribute files whose
4063           # directory does not have a Makefile.
4064           if (($fd eq $relative_dir)
4065               || ($relative_dir eq '.' && ! &is_make_dir ($fd)))
4066             {
4067               # The following will distribute $file as a side-effect when
4068               # it is appropriate (i.e., when $file is not already an output).
4069               # We do not need the result, just the side-effect.
4070               rewrite_inputs_into_dependencies ($link, $file);
4071             }
4072         }
4073     }
4075   # These files get removed by "make distclean".
4076   define_pretty_variable ('CONFIG_CLEAN_FILES', TRUE, INTERNAL,
4077                           @actual_other_files);
4080 # Handle C headers.
4081 sub handle_headers
4083     my @r = &am_install_var ('-defaultdist', 'header', 'HEADERS', 'include',
4084                              'oldinclude', 'pkginclude',
4085                              'noinst', 'check');
4086     foreach (@r)
4087     {
4088       next unless $_->[1] =~ /\..*$/;
4089       &saw_extension ($&);
4090     }
4093 sub handle_gettext
4095   return if ! $seen_gettext || $relative_dir ne '.';
4097   my $subdirs = var 'SUBDIRS';
4099   if (! $subdirs)
4100     {
4101       err_ac "AM_GNU_GETTEXT used but SUBDIRS not defined";
4102       return;
4103     }
4105   # Perform some sanity checks to help users get the right setup.
4106   # We disable these tests when po/ doesn't exist in order not to disallow
4107   # unusual gettext setups.
4108   #
4109   # Bruno Haible:
4110   # | The idea is:
4111   # |
4112   # |  1) If a package doesn't have a directory po/ at top level, it
4113   # |     will likely have multiple po/ directories in subpackages.
4114   # |
4115   # |  2) It is useful to warn for the absence of intl/ if AM_GNU_GETTEXT
4116   # |     is used without 'external'. It is also useful to warn for the
4117   # |     presence of intl/ if AM_GNU_GETTEXT([external]) is used. Both
4118   # |     warnings apply only to the usual layout of packages, therefore
4119   # |     they should both be disabled if no po/ directory is found at
4120   # |     top level.
4122   if (-d 'po')
4123     {
4124       my @subdirs = $subdirs->value_as_list_recursive;
4126       msg_var ('syntax', $subdirs,
4127                "AM_GNU_GETTEXT used but `po' not in SUBDIRS")
4128         if ! grep ($_ eq 'po', @subdirs);
4130       # intl/ is not required when AM_GNU_GETTEXT is called with
4131       # the `external' option.
4132       msg_var ('syntax', $subdirs,
4133                "AM_GNU_GETTEXT used but `intl' not in SUBDIRS")
4134         if (! $seen_gettext_external
4135             && ! grep ($_ eq 'intl', @subdirs));
4137       # intl/ should not be used with AM_GNU_GETTEXT([external])
4138       msg_var ('syntax', $subdirs,
4139                "`intl' should not be in SUBDIRS when "
4140                . "AM_GNU_GETTEXT([external]) is used")
4141         if ($seen_gettext_external && grep ($_ eq 'intl', @subdirs));
4142     }
4144   require_file ($ac_gettext_location, GNU, 'ABOUT-NLS');
4147 # Handle footer elements.
4148 sub handle_footer
4150     # NOTE don't use define_pretty_variable here, because
4151     # $contents{...} is already defined.
4152     $output_vars .= 'SOURCES = ' . variable_value ('SOURCES') . "\n\n"
4153       if variable_value ('SOURCES');
4155     reject_rule ('.SUFFIXES',
4156                  "use variable `SUFFIXES', not target `.SUFFIXES'");
4158     # Note: AIX 4.1 /bin/make will fail if any suffix rule appears
4159     # before .SUFFIXES.  So we make sure that .SUFFIXES appears before
4160     # anything else, by sticking it right after the default: target.
4161     $output_header .= ".SUFFIXES:\n";
4162     my $suffixes = var 'SUFFIXES';
4163     my @suffixes = Automake::Rule::suffixes;
4164     if (@suffixes || $suffixes)
4165     {
4166         # Make sure SUFFIXES has unique elements.  Sort them to ensure
4167         # the output remains consistent.  However, $(SUFFIXES) is
4168         # always at the start of the list, unsorted.  This is done
4169         # because make will choose rules depending on the ordering of
4170         # suffixes, and this lets the user have some control.  Push
4171         # actual suffixes, and not $(SUFFIXES).  Some versions of make
4172         # do not like variable substitutions on the .SUFFIXES line.
4173         my @user_suffixes = ($suffixes
4174                              ? $suffixes->value_as_list_recursive : ());
4176         my %suffixes = map { $_ => 1 } @suffixes;
4177         delete @suffixes{@user_suffixes};
4179         $output_header .= (".SUFFIXES: "
4180                            . join (' ', @user_suffixes, sort keys %suffixes)
4181                            . "\n");
4182     }
4184     $output_trailer .= file_contents ('footer', new Automake::Location);
4188 # Generate `make install' rules.
4189 sub handle_install ()
4191   $output_rules .= &file_contents
4192     ('install',
4193      new Automake::Location,
4194      maybe_BUILT_SOURCES => (set_seen ('BUILT_SOURCES')
4195                              ? (" \$(BUILT_SOURCES)\n"
4196                                 . "\t\$(MAKE) \$(AM_MAKEFLAGS)")
4197                              : ''),
4198      'installdirs-local' => (user_phony_rule 'installdirs-local'
4199                              ? ' installdirs-local' : ''),
4200      am__installdirs => variable_value ('am__installdirs') || '');
4204 # Deal with all and all-am.
4205 sub handle_all ($)
4207     my ($makefile) = @_;
4209     # Output `all-am'.
4211     # Put this at the beginning for the sake of non-GNU makes.  This
4212     # is still wrong if these makes can run parallel jobs.  But it is
4213     # right enough.
4214     unshift (@all, basename ($makefile));
4216     foreach my $spec (@config_headers)
4217       {
4218         my ($out, @ins) = split_config_file_spec ($spec);
4219         push (@all, basename ($out))
4220           if dirname ($out) eq $relative_dir;
4221       }
4223     # Install `all' hooks.
4224     push (@all, "all-local")
4225       if user_phony_rule "all-local";
4227     &pretty_print_rule ("all-am:", "\t\t", @all);
4228     &depend ('.PHONY', 'all-am', 'all');
4231     # Output `all'.
4233     my @local_headers = ();
4234     push @local_headers, '$(BUILT_SOURCES)'
4235       if var ('BUILT_SOURCES');
4236     foreach my $spec (@config_headers)
4237       {
4238         my ($out, @ins) = split_config_file_spec ($spec);
4239         push @local_headers, basename ($out)
4240           if dirname ($out) eq $relative_dir;
4241       }
4243     if (@local_headers)
4244       {
4245         # We need to make sure config.h is built before we recurse.
4246         # We also want to make sure that built sources are built
4247         # before any ordinary `all' targets are run.  We can't do this
4248         # by changing the order of dependencies to the "all" because
4249         # that breaks when using parallel makes.  Instead we handle
4250         # things explicitly.
4251         $output_all .= ("all: @local_headers"
4252                         . "\n\t"
4253                         . '$(MAKE) $(AM_MAKEFLAGS) '
4254                         . (var ('SUBDIRS') ? 'all-recursive' : 'all-am')
4255                         . "\n\n");
4256       }
4257     else
4258       {
4259         $output_all .= "all: " . (var ('SUBDIRS')
4260                                   ? 'all-recursive' : 'all-am') . "\n\n";
4261       }
4265 # &do_check_merge_target ()
4266 # -------------------------
4267 # Handle check merge target specially.
4268 sub do_check_merge_target ()
4270   # Include user-defined local form of target.
4271   push @check_tests, 'check-local'
4272     if user_phony_rule 'check-local';
4274   # In --cygnus mode, check doesn't depend on all.
4275   if (option 'cygnus')
4276     {
4277       # Just run the local check rules.
4278       pretty_print_rule ('check-am:', "\t\t", @check);
4279     }
4280   else
4281     {
4282       # The check target must depend on the local equivalent of
4283       # `all', to ensure all the primary targets are built.  Then it
4284       # must build the local check rules.
4285       $output_rules .= "check-am: all-am\n";
4286       pretty_print_rule ("\t\$(MAKE) \$(AM_MAKEFLAGS)", "\t  ",
4287                          @check)
4288         if @check;
4289     }
4290   pretty_print_rule ("\t\$(MAKE) \$(AM_MAKEFLAGS)", "\t  ",
4291                      @check_tests)
4292     if @check_tests;
4294   depend '.PHONY', 'check', 'check-am';
4295   # Handle recursion.  We have to honor BUILT_SOURCES like for `all:'.
4296   $output_rules .= ("check: "
4297                     . (var ('BUILT_SOURCES')
4298                        ? "\$(BUILT_SOURCES)\n\t\$(MAKE) \$(AM_MAKEFLAGS) "
4299                        : '')
4300                     . (var ('SUBDIRS') ? 'check-recursive' : 'check-am')
4301                     . "\n");
4304 # handle_clean ($MAKEFILE)
4305 # ------------------------
4306 # Handle all 'clean' targets.
4307 sub handle_clean ($)
4309   my ($makefile) = @_;
4311   # Clean the files listed in user variables if they exist.
4312   $clean_files{'$(MOSTLYCLEANFILES)'} = MOSTLY_CLEAN
4313     if var ('MOSTLYCLEANFILES');
4314   $clean_files{'$(CLEANFILES)'} = CLEAN
4315     if var ('CLEANFILES');
4316   $clean_files{'$(DISTCLEANFILES)'} = DIST_CLEAN
4317     if var ('DISTCLEANFILES');
4318   $clean_files{'$(MAINTAINERCLEANFILES)'} = MAINTAINER_CLEAN
4319     if var ('MAINTAINERCLEANFILES');
4321   # Built sources are automatically removed by maintainer-clean.
4322   $clean_files{'$(BUILT_SOURCES)'} = MAINTAINER_CLEAN
4323     if var ('BUILT_SOURCES');
4325   # Compute a list of "rm"s to run for each target.
4326   my %rms = (MOSTLY_CLEAN, [],
4327              CLEAN, [],
4328              DIST_CLEAN, [],
4329              MAINTAINER_CLEAN, []);
4331   foreach my $file (keys %clean_files)
4332     {
4333       my $when = $clean_files{$file};
4334       prog_error 'invalid entry in %clean_files'
4335         unless exists $rms{$when};
4337       my $rm = "rm -f $file";
4338       # If file is a variable, make sure when don't call `rm -f' without args.
4339       $rm ="test -z \"$file\" || $rm"
4340         if ($file =~ /^\s*\$(\(.*\)|\{.*\})\s*$/);
4342       push @{$rms{$when}}, "\t-$rm\n";
4343     }
4345   $output_rules .= &file_contents
4346     ('clean',
4347      new Automake::Location,
4348      MOSTLYCLEAN_RMS      => join ('', sort @{$rms{&MOSTLY_CLEAN}}),
4349      CLEAN_RMS            => join ('', sort @{$rms{&CLEAN}}),
4350      DISTCLEAN_RMS        => join ('', sort @{$rms{&DIST_CLEAN}}),
4351      MAINTAINER_CLEAN_RMS => join ('', sort @{$rms{&MAINTAINER_CLEAN}}),
4352      MAKEFILE             => basename $makefile,
4353      );
4357 # &target_cmp ($A, $B)
4358 # --------------------
4359 # Subroutine for &handle_factored_dependencies to let `.PHONY' be last.
4360 sub target_cmp
4362     return 0
4363         if $a eq $b;
4364     return -1
4365         if $b eq '.PHONY';
4366     return 1
4367         if $a eq '.PHONY';
4368     return $a cmp $b;
4372 # &handle_factored_dependencies ()
4373 # --------------------------------
4374 # Handle everything related to gathered targets.
4375 sub handle_factored_dependencies
4377   # Reject bad hooks.
4378   foreach my $utarg ('uninstall-data-local', 'uninstall-data-hook',
4379                      'uninstall-exec-local', 'uninstall-exec-hook')
4380     {
4381       my $x = $utarg;
4382       $x =~ s/(data|exec)-//;
4383       reject_rule ($utarg, "use `$x', not `$utarg'");
4384     }
4386   reject_rule ('install-local',
4387                "use `install-data-local' or `install-exec-local', "
4388                . "not `install-local'");
4390   reject_rule ('install-info-local',
4391                "`install-info-local' target defined but "
4392                . "`no-installinfo' option not in use")
4393     unless option 'no-installinfo';
4395   # Install the -local hooks.
4396   foreach (keys %dependencies)
4397     {
4398       # Hooks are installed on the -am targets.
4399       s/-am$// or next;
4400       depend ("$_-am", "$_-local")
4401         if user_phony_rule "$_-local";
4402     }
4404   # Install the -hook hooks.
4405   # FIXME: Why not be as liberal as we are with -local hooks?
4406   foreach ('install-exec', 'install-data', 'uninstall')
4407     {
4408       if (user_phony_rule "$_-hook")
4409         {
4410           $actions{"$_-am"} .=
4411             ("\t\@\$(NORMAL_INSTALL)\n"
4412              . "\t" . '$(MAKE) $(AM_MAKEFLAGS) ' . "$_-hook\n");
4413         }
4414     }
4416   # All the required targets are phony.
4417   depend ('.PHONY', keys %required_targets);
4419   # Actually output gathered targets.
4420   foreach (sort target_cmp keys %dependencies)
4421     {
4422       # If there is nothing about this guy, skip it.
4423       next
4424         unless (@{$dependencies{$_}}
4425                 || $actions{$_}
4426                 || $required_targets{$_});
4428       # Define gathered targets in undefined conditions.
4429       # FIXME: Right now we must handle .PHONY as an exception,
4430       # because people write things like
4431       #    .PHONY: myphonytarget
4432       # to append dependencies.  This would not work if Automake
4433       # refrained from defining its own .PHONY target as it does
4434       # with other overridden targets.
4435       my @undefined_conds = (TRUE,);
4436       if ($_ ne '.PHONY')
4437         {
4438           @undefined_conds =
4439             Automake::Rule::define ($_, 'internal',
4440                                     RULE_AUTOMAKE, TRUE, INTERNAL);
4441         }
4442       my @uniq_deps = uniq (sort @{$dependencies{$_}});
4443       foreach my $cond (@undefined_conds)
4444         {
4445           my $condstr = $cond->subst_string;
4446           &pretty_print_rule ("$condstr$_:", "$condstr\t", @uniq_deps);
4447           $output_rules .= $actions{$_} if defined $actions{$_};
4448           $output_rules .= "\n";
4449         }
4450     }
4454 # &handle_tests_dejagnu ()
4455 # ------------------------
4456 sub handle_tests_dejagnu
4458     push (@check_tests, 'check-DEJAGNU');
4459     $output_rules .= file_contents ('dejagnu', new Automake::Location);
4463 # Handle TESTS variable and other checks.
4464 sub handle_tests
4466   if (option 'dejagnu')
4467     {
4468       &handle_tests_dejagnu;
4469     }
4470   else
4471     {
4472       foreach my $c ('DEJATOOL', 'RUNTEST', 'RUNTESTFLAGS')
4473         {
4474           reject_var ($c, "`$c' defined but `dejagnu' not in "
4475                       . "`AUTOMAKE_OPTIONS'");
4476         }
4477     }
4479   if (var ('TESTS'))
4480     {
4481       push (@check_tests, 'check-TESTS');
4482       $output_rules .= &file_contents ('check', new Automake::Location);
4483     }
4486 # Handle Emacs Lisp.
4487 sub handle_emacs_lisp
4489   my @elfiles = &am_install_var ('-candist', 'lisp', 'LISP',
4490                                  'lisp', 'noinst');
4492   return if ! @elfiles;
4494   define_pretty_variable ('am__ELFILES', TRUE, INTERNAL,
4495                           map { $_->[1] } @elfiles);
4496   define_pretty_variable ('am__ELCFILES', TRUE, INTERNAL,
4497                           '$(am__ELFILES:.el=.elc)');
4498   # This one can be overridden by users.
4499   define_pretty_variable ('ELCFILES', TRUE, INTERNAL, '$(LISP:.el=.elc)');
4501   push @all, '$(ELCFILES)';
4503   require_variables ($elfiles[0][0], "Emacs Lisp sources seen", TRUE,
4504                      'EMACS', 'lispdir');
4505   require_conf_file ($elfiles[0][0], FOREIGN, 'elisp-comp');
4506   &define_variable ('elisp_comp', "$am_config_aux_dir/elisp-comp", INTERNAL);
4509 # Handle Python
4510 sub handle_python
4512   my @pyfiles = &am_install_var ('-defaultdist', 'python', 'PYTHON',
4513                                  'noinst');
4514   return if ! @pyfiles;
4516   require_variables ($pyfiles[0][0], "Python sources seen", TRUE, 'PYTHON');
4517   require_conf_file ($pyfiles[0][0], FOREIGN, 'py-compile');
4518   &define_variable ('py_compile', "$am_config_aux_dir/py-compile", INTERNAL);
4521 # Handle Java.
4522 sub handle_java
4524     my @sourcelist = &am_install_var ('-candist',
4525                                       'java', 'JAVA',
4526                                       'java', 'noinst', 'check');
4527     return if ! @sourcelist;
4529     my @prefix = am_primary_prefixes ('JAVA', 1,
4530                                       'java', 'noinst', 'check');
4532     my $dir;
4533     foreach my $curs (@prefix)
4534       {
4535         next
4536           if $curs eq 'EXTRA';
4538         err_var "${curs}_JAVA", "multiple _JAVA primaries in use"
4539           if defined $dir;
4540         $dir = $curs;
4541       }
4544     push (@all, 'class' . $dir . '.stamp');
4548 # Handle some of the minor options.
4549 sub handle_minor_options
4551   if (option 'readme-alpha')
4552     {
4553       if ($relative_dir eq '.')
4554         {
4555           if ($package_version !~ /^$GNITS_VERSION_PATTERN$/)
4556             {
4557               msg ('error-gnits', $package_version_location,
4558                    "version `$package_version' doesn't follow " .
4559                    "Gnits standards");
4560             }
4561           if (defined $1 && -f 'README-alpha')
4562             {
4563               # This means we have an alpha release.  See
4564               # GNITS_VERSION_PATTERN for details.
4565               push_dist_common ('README-alpha');
4566             }
4567         }
4568     }
4571 ################################################################
4573 # ($OUTPUT, @INPUTS)
4574 # &split_config_file_spec ($SPEC)
4575 # -------------------------------
4576 # Decode the Autoconf syntax for config files (files, headers, links
4577 # etc.).
4578 sub split_config_file_spec ($)
4580   my ($spec) = @_;
4581   my ($output, @inputs) = split (/:/, $spec);
4583   push @inputs, "$output.in"
4584     unless @inputs;
4586   return ($output, @inputs);
4589 # $input
4590 # locate_am (@POSSIBLE_SOURCES)
4591 # -----------------------------
4592 # AC_CONFIG_FILES allow specifications such as Makefile:top.in:mid.in:bot.in
4593 # This functions returns the first *.in file for which a *.am exists.
4594 # It returns undef otherwise.
4595 sub locate_am (@)
4597   my (@rest) = @_;
4598   my $input;
4599   foreach my $file (@rest)
4600     {
4601       if (($file =~ /^(.*)\.in$/) && -f "$1.am")
4602         {
4603           $input = $file;
4604           last;
4605         }
4606     }
4607   return $input;
4610 my %make_list;
4612 # &scan_autoconf_config_files ($WHERE, $CONFIG-FILES)
4613 # ---------------------------------------------------
4614 # Study $CONFIG-FILES which is the first argument to AC_CONFIG_FILES
4615 # (or AC_OUTPUT).
4616 sub scan_autoconf_config_files ($$)
4618   my ($where, $config_files) = @_;
4620   # Look at potential Makefile.am's.
4621   foreach (split ' ', $config_files)
4622     {
4623       # Must skip empty string for Perl 4.
4624       next if $_ eq "\\" || $_ eq '';
4626       # Handle $local:$input syntax.
4627       my ($local, @rest) = split (/:/);
4628       @rest = ("$local.in",) unless @rest;
4629       my $input = locate_am @rest;
4630       if ($input)
4631         {
4632           # We have a file that automake should generate.
4633           $make_list{$input} = join (':', ($local, @rest));
4634         }
4635       else
4636         {
4637           # We have a file that automake should cause to be
4638           # rebuilt, but shouldn't generate itself.
4639           push (@other_input_files, $_);
4640         }
4641       $ac_config_files_location{$local} = $where;
4642     }
4646 # &scan_autoconf_traces ($FILENAME)
4647 # ---------------------------------
4648 sub scan_autoconf_traces ($)
4650   my ($filename) = @_;
4652   # Macros to trace, with their minimal number of arguments.
4653   #
4654   # IMPORTANT: If you add a macro here, you should also add this macro
4655   # =========  to Automake-preselection in autoconf/lib/autom4te.in.
4656   my %traced = (
4657                 AC_CANONICAL_BUILD => 0,
4658                 AC_CANONICAL_HOST => 0,
4659                 AC_CANONICAL_TARGET => 0,
4660                 AC_CONFIG_AUX_DIR => 1,
4661                 AC_CONFIG_FILES => 1,
4662                 AC_CONFIG_HEADERS => 1,
4663                 AC_CONFIG_LINKS => 1,
4664                 AC_INIT => 0,
4665                 AC_LIBSOURCE => 1,
4666                 AC_REQUIRE_AUX_FILE => 1,
4667                 AC_SUBST => 1,
4668                 AM_AUTOMAKE_VERSION => 1,
4669                 AM_CONDITIONAL => 2,
4670                 AM_ENABLE_MULTILIB => 0,
4671                 AM_GNU_GETTEXT => 0,
4672                 AM_INIT_AUTOMAKE => 0,
4673                 AM_MAINTAINER_MODE => 0,
4674                 AM_PROG_CC_C_O => 0,
4675                 LT_SUPPORTED_TAG => 1,
4676                 _LT_AC_TAGCONFIG => 0,
4677                 m4_include => 1,
4678                 m4_sinclude => 1,
4679                 sinclude => 1,
4680               );
4682   my $traces = ($ENV{AUTOCONF} || 'autoconf') . " ";
4684   # Use a separator unlikely to be used, not `:', the default, which
4685   # has a precise meaning for AC_CONFIG_FILES and so on.
4686   $traces .= join (' ',
4687                    map { "--trace=$_" . ':\$f:\$l::\$n::\${::}%' }
4688                    (keys %traced));
4690   my $tracefh = new Automake::XFile ("$traces $filename |");
4691   verb "reading $traces";
4693   while ($_ = $tracefh->getline)
4694     {
4695       chomp;
4696       my ($here, @args) = split (/::/);
4697       my $where = new Automake::Location $here;
4698       my $macro = $args[0];
4700       prog_error ("unrequested trace `$macro'")
4701         unless exists $traced{$macro};
4703       # Skip and diagnose malformed calls.
4704       if ($#args < $traced{$macro})
4705         {
4706           msg ('syntax', $where, "not enough arguments for $macro");
4707           next;
4708         }
4710       # Alphabetical ordering please.
4711       if ($macro eq 'AC_CANONICAL_BUILD')
4712         {
4713           if ($seen_canonical <= AC_CANONICAL_BUILD)
4714             {
4715               $seen_canonical = AC_CANONICAL_BUILD;
4716               $canonical_location = $where;
4717             }
4718         }
4719       elsif ($macro eq 'AC_CANONICAL_HOST')
4720         {
4721           if ($seen_canonical <= AC_CANONICAL_HOST)
4722             {
4723               $seen_canonical = AC_CANONICAL_HOST;
4724               $canonical_location = $where;
4725             }
4726         }
4727       elsif ($macro eq 'AC_CANONICAL_TARGET')
4728         {
4729           $seen_canonical = AC_CANONICAL_TARGET;
4730           $canonical_location = $where;
4731         }
4732       elsif ($macro eq 'AC_CONFIG_AUX_DIR')
4733         {
4734           if ($seen_init_automake)
4735             {
4736               error ($where, "AC_CONFIG_AUX_DIR must be called before "
4737                      . "AM_INIT_AUTOMAKE...", partial => 1);
4738               error ($seen_init_automake, "... AM_INIT_AUTOMAKE called here");
4739             }
4740           $config_aux_dir = $args[1];
4741           $config_aux_dir_set_in_configure_ac = 1;
4742           $relative_dir = '.';
4743           check_directory ($config_aux_dir, $where);
4744         }
4745       elsif ($macro eq 'AC_CONFIG_FILES')
4746         {
4747           # Look at potential Makefile.am's.
4748           scan_autoconf_config_files ($where, $args[1]);
4749         }
4750       elsif ($macro eq 'AC_CONFIG_HEADERS')
4751         {
4752           foreach my $spec (split (' ', $args[1]))
4753             {
4754               my ($dest, @src) = split (':', $spec);
4755               $ac_config_files_location{$dest} = $where;
4756               push @config_headers, $spec;
4757             }
4758         }
4759       elsif ($macro eq 'AC_CONFIG_LINKS')
4760         {
4761           foreach my $spec (split (' ', $args[1]))
4762             {
4763               my ($dest, $src) = split (':', $spec);
4764               $ac_config_files_location{$dest} = $where;
4765               push @config_links, $spec;
4766             }
4767         }
4768       elsif ($macro eq 'AC_INIT')
4769         {
4770           if (defined $args[2])
4771             {
4772               $package_version = $args[2];
4773               $package_version_location = $where;
4774             }
4775         }
4776       elsif ($macro eq 'AC_LIBSOURCE')
4777         {
4778           $libsources{$args[1]} = $here;
4779         }
4780       elsif ($macro eq 'AC_SUBST')
4781         {
4782           # Just check for alphanumeric in AC_SUBST.  If you do
4783           # AC_SUBST(5), then too bad.
4784           $configure_vars{$args[1]} = $where
4785             if $args[1] =~ /^\w+$/;
4786         }
4787       elsif ($macro eq 'AM_AUTOMAKE_VERSION')
4788         {
4789           error ($where,
4790                  "version mismatch.  This is Automake $VERSION,\n" .
4791                  "but the definition used by this AM_INIT_AUTOMAKE\n" .
4792                  "comes from Automake $args[1].  You should recreate\n" .
4793                  "aclocal.m4 with aclocal and run automake again.\n",
4794                  # $? = 63 is used to indicate version mismatch to missing.
4795                  exit_code => 63)
4796             if $VERSION ne $args[1];
4798           $seen_automake_version = 1;
4799         }
4800       elsif ($macro eq 'AM_CONDITIONAL')
4801         {
4802           $configure_cond{$args[1]} = $where;
4803         }
4804       elsif ($macro eq 'AM_ENABLE_MULTILIB')
4805         {
4806           $seen_multilib = $where;
4807         }
4808       elsif ($macro eq 'AM_GNU_GETTEXT')
4809         {
4810           $seen_gettext = $where;
4811           $ac_gettext_location = $where;
4812           $seen_gettext_external = grep ($_ eq 'external', @args);
4813         }
4814       elsif ($macro eq 'AM_INIT_AUTOMAKE')
4815         {
4816           $seen_init_automake = $where;
4817           if (defined $args[2])
4818             {
4819               $package_version = $args[2];
4820               $package_version_location = $where;
4821             }
4822           elsif (defined $args[1])
4823             {
4824               exit $exit_code
4825                 if (process_global_option_list ($where,
4826                                                 split (' ', $args[1])));
4827             }
4828         }
4829       elsif ($macro eq 'AM_MAINTAINER_MODE')
4830         {
4831           $seen_maint_mode = $where;
4832         }
4833       elsif ($macro eq 'AM_PROG_CC_C_O')
4834         {
4835           $seen_cc_c_o = $where;
4836         }
4837       elsif ($macro eq 'AC_REQUIRE_AUX_FILE')
4838         {
4839           # Only remember the first time a file is required.
4840           $required_aux_file{$args[1]} = $where
4841             unless exists $required_aux_file{$args[1]};
4842         }
4843       elsif ($macro eq 'm4_include'
4844              || $macro eq 'm4_sinclude'
4845              || $macro eq 'sinclude')
4846         {
4847           # Some modified versions of Autoconf don't use
4848           # forzen files.  Consequently it's possible that we see all
4849           # m4_include's performed during Autoconf's startup.
4850           # Obviously we don't want to distribute Autoconf's files
4851           # so we skip absolute filenames here.
4852           push @configure_deps, '$(top_srcdir)/' . $args[1]
4853             unless $here =~ m,^(?:\w:)?[\\/],;
4854           # Keep track of the greatest timestamp.
4855           if (-e $args[1])
4856             {
4857               my $mtime = mtime $args[1];
4858               $configure_deps_greatest_timestamp = $mtime
4859                 if $mtime > $configure_deps_greatest_timestamp;
4860             }
4861         }
4862       elsif ($macro eq 'LT_SUPPORTED_TAG')
4863         {
4864           $libtool_tags{$args[1]} = 1;
4865           $libtool_new_api = 1;
4866         }
4867       elsif ($macro eq '_LT_AC_TAGCONFIG')
4868         {
4869           # _LT_AC_TAGCONFIG is an old macro present in Libtool 1.5.
4870           # We use it to detect whether tags are supported.  Our
4871           # prefered interface is LT_SUPPORTED_TAG, but it was
4872           # introduced in Libtool 1.6.
4873           if (0 == keys %libtool_tags)
4874             {
4875               # Hardcode the tags supported by Libtool 1.5.
4876               %libtool_tags = (CC => 1, CXX => 1, GCJ => 1, F77 => 1);
4877             }
4878         }
4879     }
4881   $tracefh->close;
4885 # &scan_autoconf_files ()
4886 # -----------------------
4887 # Check whether we use `configure.ac' or `configure.in'.
4888 # Scan it (and possibly `aclocal.m4') for interesting things.
4889 # We must scan aclocal.m4 because there might be AC_SUBSTs and such there.
4890 sub scan_autoconf_files ()
4892   # Reinitialize libsources here.  This isn't really necessary,
4893   # since we currently assume there is only one configure.ac.  But
4894   # that won't always be the case.
4895   %libsources = ();
4897   # Keep track of the youngest configure dependency.
4898   $configure_deps_greatest_timestamp = mtime $configure_ac;
4899   if (-e 'aclocal.m4')
4900     {
4901       my $mtime = mtime 'aclocal.m4';
4902       $configure_deps_greatest_timestamp = $mtime
4903         if $mtime > $configure_deps_greatest_timestamp;
4904     }
4906   scan_autoconf_traces ($configure_ac);
4908   @configure_input_files = sort keys %make_list;
4909   # Set input and output files if not specified by user.
4910   if (! @input_files)
4911     {
4912       @input_files = @configure_input_files;
4913       %output_files = %make_list;
4914     }
4917   if (! $seen_init_automake)
4918     {
4919       err_ac ("no proper invocation of AM_INIT_AUTOMAKE was found.\nYou "
4920               . "should verify that $configure_ac invokes AM_INIT_AUTOMAKE,"
4921               . "\nthat aclocal.m4 is present in the top-level directory,\n"
4922               . "and that aclocal.m4 was recently regenerated "
4923               . "(using aclocal).");
4924     }
4925   else
4926     {
4927       if (! $seen_automake_version)
4928         {
4929           if (-f 'aclocal.m4')
4930             {
4931               error ($seen_init_automake,
4932                      "your implementation of AM_INIT_AUTOMAKE comes from " .
4933                      "an\nold Automake version.  You should recreate " .
4934                      "aclocal.m4\nwith aclocal and run automake again.\n",
4935                      # $? = 63 is used to indicate version mismatch to missing.
4936                      exit_code => 63);
4937             }
4938           else
4939             {
4940               error ($seen_init_automake,
4941                      "no proper implementation of AM_INIT_AUTOMAKE was " .
4942                      "found,\nprobably because aclocal.m4 is missing...\n" .
4943                      "You should run aclocal to create this file, then\n" .
4944                      "run automake again.\n");
4945             }
4946         }
4947     }
4949   locate_aux_dir ();
4951   # Reorder @input_files so that the Makefile that distributes aux
4952   # files is processed last.  This is important because each directory
4953   # can require auxiliary scripts and we should wait until they have
4954   # been installed before distributing them.
4956   # The Makefile.in that distribute the aux files is the one in
4957   # $config_aux_dir or the top-level Makefile.
4958   my $auxdirdist = is_make_dir ($config_aux_dir) ? $config_aux_dir : '.';
4959   my @new_input_files = ();
4960   while (@input_files)
4961     {
4962       my $in = pop @input_files;
4963       my @ins = split (/:/, $output_files{$in});
4964       if (dirname ($ins[0]) eq $auxdirdist)
4965         {
4966           push @new_input_files, $in;
4967           $automake_will_process_aux_dir = 1;
4968         }
4969       else
4970         {
4971           unshift @new_input_files, $in;
4972         }
4973     }
4974   @input_files = @new_input_files;
4976   # If neither the auxdir/Makefile nor the ./Makefile are generated
4977   # by Automake, we won't distribute the aux files anyway.  Assume
4978   # the user know what (s)he does, and pretend we will distribute
4979   # them to disable the error in require_file_internal.
4980   $automake_will_process_aux_dir = 1 if ! is_make_dir ($auxdirdist);
4982   # Look for some files we need.  Always check for these.  This
4983   # check must be done for every run, even those where we are only
4984   # looking at a subdir Makefile.  We must set relative_dir for
4985   # maybe_push_required_file to work.
4986   $relative_dir = '.';
4987   foreach my $file (keys %required_aux_file)
4988     {
4989       require_conf_file ($required_aux_file{$file}->get, FOREIGN, $file)
4990     }
4991   err_am "`install.sh' is an anachronism; use `install-sh' instead"
4992     if -f $config_aux_dir . '/install.sh';
4994   # Preserve dist_common for later.
4995   $configure_dist_common = variable_value ('DIST_COMMON') || '';
4999 ################################################################
5001 # Set up for Cygnus mode.
5002 sub check_cygnus
5004   my $cygnus = option 'cygnus';
5005   return unless $cygnus;
5007   set_strictness ('foreign');
5008   set_option ('no-installinfo', $cygnus);
5009   set_option ('no-dependencies', $cygnus);
5010   set_option ('no-dist', $cygnus);
5012   err_ac "`AM_MAINTAINER_MODE' required when --cygnus specified"
5013     if !$seen_maint_mode;
5016 # Do any extra checking for GNU standards.
5017 sub check_gnu_standards
5019   if ($relative_dir eq '.')
5020     {
5021       # In top level (or only) directory.
5022       require_file ("$am_file.am", GNU,
5023                     qw/INSTALL NEWS README AUTHORS ChangeLog/);
5025       # Accept one of these three licenses; default to COPYING.
5026       # Make sure we do not overwrite an existing license.
5027       my $license;
5028       foreach (qw /COPYING COPYING.LIB COPYING.LESSER/)
5029         {
5030           if (-f $_)
5031             {
5032               $license = $_;
5033               last;
5034             }
5035         }
5036       require_file ("$am_file.am", GNU, 'COPYING')
5037         unless $license;
5038     }
5040   for my $opt ('no-installman', 'no-installinfo')
5041     {
5042       msg ('error-gnu', option $opt,
5043            "option `$opt' disallowed by GNU standards")
5044         if option $opt;
5045     }
5048 # Do any extra checking for GNITS standards.
5049 sub check_gnits_standards
5051   if ($relative_dir eq '.')
5052     {
5053       # In top level (or only) directory.
5054       require_file ("$am_file.am", GNITS, 'THANKS');
5055     }
5058 ################################################################
5060 # Functions to handle files of each language.
5062 # Each `lang_X_rewrite($DIRECTORY, $BASE, $EXT)' function follows a
5063 # simple formula: Return value is LANG_SUBDIR if the resulting object
5064 # file should be in a subdir if the source file is, LANG_PROCESS if
5065 # file is to be dealt with, LANG_IGNORE otherwise.
5067 # Much of the actual processing is handled in
5068 # handle_single_transform.  These functions exist so that
5069 # auxiliary information can be recorded for a later cleanup pass.
5070 # Note that the calls to these functions are computed, so don't bother
5071 # searching for their precise names in the source.
5073 # This is just a convenience function that can be used to determine
5074 # when a subdir object should be used.
5075 sub lang_sub_obj
5077     return option 'subdir-objects' ? LANG_SUBDIR : LANG_PROCESS;
5080 # Rewrite a single C source file.
5081 sub lang_c_rewrite
5083   my ($directory, $base, $ext, $nonansi_obj, $have_per_exec_flags, $var) = @_;
5085   if (option 'ansi2knr' && $base =~ /_$/)
5086     {
5087       # FIXME: include line number in error.
5088       err_am "C source file `$base.c' would be deleted by ansi2knr rules";
5089     }
5091   my $r = LANG_PROCESS;
5092   if (option 'subdir-objects')
5093     {
5094       $r = LANG_SUBDIR;
5095       if ($directory && $directory ne '.')
5096         {
5097           $base = $directory . '/' . $base;
5099           # libtool is always able to put the object at the proper place,
5100           # so we do not have to require AM_PROG_CC_C_O when building .lo files.
5101           err_var ($var, "compiling `$base.c' in subdir requires "
5102                    . "`AM_PROG_CC_C_O' in `$configure_ac'",
5103                    uniq_scope => US_GLOBAL, uniq_part => UP_TEXT)
5104             unless $seen_cc_c_o || $nonansi_obj eq '.lo';
5105         }
5107       # In this case we already have the directory information, so
5108       # don't add it again.
5109       $de_ansi_files{$base} = '';
5110     }
5111   else
5112     {
5113       $de_ansi_files{$base} = (($directory eq '.' || $directory eq '')
5114                                ? ''
5115                                : "$directory/");
5116     }
5118   if (! $seen_cc_c_o
5119       && $have_per_exec_flags
5120       && ! option 'subdir-objects'
5121       && $nonansi_obj ne '.lo')
5122     {
5123       err_var ($var, "compiling `$base.c' with per-target flags requires "
5124                . "`AM_PROG_CC_C_O' in `$configure_ac'",
5125                uniq_scope => US_GLOBAL, uniq_part => UP_TEXT)
5126     }
5128     return $r;
5131 # Rewrite a single C++ source file.
5132 sub lang_cxx_rewrite
5134     return &lang_sub_obj;
5137 # Rewrite a single header file.
5138 sub lang_header_rewrite
5140     # Header files are simply ignored.
5141     return LANG_IGNORE;
5144 # Rewrite a single yacc file.
5145 sub lang_yacc_rewrite
5147     my ($directory, $base, $ext) = @_;
5149     my $r = &lang_sub_obj;
5150     (my $newext = $ext) =~ tr/y/c/;
5151     return ($r, $newext);
5154 # Rewrite a single yacc++ file.
5155 sub lang_yaccxx_rewrite
5157     my ($directory, $base, $ext) = @_;
5159     my $r = &lang_sub_obj;
5160     (my $newext = $ext) =~ tr/y/c/;
5161     return ($r, $newext);
5164 # Rewrite a single lex file.
5165 sub lang_lex_rewrite
5167     my ($directory, $base, $ext) = @_;
5169     my $r = &lang_sub_obj;
5170     (my $newext = $ext) =~ tr/l/c/;
5171     return ($r, $newext);
5174 # Rewrite a single lex++ file.
5175 sub lang_lexxx_rewrite
5177     my ($directory, $base, $ext) = @_;
5179     my $r = &lang_sub_obj;
5180     (my $newext = $ext) =~ tr/l/c/;
5181     return ($r, $newext);
5184 # Rewrite a single assembly file.
5185 sub lang_asm_rewrite
5187     return &lang_sub_obj;
5190 # Rewrite a single Fortran 77 file.
5191 sub lang_f77_rewrite
5193     return LANG_PROCESS;
5196 # Rewrite a single Fortran file.
5197 sub lang_fc_rewrite
5199     return LANG_PROCESS;
5202 # Rewrite a single preprocessed Fortran file.
5203 sub lang_ppfc_rewrite
5205     return LANG_PROCESS;
5208 # Rewrite a single preprocessed Fortran 77 file.
5209 sub lang_ppf77_rewrite
5211     return LANG_PROCESS;
5214 # Rewrite a single ratfor file.
5215 sub lang_ratfor_rewrite
5217     return LANG_PROCESS;
5220 # Rewrite a single Objective C file.
5221 sub lang_objc_rewrite
5223     return &lang_sub_obj;
5226 # Rewrite a single Java file.
5227 sub lang_java_rewrite
5229     return LANG_SUBDIR;
5232 # The lang_X_finish functions are called after all source file
5233 # processing is done.  Each should handle defining rules for the
5234 # language, etc.  A finish function is only called if a source file of
5235 # the appropriate type has been seen.
5237 sub lang_c_finish
5239     # Push all libobjs files onto de_ansi_files.  We actually only
5240     # push files which exist in the current directory, and which are
5241     # genuine source files.
5242     foreach my $file (keys %libsources)
5243     {
5244         if ($file =~ /^(.*)\.[cly]$/ && -f "$relative_dir/$file")
5245         {
5246             $de_ansi_files{$1} = ''
5247         }
5248     }
5250     if (option 'ansi2knr' && keys %de_ansi_files)
5251     {
5252         # Make all _.c files depend on their corresponding .c files.
5253         my @objects;
5254         foreach my $base (sort keys %de_ansi_files)
5255         {
5256             # Each _.c file must depend on ansi2knr; otherwise it
5257             # might be used in a parallel build before it is built.
5258             # We need to support files in the srcdir and in the build
5259             # dir (because these files might be auto-generated.  But
5260             # we can't use $< -- some makes only define $< during a
5261             # suffix rule.
5262             my $ansfile = $de_ansi_files{$base} . $base . '.c';
5263             $output_rules .= ($base . "_.c: $ansfile \$(ANSI2KNR)\n\t"
5264                               . '$(CPP) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) '
5265                               . '`if test -f $(srcdir)/' . $ansfile
5266                               . '; then echo $(srcdir)/' . $ansfile
5267                               . '; else echo ' . $ansfile . '; fi` '
5268                               . "| sed 's/^# \\([0-9]\\)/#line \\1/' "
5269                               . '| $(ANSI2KNR) > $@'
5270                               # If ansi2knr fails then we shouldn't
5271                               # create the _.c file
5272                               . " || rm -f \$\@\n");
5273             push (@objects, $base . '_.$(OBJEXT)');
5274             push (@objects, $base . '_.lo')
5275               if var ('LIBTOOL');
5277             # Explicitly clean the _.c files if they are in a
5278             # subdirectory. (In the current directory they get erased
5279             # by a `rm -f *_.c' rule.)
5280             $clean_files{$base . '_.c'} = MOSTLY_CLEAN
5281               if dirname ($base) ne '.';
5282         }
5284         # Make all _.o (and _.lo) files depend on ansi2knr.
5285         # Use a sneaky little hack to make it print nicely.
5286         &pretty_print_rule ('', '', @objects, ':', '$(ANSI2KNR)');
5287     }
5290 # This is a yacc helper which is called whenever we have decided to
5291 # compile a yacc file.
5292 sub lang_yacc_target_hook
5294     my ($self, $aggregate, $output, $input, %transform) = @_;
5296     my $flag = $aggregate . "_YFLAGS";
5297     my $flagvar = var $flag;
5298     my $YFLAGSvar = var 'YFLAGS';
5299     if (($flagvar && $flagvar->variable_value =~ /$DASH_D_PATTERN/o)
5300         || ($YFLAGSvar && $YFLAGSvar->variable_value =~ /$DASH_D_PATTERN/o))
5301     {
5302         (my $output_base = $output) =~ s/$KNOWN_EXTENSIONS_PATTERN$//;
5303         my $header = $output_base . '.h';
5305         # Found a `-d' that applies to the compilation of this file.
5306         # Add a dependency for the generated header file, and arrange
5307         # for that file to be included in the distribution.
5308         foreach my $cond (Automake::Rule::define (${header}, 'internal',
5309                                                   RULE_AUTOMAKE, TRUE,
5310                                                   INTERNAL))
5311           {
5312             my $condstr = $cond->subst_string;
5313             $output_rules .= ("$condstr${header}: $output\n"
5314                               # Recover from removal of $header
5315                               . "$condstr\t\@if test ! -f \$@; then \\\n"
5316                               . "$condstr\t  rm -f $output; \\\n"
5317                               . "$condstr\t  \$(MAKE) $output; \\\n"
5318                               . "$condstr\telse :; fi\n");
5319           }
5320         # Distribute the generated file, unless its .y source was
5321         # listed in a nodist_ variable.  (&handle_source_transform
5322         # will set DIST_SOURCE.)
5323         &push_dist_common ($header)
5324           if $transform{'DIST_SOURCE'};
5326         # If the files are built in the build directory, then we want
5327         # to remove them with `make clean'.  If they are in srcdir
5328         # they shouldn't be touched.  However, we can't determine this
5329         # statically, and the GNU rules say that yacc/lex output files
5330         # should be removed by maintainer-clean.  So that's what we
5331         # do.
5332         $clean_files{$header} = MAINTAINER_CLEAN;
5333     }
5334     # Erase $OUTPUT on `make maintainer-clean' (by GNU standards).
5335     # See the comment above for $HEADER.
5336     $clean_files{$output} = MAINTAINER_CLEAN;
5339 # This is a lex helper which is called whenever we have decided to
5340 # compile a lex file.
5341 sub lang_lex_target_hook
5343     my ($self, $aggregate, $output, $input) = @_;
5344     # If the files are built in the build directory, then we want to
5345     # remove them with `make clean'.  If they are in srcdir they
5346     # shouldn't be touched.  However, we can't determine this
5347     # statically, and the GNU rules say that yacc/lex output files
5348     # should be removed by maintainer-clean.  So that's what we do.
5349     $clean_files{$output} = MAINTAINER_CLEAN;
5352 # This is a helper for both lex and yacc.
5353 sub yacc_lex_finish_helper
5355   return if defined $language_scratch{'lex-yacc-done'};
5356   $language_scratch{'lex-yacc-done'} = 1;
5358   # If there is more than one distinct yacc (resp lex) source file
5359   # in a given directory, then the `ylwrap' program is required to
5360   # allow parallel builds to work correctly.  FIXME: for now, no
5361   # line number.
5362   require_conf_file ($configure_ac, FOREIGN, 'ylwrap');
5363   &define_variable ('YLWRAP', "$am_config_aux_dir/ylwrap", INTERNAL);
5366 sub lang_yacc_finish
5368   return if defined $language_scratch{'yacc-done'};
5369   $language_scratch{'yacc-done'} = 1;
5371   reject_var 'YACCFLAGS', "`YACCFLAGS' obsolete; use `YFLAGS' instead";
5373   &yacc_lex_finish_helper
5374     if count_files_for_language ('yacc') > 1;
5378 sub lang_lex_finish
5380   return if defined $language_scratch{'lex-done'};
5381   $language_scratch{'lex-done'} = 1;
5383   &yacc_lex_finish_helper
5384     if count_files_for_language ('lex') > 1;
5388 # Given a hash table of linker names, pick the name that has the most
5389 # precedence.  This is lame, but something has to have global
5390 # knowledge in order to eliminate the conflict.  Add more linkers as
5391 # required.
5392 sub resolve_linker
5394     my (%linkers) = @_;
5396     foreach my $l (qw(GCJLINK CXXLINK F77LINK FCLINK OBJCLINK))
5397     {
5398         return $l if defined $linkers{$l};
5399     }
5400     return 'LINK';
5403 # Called to indicate that an extension was used.
5404 sub saw_extension
5406     my ($ext) = @_;
5407     if (! defined $extension_seen{$ext})
5408     {
5409         $extension_seen{$ext} = 1;
5410     }
5411     else
5412     {
5413         ++$extension_seen{$ext};
5414     }
5417 # Return the number of files seen for a given language.  Knows about
5418 # special cases we care about.  FIXME: this is hideous.  We need
5419 # something that involves real language objects.  For instance yacc
5420 # and yaccxx could both derive from a common yacc class which would
5421 # know about the strange ylwrap requirement.  (Or better yet we could
5422 # just not support legacy yacc!)
5423 sub count_files_for_language
5425     my ($name) = @_;
5427     my @names;
5428     if ($name eq 'yacc' || $name eq 'yaccxx')
5429     {
5430         @names = ('yacc', 'yaccxx');
5431     }
5432     elsif ($name eq 'lex' || $name eq 'lexxx')
5433     {
5434         @names = ('lex', 'lexxx');
5435     }
5436     else
5437     {
5438         @names = ($name);
5439     }
5441     my $r = 0;
5442     foreach $name (@names)
5443     {
5444         my $lang = $languages{$name};
5445         foreach my $ext (@{$lang->extensions})
5446         {
5447             $r += $extension_seen{$ext}
5448                 if defined $extension_seen{$ext};
5449         }
5450     }
5452     return $r
5455 # Called to ask whether source files have been seen . If HEADERS is 1,
5456 # headers can be included.
5457 sub saw_sources_p
5459     my ($headers) = @_;
5461     # count all the sources
5462     my $count = 0;
5463     foreach my $val (values %extension_seen)
5464     {
5465         $count += $val;
5466     }
5468     if (!$headers)
5469     {
5470         $count -= count_files_for_language ('header');
5471     }
5473     return $count > 0;
5477 # register_language (%ATTRIBUTE)
5478 # ------------------------------
5479 # Register a single language.
5480 # Each %ATTRIBUTE is of the form ATTRIBUTE => VALUE.
5481 sub register_language (%)
5483   my (%option) = @_;
5485   # Set the defaults.
5486   $option{'ansi'} = 0
5487     unless defined $option{'ansi'};
5488   $option{'autodep'} = 'no'
5489     unless defined $option{'autodep'};
5490   $option{'linker'} = ''
5491     unless defined $option{'linker'};
5492   $option{'flags'} = []
5493     unless defined $option{'flags'};
5494   $option{'output_extensions'} = sub { return ( '.$(OBJEXT)', '.lo' ) }
5495     unless defined $option{'output_extensions'};
5496   $option{'nodist_specific'} = 0
5497     unless defined $option{'nodist_specific'};
5499   my $lang = new Language (%option);
5501   # Fill indexes.
5502   $extension_map{$_} = $lang->name foreach @{$lang->extensions};
5503   $languages{$lang->name} = $lang;
5505   # Update the pattern of known extensions.
5506   accept_extensions (@{$lang->extensions});
5508   # Upate the $suffix_rule map.
5509   foreach my $suffix (@{$lang->extensions})
5510     {
5511       foreach my $dest (&{$lang->output_extensions} ($suffix))
5512         {
5513           register_suffix_rule (INTERNAL, $suffix, $dest);
5514         }
5515     }
5518 # derive_suffix ($EXT, $OBJ)
5519 # --------------------------
5520 # This function is used to find a path from a user-specified suffix $EXT
5521 # to $OBJ or to some other suffix we recognize internally, e.g. `cc'.
5522 sub derive_suffix ($$)
5524   my ($source_ext, $obj) = @_;
5526   while (! $extension_map{$source_ext}
5527          && $source_ext ne $obj
5528          && exists $suffix_rules->{$source_ext}
5529          && exists $suffix_rules->{$source_ext}{$obj})
5530     {
5531       $source_ext = $suffix_rules->{$source_ext}{$obj}[0];
5532     }
5534   return $source_ext;
5538 ################################################################
5540 # Pretty-print something and append to output_rules.
5541 sub pretty_print_rule
5543     $output_rules .= &makefile_wrap (@_);
5547 ################################################################
5550 ## -------------------------------- ##
5551 ## Handling the conditional stack.  ##
5552 ## -------------------------------- ##
5555 # $STRING
5556 # make_conditional_string ($NEGATE, $COND)
5557 # ----------------------------------------
5558 sub make_conditional_string ($$)
5560   my ($negate, $cond) = @_;
5561   $cond = "${cond}_TRUE"
5562     unless $cond =~ /^TRUE|FALSE$/;
5563   $cond = Automake::Condition::conditional_negate ($cond)
5564     if $negate;
5565   return $cond;
5569 # $COND
5570 # cond_stack_if ($NEGATE, $COND, $WHERE)
5571 # --------------------------------------
5572 sub cond_stack_if ($$$)
5574   my ($negate, $cond, $where) = @_;
5576   error $where, "$cond does not appear in AM_CONDITIONAL"
5577     if ! $configure_cond{$cond} && $cond !~ /^TRUE|FALSE$/;
5579   push (@cond_stack, make_conditional_string ($negate, $cond));
5581   return new Automake::Condition (@cond_stack);
5585 # $COND
5586 # cond_stack_else ($NEGATE, $COND, $WHERE)
5587 # ----------------------------------------
5588 sub cond_stack_else ($$$)
5590   my ($negate, $cond, $where) = @_;
5592   if (! @cond_stack)
5593     {
5594       error $where, "else without if";
5595       return FALSE;
5596     }
5598   $cond_stack[$#cond_stack] =
5599     Automake::Condition::conditional_negate ($cond_stack[$#cond_stack]);
5601   # If $COND is given, check against it.
5602   if (defined $cond)
5603     {
5604       $cond = make_conditional_string ($negate, $cond);
5606       error ($where, "else reminder ($negate$cond) incompatible with "
5607              . "current conditional: $cond_stack[$#cond_stack]")
5608         if $cond_stack[$#cond_stack] ne $cond;
5609     }
5611   return new Automake::Condition (@cond_stack);
5615 # $COND
5616 # cond_stack_endif ($NEGATE, $COND, $WHERE)
5617 # -----------------------------------------
5618 sub cond_stack_endif ($$$)
5620   my ($negate, $cond, $where) = @_;
5621   my $old_cond;
5623   if (! @cond_stack)
5624     {
5625       error $where, "endif without if";
5626       return TRUE;
5627     }
5629   # If $COND is given, check against it.
5630   if (defined $cond)
5631     {
5632       $cond = make_conditional_string ($negate, $cond);
5634       error ($where, "endif reminder ($negate$cond) incompatible with "
5635              . "current conditional: $cond_stack[$#cond_stack]")
5636         if $cond_stack[$#cond_stack] ne $cond;
5637     }
5639   pop @cond_stack;
5641   return new Automake::Condition (@cond_stack);
5648 ## ------------------------ ##
5649 ## Handling the variables.  ##
5650 ## ------------------------ ##
5653 # &define_pretty_variable ($VAR, $COND, $WHERE, @VALUE)
5654 # -----------------------------------------------------
5655 # Like define_variable, but the value is a list, and the variable may
5656 # be defined conditionally.  The second argument is the Condition
5657 # under which the value should be defined; this should be the empty
5658 # string to define the variable unconditionally.  The third argument
5659 # is a list holding the values to use for the variable.  The value is
5660 # pretty printed in the output file.
5661 sub define_pretty_variable ($$$@)
5663     my ($var, $cond, $where, @value) = @_;
5665     if (! vardef ($var, $cond))
5666     {
5667         Automake::Variable::define ($var, VAR_AUTOMAKE, '', $cond, "@value",
5668                                     '', $where, VAR_PRETTY);
5669         rvar ($var)->rdef ($cond)->set_seen;
5670     }
5674 # define_variable ($VAR, $VALUE, $WHERE)
5675 # --------------------------------------
5676 # Define a new user variable VAR to VALUE, but only if not already defined.
5677 sub define_variable ($$$)
5679     my ($var, $value, $where) = @_;
5680     define_pretty_variable ($var, TRUE, $where, $value);
5684 # define_files_variable ($VAR, \@BASENAME, $EXTENSION, $WHERE)
5685 # -----------------------------------------------------------
5686 # Define the $VAR which content is the list of file names composed of
5687 # a @BASENAME and the $EXTENSION.
5688 sub define_files_variable ($\@$$)
5690   my ($var, $basename, $extension, $where) = @_;
5691   define_variable ($var,
5692                    join (' ', map { "$_.$extension" } @$basename),
5693                    $where);
5697 # Like define_variable, but define a variable to be the configure
5698 # substitution by the same name.
5699 sub define_configure_variable ($)
5701   my ($var) = @_;
5703   my $pretty = VAR_ASIS;
5704   my $owner = VAR_CONFIGURE;
5706   # Do not output the ANSI2KNR configure variable -- we AC_SUBST
5707   # it in protos.m4, but later redefine it elsewhere.  This is
5708   # pretty hacky.  We also don't output AMDEPBACKSLASH: it might
5709   # be subst'd by `\', which certainly would not be appreciated by
5710   # Make.
5711   if ($var eq 'ANSI2KNR' || $var eq 'AMDEPBACKSLASH')
5712     {
5713       $pretty = VAR_SILENT;
5714       $owner = VAR_AUTOMAKE;
5715     }
5717   Automake::Variable::define ($var, $owner, '', TRUE, subst $var,
5718                               '', $configure_vars{$var}, $pretty);
5722 # define_compiler_variable ($LANG)
5723 # --------------------------------
5724 # Define a compiler variable.  We also handle defining the `LT'
5725 # version of the command when using libtool.
5726 sub define_compiler_variable ($)
5728     my ($lang) = @_;
5730     my ($var, $value) = ($lang->compiler, $lang->compile);
5731     my $libtool_tag = '';
5732     $libtool_tag = '--tag=' . $lang->libtool_tag . ' '
5733       if $lang->libtool_tag && exists $libtool_tags{$lang->libtool_tag};
5734     &define_variable ($var, $value, INTERNAL);
5735     &define_variable ("LT$var",
5736                       "\$(LIBTOOL) --mode=compile $libtool_tag$value",
5737                       INTERNAL)
5738       if var ('LIBTOOL');
5742 # define_linker_variable ($LANG)
5743 # ------------------------------
5744 # Define linker variables.
5745 sub define_linker_variable ($)
5747     my ($lang) = @_;
5749     my ($var, $value) = ($lang->lder, $lang->ld);
5750     my $libtool_tag = '';
5751     $libtool_tag = '--tag=' . $lang->libtool_tag . ' '
5752       if $lang->libtool_tag && exists $libtool_tags{$lang->libtool_tag};
5753     # CCLD = $(CC).
5754     &define_variable ($lang->lder, $lang->ld, INTERNAL);
5755     # CCLINK = $(CCLD) blah blah...
5756     &define_variable ($lang->linker,
5757                       ((var ('LIBTOOL') ?
5758                         '$(LIBTOOL) --mode=link ' . $libtool_tag  : '')
5759                        . $lang->link),
5760                       INTERNAL);
5763 ################################################################
5765 # &check_trailing_slash ($WHERE, $LINE)
5766 # --------------------------------------
5767 # Return 1 iff $LINE ends with a slash.
5768 # Might modify $LINE.
5769 sub check_trailing_slash ($\$)
5771   my ($where, $line) = @_;
5773   # Ignore `##' lines.
5774   return 0 if $$line =~ /$IGNORE_PATTERN/o;
5776   # Catch and fix a common error.
5777   msg "syntax", $where, "whitespace following trailing backslash"
5778     if $$line =~ s/\\\s+\n$/\\\n/;
5780   return $$line =~ /\\$/;
5784 # &read_am_file ($AMFILE, $WHERE)
5785 # -------------------------------
5786 # Read Makefile.am and set up %contents.  Simultaneously copy lines
5787 # from Makefile.am into $output_trailer, or define variables as
5788 # appropriate.  NOTE we put rules in the trailer section.  We want
5789 # user rules to come after our generated stuff.
5790 sub read_am_file ($$)
5792     my ($amfile, $where) = @_;
5794     my $am_file = new Automake::XFile ("< $amfile");
5795     verb "reading $amfile";
5797     # Keep track of the youngest output dependency.
5798     my $mtime = mtime $amfile;
5799     $output_deps_greatest_timestamp = $mtime
5800       if $mtime > $output_deps_greatest_timestamp;
5802     my $spacing = '';
5803     my $comment = '';
5804     my $blank = 0;
5805     my $saw_bk = 0;
5807     use constant IN_VAR_DEF => 0;
5808     use constant IN_RULE_DEF => 1;
5809     use constant IN_COMMENT => 2;
5810     my $prev_state = IN_RULE_DEF;
5812     while ($_ = $am_file->getline)
5813     {
5814         $where->set ("$amfile:$.");
5815         if (/$IGNORE_PATTERN/o)
5816         {
5817             # Merely delete comments beginning with two hashes.
5818         }
5819         elsif (/$WHITE_PATTERN/o)
5820         {
5821             error $where, "blank line following trailing backslash"
5822               if $saw_bk;
5823             # Stick a single white line before the incoming macro or rule.
5824             $spacing = "\n";
5825             $blank = 1;
5826             # Flush all comments seen so far.
5827             if ($comment ne '')
5828             {
5829                 $output_vars .= $comment;
5830                 $comment = '';
5831             }
5832         }
5833         elsif (/$COMMENT_PATTERN/o)
5834         {
5835             # Stick comments before the incoming macro or rule.  Make
5836             # sure a blank line precedes the first block of comments.
5837             $spacing = "\n" unless $blank;
5838             $blank = 1;
5839             $comment .= $spacing . $_;
5840             $spacing = '';
5841             $prev_state = IN_COMMENT;
5842         }
5843         else
5844         {
5845             last;
5846         }
5847         $saw_bk = check_trailing_slash ($where, $_);
5848     }
5850     # We save the conditional stack on entry, and then check to make
5851     # sure it is the same on exit.  This lets us conditionally include
5852     # other files.
5853     my @saved_cond_stack = @cond_stack;
5854     my $cond = new Automake::Condition (@cond_stack);
5856     my $last_var_name = '';
5857     my $last_var_type = '';
5858     my $last_var_value = '';
5859     my $last_where;
5860     # FIXME: shouldn't use $_ in this loop; it is too big.
5861     while ($_)
5862     {
5863         $where->set ("$amfile:$.");
5865         # Make sure the line is \n-terminated.
5866         chomp;
5867         $_ .= "\n";
5869         # Don't look at MAINTAINER_MODE_TRUE here.  That shouldn't be
5870         # used by users.  @MAINT@ is an anachronism now.
5871         $_ =~ s/\@MAINT\@//g
5872             unless $seen_maint_mode;
5874         my $new_saw_bk = check_trailing_slash ($where, $_);
5876         if (/$IGNORE_PATTERN/o)
5877         {
5878             # Merely delete comments beginning with two hashes.
5879         }
5880         elsif (/$WHITE_PATTERN/o)
5881         {
5882             # Stick a single white line before the incoming macro or rule.
5883             $spacing = "\n";
5884             error $where, "blank line following trailing backslash"
5885               if $saw_bk;
5886         }
5887         elsif (/$COMMENT_PATTERN/o)
5888         {
5889             # Stick comments before the incoming macro or rule.
5890             $comment .= $spacing . $_;
5891             $spacing = '';
5892             error $where, "comment following trailing backslash"
5893               if $saw_bk && $comment eq '';
5894             $prev_state = IN_COMMENT;
5895         }
5896         elsif ($saw_bk)
5897         {
5898             if ($prev_state == IN_RULE_DEF)
5899             {
5900               my $cond = new Automake::Condition @cond_stack;
5901               $output_trailer .= $cond->subst_string;
5902               $output_trailer .= $_;
5903             }
5904             elsif ($prev_state == IN_COMMENT)
5905             {
5906                 # If the line doesn't start with a `#', add it.
5907                 # We do this because a continued comment like
5908                 #   # A = foo \
5909                 #         bar \
5910                 #         baz
5911                 # is not portable.  BSD make doesn't honor
5912                 # escaped newlines in comments.
5913                 s/^#?/#/;
5914                 $comment .= $spacing . $_;
5915             }
5916             else # $prev_state == IN_VAR_DEF
5917             {
5918               $last_var_value .= ' '
5919                 unless $last_var_value =~ /\s$/;
5920               $last_var_value .= $_;
5922               if (!/\\$/)
5923                 {
5924                   Automake::Variable::define ($last_var_name, VAR_MAKEFILE,
5925                                               $last_var_type, $cond,
5926                                               $last_var_value, $comment,
5927                                               $last_where, VAR_ASIS)
5928                     if $cond != FALSE;
5929                   $comment = $spacing = '';
5930                 }
5931             }
5932         }
5934         elsif (/$IF_PATTERN/o)
5935           {
5936             $cond = cond_stack_if ($1, $2, $where);
5937           }
5938         elsif (/$ELSE_PATTERN/o)
5939           {
5940             $cond = cond_stack_else ($1, $2, $where);
5941           }
5942         elsif (/$ENDIF_PATTERN/o)
5943           {
5944             $cond = cond_stack_endif ($1, $2, $where);
5945           }
5947         elsif (/$RULE_PATTERN/o)
5948         {
5949             # Found a rule.
5950             $prev_state = IN_RULE_DEF;
5952             # For now we have to output all definitions of user rules
5953             # and can't diagnose duplicates (see the comment in
5954             # rule_define). So we go on and ignore the return value.
5955             Automake::Rule::define ($1, $amfile, RULE_USER, $cond, $where);
5957             check_variable_expansions ($_, $where);
5959             $output_trailer .= $comment . $spacing;
5960             my $cond = new Automake::Condition @cond_stack;
5961             $output_trailer .= $cond->subst_string;
5962             $output_trailer .= $_;
5963             $comment = $spacing = '';
5964         }
5965         elsif (/$ASSIGNMENT_PATTERN/o)
5966         {
5967             # Found a macro definition.
5968             $prev_state = IN_VAR_DEF;
5969             $last_var_name = $1;
5970             $last_var_type = $2;
5971             $last_var_value = $3;
5972             $last_where = $where->clone;
5973             if ($3 ne '' && substr ($3, -1) eq "\\")
5974             {
5975                 # We preserve the `\' because otherwise the long lines
5976                 # that are generated will be truncated by broken
5977                 # `sed's.
5978                 $last_var_value = $3 . "\n";
5979             }
5981             if (!/\\$/)
5982               {
5983                 Automake::Variable::define ($last_var_name, VAR_MAKEFILE,
5984                                             $last_var_type, $cond,
5985                                             $last_var_value, $comment,
5986                                             $last_where, VAR_ASIS)
5987                   if $cond != FALSE;
5988                 $comment = $spacing = '';
5989               }
5990         }
5991         elsif (/$INCLUDE_PATTERN/o)
5992         {
5993             my $path = $1;
5995             if ($path =~ s/^\$\(top_srcdir\)\///)
5996               {
5997                 push (@include_stack, "\$\(top_srcdir\)/$path");
5998                 # Distribute any included file.
6000                 # Always use the $(top_srcdir) prefix in DIST_COMMON,
6001                 # otherwise OSF make will implicitly copy the included
6002                 # file in the build tree during `make distdir' to satisfy
6003                 # the dependency.
6004                 # (subdircond2.test and subdircond3.test will fail.)
6005                 push_dist_common ("\$\(top_srcdir\)/$path");
6006               }
6007             else
6008               {
6009                 $path =~ s/\$\(srcdir\)\///;
6010                 push (@include_stack, "\$\(srcdir\)/$path");
6011                 # Always use the $(srcdir) prefix in DIST_COMMON,
6012                 # otherwise OSF make will implicitly copy the included
6013                 # file in the build tree during `make distdir' to satisfy
6014                 # the dependency.
6015                 # (subdircond2.test and subdircond3.test will fail.)
6016                 push_dist_common ("\$\(srcdir\)/$path");
6017                 $path = $relative_dir . "/" . $path if $relative_dir ne '.';
6018               }
6019             $where->push_context ("`$path' included from here");
6020             &read_am_file ($path, $where);
6021             $where->pop_context;
6022         }
6023         else
6024         {
6025             # This isn't an error; it is probably a continued rule.
6026             # In fact, this is what we assume.
6027             $prev_state = IN_RULE_DEF;
6028             check_variable_expansions ($_, $where);
6029             $output_trailer .= $comment . $spacing;
6030             my $cond = new Automake::Condition @cond_stack;
6031             $output_trailer .= $cond->subst_string;
6032             $output_trailer .= $_;
6033             $comment = $spacing = '';
6034             error $where, "`#' comment at start of rule is unportable"
6035               if $_ =~ /^\t\s*\#/;
6036         }
6038         $saw_bk = $new_saw_bk;
6039         $_ = $am_file->getline;
6040     }
6042     $output_trailer .= $comment;
6044     error ($where, "trailing backslash on last line")
6045       if $saw_bk;
6047     error ($where, (@cond_stack ? "unterminated conditionals: @cond_stack"
6048                     : "too many conditionals closed in include file"))
6049       if "@saved_cond_stack" ne "@cond_stack";
6053 # define_standard_variables ()
6054 # ----------------------------
6055 # A helper for read_main_am_file which initializes configure variables
6056 # and variables from header-vars.am.
6057 sub define_standard_variables
6059   my $saved_output_vars = $output_vars;
6060   my ($comments, undef, $rules) =
6061     file_contents_internal (1, "$libdir/am/header-vars.am",
6062                             new Automake::Location);
6064   foreach my $var (sort keys %configure_vars)
6065     {
6066       &define_configure_variable ($var);
6067     }
6069   $output_vars .= $comments . $rules;
6072 # Read main am file.
6073 sub read_main_am_file
6075     my ($amfile) = @_;
6077     # This supports the strange variable tricks we are about to play.
6078     prog_error (macros_dump () . "variable defined before read_main_am_file")
6079       if (scalar (variables) > 0);
6081     # Generate copyright header for generated Makefile.in.
6082     # We do discard the output of predefined variables, handled below.
6083     $output_vars = ("# $in_file_name generated by automake "
6084                    . $VERSION . " from $am_file_name.\n");
6085     $output_vars .= '# ' . subst ('configure_input') . "\n";
6086     $output_vars .= $gen_copyright;
6088     # We want to predefine as many variables as possible.  This lets
6089     # the user set them with `+=' in Makefile.am.
6090     &define_standard_variables;
6092     # Read user file, which might override some of our values.
6093     &read_am_file ($amfile, new Automake::Location);
6098 ################################################################
6100 # $FLATTENED
6101 # &flatten ($STRING)
6102 # ------------------
6103 # Flatten the $STRING and return the result.
6104 sub flatten
6106   $_ = shift;
6108   s/\\\n//somg;
6109   s/\s+/ /g;
6110   s/^ //;
6111   s/ $//;
6113   return $_;
6116 # transform($TOKEN, \%PAIRS)
6117 # ==========================
6118 # If ($TOKEN, $VAL) is in %PAIRS:
6119 #   - replaces %$TOKEN% with $VAL,
6120 #   - enables/disables ?$TOKEN? and ?!$TOKEN?,
6121 #   - replaces %?$TOKEN% with TRUE or FALSE.
6122 sub transform($$)
6124   my ($token, $transform) = @_;
6126   if (substr ($token, 0, 1) eq '%')
6127     {
6128       my $cond = (substr ($token, 1, 1) eq '?') ? 1 : 0;
6129       $token = substr ($token, 1 + $cond, -1);
6130       my $val = $transform->{$token};
6131       prog_error "Unknown %token% `$token'" unless defined $val;
6132       if ($cond)
6133         {
6134           return $val ? 'TRUE' : 'FALSE';
6135         }
6136       else
6137         {
6138           return $val;
6139         }
6140     }
6141   # Now $token is '?xxx?' or '?!xxx?'.
6142   my $neg = (substr ($token, 1, 1) eq '!') ? 1 : 0;
6143   $token = substr ($token, 1 + $neg, -1);
6144   my $val = $transform->{$token};
6145   prog_error "Unknown ?token? `$token' (neg = $neg)" unless defined $val;
6146   return (!!$val == $neg) ? '##%' : '';
6149 # @PARAGRAPHS
6150 # &make_paragraphs ($MAKEFILE, [%TRANSFORM])
6151 # ------------------------------------------
6152 # Load a $MAKEFILE, apply the %TRANSFORM, and return it as a list of
6153 # paragraphs.
6154 sub make_paragraphs ($%)
6156   my ($file, %transform) = @_;
6158   # Complete %transform with global options.
6159   # Note that %transform goes last, so it overrides global options.
6160   %transform = ('CYGNUS'      => !! option 'cygnus',
6161                  'MAINTAINER-MODE'
6162                  => $seen_maint_mode ? subst ('MAINTAINER_MODE_TRUE') : '',
6164                  'BZIP2'       => !! option 'dist-bzip2',
6165                  'COMPRESS'    => !! option 'dist-tarZ',
6166                  'GZIP'        =>  ! option 'no-dist-gzip',
6167                  'SHAR'        => !! option 'dist-shar',
6168                  'ZIP'         => !! option 'dist-zip',
6170                  'INSTALL-INFO' =>  ! option 'no-installinfo',
6171                  'INSTALL-MAN'  =>  ! option 'no-installman',
6172                  'CK-NEWS'      => !! option 'check-news',
6174                  'SUBDIRS'      => !! var ('SUBDIRS'),
6175                  'TOPDIR'       => backname ($relative_dir),
6176                  'TOPDIR_P'     => $relative_dir eq '.',
6178                  'BUILD'    => ($seen_canonical >= AC_CANONICAL_BUILD),
6179                  'HOST'     => ($seen_canonical >= AC_CANONICAL_HOST),
6180                  'TARGET'   => ($seen_canonical >= AC_CANONICAL_TARGET),
6182                  'LIBTOOL'      => !! var ('LIBTOOL'),
6183                  'NONLIBTOOL'   => 1,
6184                  'FIRST'        => ! $transformed_files{$file},
6185                 %transform);
6187   $transformed_files{$file} = 1;
6188   $_ = $am_file_cache{$file};
6190   if (! defined $_)
6191     {
6192       verb "reading $file";
6193       # Swallow the whole file.
6194       my $fc_file = new Automake::XFile "< $file";
6195       my $saved_dollar_slash = $/;
6196       undef $/;
6197       $_ = $fc_file->getline;
6198       $/ = $saved_dollar_slash;
6199       $fc_file->close;
6201       # Remove ##-comments.
6202       # Besides we don't need more than two consecutive new-lines.
6203       s/(?:$IGNORE_PATTERN|(?<=\n\n)\n+)//gom;
6205       $am_file_cache{$file} = $_;
6206     }
6208   # Substitute Automake template tokens.
6209   s/(?:%\??[\w\-]+%|\?!?[\w\-]+\?)/transform($&, \%transform)/ge;
6210   # transform() may have added some ##%-comments to strip.
6211   # (we use `##%' instead of `##' so we can distinguish ##%##%##% from
6212   # ####### and do not remove the latter.)
6213   s/^[ \t]*(?:##%)+.*\n//gm;
6215   # Split at unescaped new lines.
6216   my @lines = split (/(?<!\\)\n/, $_);
6217   my @res;
6219   while (defined ($_ = shift @lines))
6220     {
6221       my $paragraph = $_;
6222       # If we are a rule, eat as long as we start with a tab.
6223       if (/$RULE_PATTERN/smo)
6224         {
6225           while (defined ($_ = shift @lines) && $_ =~ /^\t/)
6226             {
6227               $paragraph .= "\n$_";
6228             }
6229           unshift (@lines, $_);
6230         }
6232       # If we are a comments, eat as much comments as you can.
6233       elsif (/$COMMENT_PATTERN/smo)
6234         {
6235           while (defined ($_ = shift @lines)
6236                  && $_ =~ /$COMMENT_PATTERN/smo)
6237             {
6238               $paragraph .= "\n$_";
6239             }
6240           unshift (@lines, $_);
6241         }
6243       push @res, $paragraph;
6244     }
6246   return @res;
6251 # ($COMMENT, $VARIABLES, $RULES)
6252 # &file_contents_internal ($IS_AM, $FILE, $WHERE, [%TRANSFORM])
6253 # -------------------------------------------------------------
6254 # Return contents of a file from $libdir/am, automatically skipping
6255 # macros or rules which are already known. $IS_AM iff the caller is
6256 # reading an Automake file (as opposed to the user's Makefile.am).
6257 sub file_contents_internal ($$$%)
6259     my ($is_am, $file, $where, %transform) = @_;
6261     $where->set ($file);
6263     my $result_vars = '';
6264     my $result_rules = '';
6265     my $comment = '';
6266     my $spacing = '';
6268     # The following flags are used to track rules spanning across
6269     # multiple paragraphs.
6270     my $is_rule = 0;            # 1 if we are processing a rule.
6271     my $discard_rule = 0;       # 1 if the current rule should not be output.
6273     # We save the conditional stack on entry, and then check to make
6274     # sure it is the same on exit.  This lets us conditionally include
6275     # other files.
6276     my @saved_cond_stack = @cond_stack;
6277     my $cond = new Automake::Condition (@cond_stack);
6279     foreach (make_paragraphs ($file, %transform))
6280     {
6281         # FIXME: no line number available.
6282         $where->set ($file);
6284         # Sanity checks.
6285         error $where, "blank line following trailing backslash:\n$_"
6286           if /\\$/;
6287         error $where, "comment following trailing backslash:\n$_"
6288           if /\\#/;
6290         if (/^$/)
6291         {
6292             $is_rule = 0;
6293             # Stick empty line before the incoming macro or rule.
6294             $spacing = "\n";
6295         }
6296         elsif (/$COMMENT_PATTERN/mso)
6297         {
6298             $is_rule = 0;
6299             # Stick comments before the incoming macro or rule.
6300             $comment = "$_\n";
6301         }
6303         # Handle inclusion of other files.
6304         elsif (/$INCLUDE_PATTERN/o)
6305         {
6306             if ($cond != FALSE)
6307               {
6308                 my $file = ($is_am ? "$libdir/am/" : '') . $1;
6309                 $where->push_context ("`$file' included from here");
6310                 # N-ary `.=' fails.
6311                 my ($com, $vars, $rules)
6312                   = file_contents_internal ($is_am, $file, $where, %transform);
6313                 $where->pop_context;
6314                 $comment .= $com;
6315                 $result_vars .= $vars;
6316                 $result_rules .= $rules;
6317               }
6318         }
6320         # Handling the conditionals.
6321         elsif (/$IF_PATTERN/o)
6322           {
6323             $cond = cond_stack_if ($1, $2, $file);
6324           }
6325         elsif (/$ELSE_PATTERN/o)
6326           {
6327             $cond = cond_stack_else ($1, $2, $file);
6328           }
6329         elsif (/$ENDIF_PATTERN/o)
6330           {
6331             $cond = cond_stack_endif ($1, $2, $file);
6332           }
6334         # Handling rules.
6335         elsif (/$RULE_PATTERN/mso)
6336         {
6337           $is_rule = 1;
6338           $discard_rule = 0;
6339           # Separate relationship from optional actions: the first
6340           # `new-line tab" not preceded by backslash (continuation
6341           # line).
6342           my $paragraph = $_;
6343           /^(.*?)(?:(?<!\\)\n(\t.*))?$/s;
6344           my ($relationship, $actions) = ($1, $2 || '');
6346           # Separate targets from dependencies: the first colon.
6347           $relationship =~ /^([^:]+\S+) *: *(.*)$/som;
6348           my ($targets, $dependencies) = ($1, $2);
6349           # Remove the escaped new lines.
6350           # I don't know why, but I have to use a tmp $flat_deps.
6351           my $flat_deps = &flatten ($dependencies);
6352           my @deps = split (' ', $flat_deps);
6354           foreach (split (' ' , $targets))
6355             {
6356               # FIXME: 1. We are not robust to people defining several targets
6357               # at once, only some of them being in %dependencies.  The
6358               # actions from the targets in %dependencies are usually generated
6359               # from the content of %actions, but if some targets in $targets
6360               # are not in %dependencies the ELSE branch will output
6361               # a rule for all $targets (i.e. the targets which are both
6362               # in %dependencies and $targets will have two rules).
6364               # FIXME: 2. The logic here is not able to output a
6365               # multi-paragraph rule several time (e.g. for each condition
6366               # it is defined for) because it only knows the first paragraph.
6368               # FIXME: 3. We are not robust to people defining a subset
6369               # of a previously defined "multiple-target" rule.  E.g.
6370               # `foo:' after `foo bar:'.
6372               # Output only if not in FALSE.
6373               if (defined $dependencies{$_} && $cond != FALSE)
6374                 {
6375                   &depend ($_, @deps);
6376                   if ($actions{$_})
6377                     {
6378                       $actions{$_} .= "\n$actions" if $actions;
6379                     }
6380                   else
6381                     {
6382                       $actions{$_} = $actions;
6383                     }
6384                 }
6385               else
6386                 {
6387                   # Free-lance dependency.  Output the rule for all the
6388                   # targets instead of one by one.
6389                   my @undefined_conds =
6390                     Automake::Rule::define ($targets, $file,
6391                                             $is_am ? RULE_AUTOMAKE : RULE_USER,
6392                                             $cond, $where);
6393                   for my $undefined_cond (@undefined_conds)
6394                     {
6395                       my $condparagraph = $paragraph;
6396                       $condparagraph =~ s/^/$undefined_cond->subst_string/gme;
6397                       $result_rules .= "$spacing$comment$condparagraph\n";
6398                     }
6399                   if (scalar @undefined_conds == 0)
6400                     {
6401                       # Remember to discard next paragraphs
6402                       # if they belong to this rule.
6403                       # (but see also FIXME: #2 above.)
6404                       $discard_rule = 1;
6405                     }
6406                   $comment = $spacing = '';
6407                   last;
6408                 }
6409             }
6410         }
6412         elsif (/$ASSIGNMENT_PATTERN/mso)
6413         {
6414             my ($var, $type, $val) = ($1, $2, $3);
6415             error $where, "variable `$var' with trailing backslash"
6416               if /\\$/;
6418             $is_rule = 0;
6420             Automake::Variable::define ($var,
6421                                         $is_am ? VAR_AUTOMAKE : VAR_MAKEFILE,
6422                                         $type, $cond, $val, $comment, $where,
6423                                         VAR_ASIS)
6424               if $cond != FALSE;
6426             $comment = $spacing = '';
6427         }
6428         else
6429         {
6430             # This isn't an error; it is probably some tokens which
6431             # configure is supposed to replace, such as `@SET-MAKE@',
6432             # or some part of a rule cut by an if/endif.
6433             if (! $cond->false && ! ($is_rule && $discard_rule))
6434               {
6435                 s/^/$cond->subst_string/gme;
6436                 $result_rules .= "$spacing$comment$_\n";
6437               }
6438             $comment = $spacing = '';
6439         }
6440     }
6442     error ($where, @cond_stack ?
6443            "unterminated conditionals: @cond_stack" :
6444            "too many conditionals closed in include file")
6445       if "@saved_cond_stack" ne "@cond_stack";
6447     return ($comment, $result_vars, $result_rules);
6451 # $CONTENTS
6452 # &file_contents ($BASENAME, $WHERE, [%TRANSFORM])
6453 # ------------------------------------------------
6454 # Return contents of a file from $libdir/am, automatically skipping
6455 # macros or rules which are already known.
6456 sub file_contents ($$%)
6458     my ($basename, $where, %transform) = @_;
6459     my ($comments, $variables, $rules) =
6460       file_contents_internal (1, "$libdir/am/$basename.am", $where,
6461                               %transform);
6462     return "$comments$variables$rules";
6466 # &append_exeext ($MACRO)
6467 # -----------------------
6468 # Macro is an Automake magic macro which primary is PROGRAMS, e.g.
6469 # bin_PROGRAMS.  Make sure these programs have $(EXEEXT) appended.
6470 sub append_exeext ($)
6472   my ($macro) = @_;
6474   prog_error "append_exeext ($macro)"
6475     unless $macro =~ /_PROGRAMS$/;
6477   transform_variable_recursively
6478     ($macro, $macro, 'am__EXEEXT', 0, INTERNAL,
6479      sub {
6480        my ($subvar, $val, $cond, $full_cond) = @_;
6481        # Append $(EXEEXT) unless the user did it already, or it's a
6482        # @substitution@.
6483        $val .= '$(EXEEXT)' unless $val =~ /(?:\$\(EXEEXT\)$|^[@]\w+[@]$)/;
6484        return $val;
6485      });
6489 # @PREFIX
6490 # &am_primary_prefixes ($PRIMARY, $CAN_DIST, @PREFIXES)
6491 # -----------------------------------------------------
6492 # Find all variable prefixes that are used for install directories.  A
6493 # prefix `zar' qualifies iff:
6495 # * `zardir' is a variable.
6496 # * `zar_PRIMARY' is a variable.
6498 # As a side effect, it looks for misspellings.  It is an error to have
6499 # a variable ending in a "reserved" suffix whose prefix is unknown, e.g.
6500 # "bin_PROGRAMS".  However, unusual prefixes are allowed if a variable
6501 # of the same name (with "dir" appended) exists.  For instance, if the
6502 # variable "zardir" is defined, then "zar_PROGRAMS" becomes valid.
6503 # This is to provide a little extra flexibility in those cases which
6504 # need it.
6505 sub am_primary_prefixes ($$@)
6507   my ($primary, $can_dist, @prefixes) = @_;
6509   local $_;
6510   my %valid = map { $_ => 0 } @prefixes;
6511   $valid{'EXTRA'} = 0;
6512   foreach my $var (variables $primary)
6513     {
6514       # Automake is allowed to define variables that look like primaries
6515       # but which aren't.  E.g. INSTALL_sh_DATA.
6516       # Autoconf can also define variables like INSTALL_DATA, so
6517       # ignore all configure variables (at least those which are not
6518       # redefined in Makefile.am).
6519       # FIXME: We should make sure that these variables are not
6520       # conditionally defined (or else adjust the condition below).
6521       my $def = $var->def (TRUE);
6522       next if $def && $def->owner != VAR_MAKEFILE;
6524       my $varname = $var->name;
6526       if ($varname =~ /^(nobase_)?(dist_|nodist_)?(.*)_[[:alnum:]]+$/)
6527         {
6528           my ($base, $dist, $X) = ($1 || '', $2 || '', $3 || '');
6529           if ($dist ne '' && ! $can_dist)
6530             {
6531               err_var ($var,
6532                        "invalid variable `$varname': `dist' is forbidden");
6533             }
6534           # Standard directories must be explicitly allowed.
6535           elsif (! defined $valid{$X} && exists $standard_prefix{$X})
6536             {
6537               err_var ($var,
6538                        "`${X}dir' is not a legitimate directory " .
6539                        "for `$primary'");
6540             }
6541           # A not explicitly valid directory is allowed if Xdir is defined.
6542           elsif (! defined $valid{$X} &&
6543                  $var->requires_variables ("`$varname' is used", "${X}dir"))
6544             {
6545               # Nothing to do.  Any error message has been output
6546               # by $var->requires_variables.
6547             }
6548           else
6549             {
6550               # Ensure all extended prefixes are actually used.
6551               $valid{"$base$dist$X"} = 1;
6552             }
6553         }
6554       else
6555         {
6556           prog_error "unexpected variable name: $varname";
6557         }
6558     }
6560   # Return only those which are actually defined.
6561   return sort grep { var ($_ . '_' . $primary) } keys %valid;
6565 # Handle `where_HOW' variable magic.  Does all lookups, generates
6566 # install code, and possibly generates code to define the primary
6567 # variable.  The first argument is the name of the .am file to munge,
6568 # the second argument is the primary variable (e.g. HEADERS), and all
6569 # subsequent arguments are possible installation locations.
6571 # Returns list of [$location, $value] pairs, where
6572 # $value's are the values in all where_HOW variable, and $location
6573 # there associated location (the place here their parent variables were
6574 # defined).
6576 # FIXME: this should be rewritten to be cleaner.  It should be broken
6577 # up into multiple functions.
6579 # Usage is: am_install_var (OPTION..., file, HOW, where...)
6580 sub am_install_var
6582   my (@args) = @_;
6584   my $do_require = 1;
6585   my $can_dist = 0;
6586   my $default_dist = 0;
6587   while (@args)
6588     {
6589       if ($args[0] eq '-noextra')
6590         {
6591           $do_require = 0;
6592         }
6593       elsif ($args[0] eq '-candist')
6594         {
6595           $can_dist = 1;
6596         }
6597       elsif ($args[0] eq '-defaultdist')
6598         {
6599           $default_dist = 1;
6600           $can_dist = 1;
6601         }
6602       elsif ($args[0] !~ /^-/)
6603         {
6604           last;
6605         }
6606       shift (@args);
6607     }
6609   my ($file, $primary, @prefix) = @args;
6611   # Now that configure substitutions are allowed in where_HOW
6612   # variables, it is an error to actually define the primary.  We
6613   # allow `JAVA', as it is customarily used to mean the Java
6614   # interpreter.  This is but one of several Java hacks.  Similarly,
6615   # `PYTHON' is customarily used to mean the Python interpreter.
6616   reject_var $primary, "`$primary' is an anachronism"
6617     unless $primary eq 'JAVA' || $primary eq 'PYTHON';
6619   # Get the prefixes which are valid and actually used.
6620   @prefix = am_primary_prefixes ($primary, $can_dist, @prefix);
6622   # If a primary includes a configure substitution, then the EXTRA_
6623   # form is required.  Otherwise we can't properly do our job.
6624   my $require_extra;
6626   my @used = ();
6627   my @result = ();
6629   foreach my $X (@prefix)
6630     {
6631       my $nodir_name = $X;
6632       my $one_name = $X . '_' . $primary;
6633       my $one_var = var $one_name;
6635       my $strip_subdir = 1;
6636       # If subdir prefix should be preserved, do so.
6637       if ($nodir_name =~ /^nobase_/)
6638         {
6639           $strip_subdir = 0;
6640           $nodir_name =~ s/^nobase_//;
6641         }
6643       # If files should be distributed, do so.
6644       my $dist_p = 0;
6645       if ($can_dist)
6646         {
6647           $dist_p = (($default_dist && $nodir_name !~ /^nodist_/)
6648                      || (! $default_dist && $nodir_name =~ /^dist_/));
6649           $nodir_name =~ s/^(dist|nodist)_//;
6650         }
6653       # Use the location of the currently processed variable.
6654       # We are not processing a particular condition, so pick the first
6655       # available.
6656       my $tmpcond = $one_var->conditions->one_cond;
6657       my $where = $one_var->rdef ($tmpcond)->location->clone;
6659       # Append actual contents of where_PRIMARY variable to
6660       # @result, skipping @substitutions@.
6661       foreach my $locvals ($one_var->value_as_list_recursive (location => 1))
6662         {
6663           my ($loc, $value) = @$locvals;
6664           # Skip configure substitutions.
6665           if ($value =~ /^\@.*\@$/)
6666             {
6667               if ($nodir_name eq 'EXTRA')
6668                 {
6669                   error ($where,
6670                          "`$one_name' contains configure substitution, "
6671                          . "but shouldn't");
6672                 }
6673               # Check here to make sure variables defined in
6674               # configure.ac do not imply that EXTRA_PRIMARY
6675               # must be defined.
6676               elsif (! defined $configure_vars{$one_name})
6677                 {
6678                   $require_extra = $one_name
6679                     if $do_require;
6680                 }
6681             }
6682           else
6683             {
6684               push (@result, $locvals);
6685             }
6686         }
6687       # A blatant hack: we rewrite each _PROGRAMS primary to include
6688       # EXEEXT.
6689       append_exeext ($one_name)
6690         if $primary eq 'PROGRAMS';
6691       # "EXTRA" shouldn't be used when generating clean targets,
6692       # all, or install targets.  We used to warn if EXTRA_FOO was
6693       # defined uselessly, but this was annoying.
6694       next
6695         if $nodir_name eq 'EXTRA';
6697       if ($nodir_name eq 'check')
6698         {
6699           push (@check, '$(' . $one_name . ')');
6700         }
6701       else
6702         {
6703           push (@used, '$(' . $one_name . ')');
6704         }
6706       # Is this to be installed?
6707       my $install_p = $nodir_name ne 'noinst' && $nodir_name ne 'check';
6709       # If so, with install-exec? (or install-data?).
6710       my $exec_p = ($nodir_name =~ /$EXEC_DIR_PATTERN/o);
6712       my $check_options_p = $install_p && !! option 'std-options';
6714       # Use the location of the currently processed variable as context.
6715       $where->push_context ("while processing `$one_name'");
6717       # The variable containing all file to distribute.
6718       my $distvar = "\$($one_name)";
6719       $distvar = shadow_unconditionally ($one_name, $where)
6720         if ($dist_p && $one_var->has_conditional_contents);
6722       # Singular form of $PRIMARY.
6723       (my $one_primary = $primary) =~ s/S$//;
6724       $output_rules .= &file_contents ($file, $where,
6725                                        PRIMARY     => $primary,
6726                                        ONE_PRIMARY => $one_primary,
6727                                        DIR         => $X,
6728                                        NDIR        => $nodir_name,
6729                                        BASE        => $strip_subdir,
6731                                        EXEC      => $exec_p,
6732                                        INSTALL   => $install_p,
6733                                        DIST      => $dist_p,
6734                                        DISTVAR   => $distvar,
6735                                        'CK-OPTS' => $check_options_p);
6736     }
6738   # The JAVA variable is used as the name of the Java interpreter.
6739   # The PYTHON variable is used as the name of the Python interpreter.
6740   if (@used && $primary ne 'JAVA' && $primary ne 'PYTHON')
6741     {
6742       # Define it.
6743       define_pretty_variable ($primary, TRUE, INTERNAL, @used);
6744       $output_vars .= "\n";
6745     }
6747   err_var ($require_extra,
6748            "`$require_extra' contains configure substitution,\n"
6749            . "but `EXTRA_$primary' not defined")
6750     if ($require_extra && ! var ('EXTRA_' . $primary));
6752   # Push here because PRIMARY might be configure time determined.
6753   push (@all, '$(' . $primary . ')')
6754     if @used && $primary ne 'JAVA' && $primary ne 'PYTHON';
6756   # Make the result unique.  This lets the user use conditionals in
6757   # a natural way, but still lets us program lazily -- we don't have
6758   # to worry about handling a particular object more than once.
6759   # We will keep only one location per object.
6760   my %result = ();
6761   for my $pair (@result)
6762     {
6763       my ($loc, $val) = @$pair;
6764       $result{$val} = $loc;
6765     }
6766   my @l = sort keys %result;
6767   return map { [$result{$_}->clone, $_] } @l;
6771 ################################################################
6773 # Each key in this hash is the name of a directory holding a
6774 # Makefile.in.  These variables are local to `is_make_dir'.
6775 my %make_dirs = ();
6776 my $make_dirs_set = 0;
6778 sub is_make_dir
6780     my ($dir) = @_;
6781     if (! $make_dirs_set)
6782     {
6783         foreach my $iter (@configure_input_files)
6784         {
6785             $make_dirs{dirname ($iter)} = 1;
6786         }
6787         # We also want to notice Makefile.in's.
6788         foreach my $iter (@other_input_files)
6789         {
6790             if ($iter =~ /Makefile\.in$/)
6791             {
6792                 $make_dirs{dirname ($iter)} = 1;
6793             }
6794         }
6795         $make_dirs_set = 1;
6796     }
6797     return defined $make_dirs{$dir};
6800 ################################################################
6802 # Find the aux dir.  This should match the algorithm used by
6803 # ./configure. (See the Autoconf documentation for for
6804 # AC_CONFIG_AUX_DIR.)
6805 sub locate_aux_dir ()
6807   if (! $config_aux_dir_set_in_configure_ac)
6808     {
6809       # The default auxiliary directory is the first
6810       # of ., .., or ../.. that contains install-sh.
6811       # Assume . if install-sh doesn't exist yet.
6812       for my $dir (qw (. .. ../..))
6813         {
6814           if (-f "$dir/install-sh")
6815             {
6816               $config_aux_dir = $dir;
6817               last;
6818             }
6819         }
6820       $config_aux_dir = '.' unless $config_aux_dir;
6821     }
6822   # Avoid unsightly '/.'s.
6823   $am_config_aux_dir =
6824     '$(top_srcdir)' . ($config_aux_dir eq '.' ? "" : "/$config_aux_dir");
6825   $am_config_aux_dir =~ s,/*$,,;
6829 # &maybe_push_required_file ($DIR, $FILE, $FULLFILE)
6830 # --------------------------------------------------
6831 # See if we want to push this file onto dist_common.  This function
6832 # encodes the rules for deciding when to do so.
6833 sub maybe_push_required_file
6835   my ($dir, $file, $fullfile) = @_;
6837   if ($dir eq $relative_dir)
6838     {
6839       push_dist_common ($file);
6840       return 1;
6841     }
6842   elsif ($relative_dir eq '.' && ! &is_make_dir ($dir))
6843     {
6844       # If we are doing the topmost directory, and the file is in a
6845       # subdir which does not have a Makefile, then we distribute it
6846       # here.
6848       # If a required file is above the source tree, it is important
6849       # to prefix it with `$(srcdir)' so that no VPATH search is
6850       # performed.  Otherwise problems occur with Make implementations
6851       # that rewrite and simplify rules whose dependencies are found in a
6852       # VPATH location.  Here is an example with OSF1/Tru64 Make.
6853       #
6854       #   % cat Makefile
6855       #   VPATH = sub
6856       #   distdir: ../a
6857       #           echo ../a
6858       #   % ls
6859       #   Makefile a
6860       #   % make
6861       #   echo a
6862       #   a
6863       #
6864       # Dependency `../a' was found in `sub/../a', but this make
6865       # implementation simplified it as `a'.  (Note that the sub/
6866       # directory does not even exist.)
6867       #
6868       # This kind of VPATH rewriting seems hard to cancel.  The
6869       # distdir.am hack against VPATH rewriting works only when no
6870       # simplification is done, i.e., for dependencies which are in
6871       # subdirectories, not in enclosing directories.  Hence, in
6872       # the latter case we use a full path to make sure no VPATH
6873       # search occurs.
6874       $fullfile = '$(srcdir)/' . $fullfile
6875         if $dir =~ m,^\.\.(?:$|/),;
6877       push_dist_common ($fullfile);
6878       return 1;
6879     }
6880   return 0;
6884 # If a file name appears as a key in this hash, then it has already
6885 # been checked for.  This allows us not to report the same error more
6886 # than once.
6887 my %required_file_not_found = ();
6889 # &require_file_internal ($WHERE, $MYSTRICT, $DIRECTORY, @FILES)
6890 # --------------------------------------------------------------
6891 # Verify that the file must exist in $DIRECTORY, or install it.
6892 # $MYSTRICT is the strictness level at which this file becomes required.
6893 sub require_file_internal ($$$@)
6895   my ($where, $mystrict, $dir, @files) = @_;
6897   foreach my $file (@files)
6898     {
6899       my $fullfile = "$dir/$file";
6900       my $found_it = 0;
6901       my $dangling_sym = 0;
6903       if (-l $fullfile && ! -f $fullfile)
6904         {
6905           $dangling_sym = 1;
6906         }
6907       elsif (-f $fullfile)
6908         {
6909           $found_it = 1;
6910           maybe_push_required_file ($dir, $file, $fullfile);
6911         }
6913       # `--force-missing' only has an effect if `--add-missing' is
6914       # specified.
6915       if ($found_it && (! $add_missing || ! $force_missing))
6916         {
6917           next;
6918         }
6919       else
6920         {
6921           # If we've already looked for it, we're done.  You might
6922           # wonder why we don't do this before searching for the
6923           # file.  If we do that, then something like
6924           # AC_OUTPUT(subdir/foo foo) will fail to put foo.in into
6925           # DIST_COMMON.
6926           if (! $found_it)
6927             {
6928               next if defined $required_file_not_found{$fullfile};
6929               $required_file_not_found{$fullfile} = 1;
6930             }
6932           if ($strictness >= $mystrict)
6933             {
6934               if ($dangling_sym && $add_missing)
6935                 {
6936                   unlink ($fullfile);
6937                 }
6939               my $trailer = '';
6940               my $suppress = 0;
6942               # Only install missing files according to our desired
6943               # strictness level.
6944               my $message = "required file `$fullfile' not found";
6945               if ($add_missing)
6946                 {
6947                   if (-f ("$libdir/$file"))
6948                     {
6949                       $suppress = 1;
6951                       # Install the missing file.  Symlink if we
6952                       # can, copy if we must.  Note: delete the file
6953                       # first, in case it is a dangling symlink.
6954                       $message = "installing `$fullfile'";
6955                       # Windows Perl will hang if we try to delete a
6956                       # file that doesn't exist.
6957                       unlink ($fullfile) if -f $fullfile;
6958                       if ($symlink_exists && ! $copy_missing)
6959                         {
6960                           if (! symlink ("$libdir/$file", $fullfile))
6961                             {
6962                               $suppress = 0;
6963                               $trailer = "; error while making link: $!";
6964                             }
6965                         }
6966                       elsif (system ('cp', "$libdir/$file", $fullfile))
6967                         {
6968                           $suppress = 0;
6969                           $trailer = "\n    error while copying";
6970                         }
6971                     }
6973                   if (! maybe_push_required_file (dirname ($fullfile),
6974                                                   $file, $fullfile))
6975                     {
6976                       if (! $found_it && ! $automake_will_process_aux_dir)
6977                         {
6978                           # We have added the file but could not push it
6979                           # into DIST_COMMON, probably because this is
6980                           # an auxiliary file and we are not processing
6981                           # the top level Makefile.  Furthermore Automake
6982                           # hasn't been asked to create the Makefile.in
6983                           # that distribute the aux dir files.
6984                           error ($where, 'Please make a full run of automake'
6985                                  . " so $fullfile gets distributed.");
6986                         }
6987                     }
6988                 }
6990               # If --force-missing was specified, and we have
6991               # actually found the file, then do nothing.
6992               next
6993                 if $found_it && $force_missing;
6995               # If we couldn' install the file, but it is a target in
6996               # the Makefile, don't print anything.  This allows files
6997               # like README, AUTHORS, or THANKS to be generated.
6998               next
6999                 if !$suppress && rule $file;
7001               msg ($suppress ? 'note' : 'error', $where, "$message$trailer");
7002             }
7003         }
7004     }
7007 # &require_file ($WHERE, $MYSTRICT, @FILES)
7008 # -----------------------------------------
7009 sub require_file ($$@)
7011     my ($where, $mystrict, @files) = @_;
7012     require_file_internal ($where, $mystrict, $relative_dir, @files);
7015 # &require_file_with_macro ($COND, $MACRO, $MYSTRICT, @FILES)
7016 # -----------------------------------------------------------
7017 sub require_file_with_macro ($$$@)
7019     my ($cond, $macro, $mystrict, @files) = @_;
7020     $macro = rvar ($macro) unless ref $macro;
7021     require_file ($macro->rdef ($cond)->location, $mystrict, @files);
7025 # &require_conf_file ($WHERE, $MYSTRICT, @FILES)
7026 # ----------------------------------------------
7027 # Looks in configuration path, as specified by AC_CONFIG_AUX_DIR.
7028 sub require_conf_file ($$@)
7030     my ($where, $mystrict, @files) = @_;
7031     require_file_internal ($where, $mystrict, $config_aux_dir, @files);
7035 # &require_conf_file_with_macro ($COND, $MACRO, $MYSTRICT, @FILES)
7036 # ----------------------------------------------------------------
7037 sub require_conf_file_with_macro ($$$@)
7039     my ($cond, $macro, $mystrict, @files) = @_;
7040     require_conf_file (rvar ($macro)->rdef ($cond)->location,
7041                        $mystrict, @files);
7044 ################################################################
7046 # &require_build_directory ($DIRECTORY)
7047 # ------------------------------------
7048 # Emit rules to create $DIRECTORY if needed, and return
7049 # the file that any target requiring this directory should be made
7050 # dependent upon.
7051 sub require_build_directory ($)
7053   my $directory = shift;
7054   my $dirstamp = "$directory/\$(am__dirstamp)";
7056   # Don't emit the rule twice.
7057   if (! defined $directory_map{$directory})
7058     {
7059       $directory_map{$directory} = 1;
7061       # Set a variable for the dirstamp basename.
7062       define_pretty_variable ('am__dirstamp', TRUE, INTERNAL,
7063                               '$(am__leading_dot)dirstamp');
7065       # Directory must be removed by `make distclean'.
7066       $clean_files{$dirstamp} = DIST_CLEAN;
7068       $output_rules .= ("$dirstamp:\n"
7069                         . "\t\@\$(mkdir_p) $directory\n"
7070                         . "\t\@: > $dirstamp\n");
7071     }
7073   return $dirstamp;
7076 # &require_build_directory_maybe ($FILE)
7077 # --------------------------------------
7078 # If $FILE lies in a subdirectory, emit a rule to create this
7079 # directory and return the file that $FILE should be made
7080 # dependent upon.  Otherwise, just return the empty string.
7081 sub require_build_directory_maybe ($)
7083     my $file = shift;
7084     my $directory = dirname ($file);
7086     if ($directory ne '.')
7087     {
7088         return require_build_directory ($directory);
7089     }
7090     else
7091     {
7092         return '';
7093     }
7096 ################################################################
7098 # Push a list of files onto dist_common.
7099 sub push_dist_common
7101   prog_error "push_dist_common run after handle_dist"
7102     if $handle_dist_run;
7103   Automake::Variable::define ('DIST_COMMON', VAR_AUTOMAKE, '+', TRUE, "@_",
7104                               '', INTERNAL, VAR_PRETTY);
7108 ################################################################
7110 # generate_makefile ($MAKEFILE_AM, $MAKEFILE_IN)
7111 # ----------------------------------------------
7112 # Generate a Makefile.in given the name of the corresponding Makefile and
7113 # the name of the file output by config.status.
7114 sub generate_makefile ($$)
7116   my ($makefile_am, $makefile_in) = @_;
7118   # Reset all the Makefile.am related variables.
7119   initialize_per_input;
7121   # AUTOMAKE_OPTIONS can contains -W flags to disable or enable
7122   # warnings for this file.  So hold any warning issued before
7123   # we have processed AUTOMAKE_OPTIONS.
7124   buffer_messages ('warning');
7126   # Name of input file ("Makefile.am") and output file
7127   # ("Makefile.in").  These have no directory components.
7128   $am_file_name = basename ($makefile_am);
7129   $in_file_name = basename ($makefile_in);
7131   # $OUTPUT is encoded.  If it contains a ":" then the first element
7132   # is the real output file, and all remaining elements are input
7133   # files.  We don't scan or otherwise deal with these input files,
7134   # other than to mark them as dependencies.  See
7135   # &scan_autoconf_files for details.
7136   my ($makefile, @inputs) = split (/:/, $output_files{$makefile_in});
7138   $relative_dir = dirname ($makefile);
7139   $am_relative_dir = dirname ($makefile_am);
7141   read_main_am_file ($makefile_am);
7142   if (handle_options)
7143     {
7144       # Process buffered warnings.
7145       flush_messages;
7146       # Fatal error.  Just return, so we can continue with next file.
7147       return;
7148     }
7149   # Process buffered warnings.
7150   flush_messages;
7152   # There are a few install-related variables that you should not define.
7153   foreach my $var ('PRE_INSTALL', 'POST_INSTALL', 'NORMAL_INSTALL')
7154     {
7155       my $v = var $var;
7156       if ($v)
7157         {
7158           my $def = $v->def (TRUE);
7159           prog_error "$var not defined in condition TRUE"
7160             unless $def;
7161           reject_var $var, "`$var' should not be defined"
7162             if $def->owner != VAR_AUTOMAKE;
7163         }
7164     }
7166   # Catch some obsolete variables.
7167   msg_var ('obsolete', 'INCLUDES',
7168            "`INCLUDES' is the old name for `AM_CPPFLAGS' (or `*_CPPFLAGS')")
7169     if var ('INCLUDES');
7171   # Must do this after reading .am file.
7172   define_variable ('subdir', $relative_dir, INTERNAL);
7174   # If DIST_SUBDIRS is defined, make sure SUBDIRS is, so that
7175   # recursive rules are enabled.
7176   define_pretty_variable ('SUBDIRS', TRUE, INTERNAL, '')
7177     if var 'DIST_SUBDIRS' && ! var 'SUBDIRS';
7179   # Check first, because we might modify some state.
7180   check_cygnus;
7181   check_gnu_standards;
7182   check_gnits_standards;
7184   handle_configure ($makefile_am, $makefile_in, $makefile, @inputs);
7185   handle_gettext;
7186   handle_libraries;
7187   handle_ltlibraries;
7188   handle_programs;
7189   handle_scripts;
7191   # These must be run after all the sources are scanned.  They
7192   # use variables defined by &handle_libraries, &handle_ltlibraries,
7193   # or &handle_programs.
7194   handle_compile;
7195   handle_languages;
7196   handle_libtool;
7198   # Variables used by distdir.am and tags.am.
7199   define_pretty_variable ('SOURCES', TRUE, INTERNAL, @sources);
7200   if (! option 'no-dist')
7201     {
7202       define_pretty_variable ('DIST_SOURCES', TRUE, INTERNAL, @dist_sources);
7203     }
7205   handle_multilib;
7206   handle_texinfo;
7207   handle_emacs_lisp;
7208   handle_python;
7209   handle_java;
7210   handle_man_pages;
7211   handle_data;
7212   handle_headers;
7213   handle_subdirs;
7214   handle_tags;
7215   handle_minor_options;
7216   handle_tests;
7218   # This must come after most other rules.
7219   handle_dist;
7221   handle_footer;
7222   do_check_merge_target;
7223   handle_all ($makefile);
7225   # FIXME: Gross!
7226   if (var ('lib_LTLIBRARIES') && var ('bin_PROGRAMS'))
7227     {
7228       $output_rules .= "install-binPROGRAMS: install-libLTLIBRARIES\n\n";
7229     }
7231   handle_install;
7232   handle_clean ($makefile);
7233   handle_factored_dependencies;
7235   # Comes last, because all the above procedures may have
7236   # defined or overridden variables.
7237   $output_vars .= output_variables;
7239   check_typos;
7241   my ($out_file) = $output_directory . '/' . $makefile_in;
7243   if ($exit_code != 0)
7244     {
7245       verb "not writing $out_file because of earlier errors";
7246       return;
7247     }
7249   if (! -d ($output_directory . '/' . $am_relative_dir))
7250     {
7251       mkdir ($output_directory . '/' . $am_relative_dir, 0755);
7252     }
7254   # We make sure that `all:' is the first target.
7255   my $output =
7256     "$output_vars$output_all$output_header$output_rules$output_trailer";
7258   # Decide whether we must update the output file or not.
7259   # We have to update in the following situations.
7260   #  * $force_generation is set.
7261   #  * any of the output dependencies is younger than the output
7262   #  * the contents of the output is different (this can happen
7263   #    if the project has been populated with a file listed in
7264   #    @common_files since the last run).
7265   # Output's dependencies are split in two sets:
7266   #  * dependencies which are also configure dependencies
7267   #    These do not change between each Makefile.am
7268   #  * other dependencies, specific to the Makefile.am being processed
7269   #    (such as the Makefile.am itself, or any Makefile fragment
7270   #    it includes).
7271   my $timestamp = mtime $out_file;
7272   if (! $force_generation
7273       && $configure_deps_greatest_timestamp < $timestamp
7274       && $output_deps_greatest_timestamp < $timestamp
7275       && $output eq contents ($out_file))
7276     {
7277       verb "$out_file unchanged";
7278       # No need to update.
7279       return;
7280     }
7282   if (-e $out_file)
7283     {
7284       unlink ($out_file)
7285         or fatal "cannot remove $out_file: $!\n";
7286     }
7288   my $gm_file = new Automake::XFile "> $out_file";
7289   verb "creating $out_file";
7290   print $gm_file $output;
7293 ################################################################
7298 ################################################################
7300 # Print usage information.
7301 sub usage ()
7303     print "Usage: $0 [OPTION] ... [Makefile]...
7305 Generate Makefile.in for configure from Makefile.am.
7307 Operation modes:
7308       --help               print this help, then exit
7309       --version            print version number, then exit
7310   -v, --verbose            verbosely list files processed
7311       --no-force           only update Makefile.in's that are out of date
7312   -W, --warnings=CATEGORY  report the warnings falling in CATEGORY
7314 Dependency tracking:
7315   -i, --ignore-deps      disable dependency tracking code
7316       --include-deps     enable dependency tracking code
7318 Flavors:
7319       --cygnus           assume program is part of Cygnus-style tree
7320       --foreign          set strictness to foreign
7321       --gnits            set strictness to gnits
7322       --gnu              set strictness to gnu
7324 Library files:
7325   -a, --add-missing      add missing standard files to package
7326       --libdir=DIR       directory storing library files
7327   -c, --copy             with -a, copy missing files (default is symlink)
7328   -f, --force-missing    force update of standard files
7331     Automake::ChannelDefs::usage;
7333     my ($last, @lcomm);
7334     $last = '';
7335     foreach my $iter (sort ((@common_files, @common_sometimes)))
7336     {
7337         push (@lcomm, $iter) unless $iter eq $last;
7338         $last = $iter;
7339     }
7341     my @four;
7342     print "\nFiles which are automatically distributed, if found:\n";
7343     format USAGE_FORMAT =
7344   @<<<<<<<<<<<<<<<<   @<<<<<<<<<<<<<<<<   @<<<<<<<<<<<<<<<<   @<<<<<<<<<<<<<<<<
7345   $four[0],           $four[1],           $four[2],           $four[3]
7347     $~ = "USAGE_FORMAT";
7349     my $cols = 4;
7350     my $rows = int(@lcomm / $cols);
7351     my $rest = @lcomm % $cols;
7353     if ($rest)
7354     {
7355         $rows++;
7356     }
7357     else
7358     {
7359         $rest = $cols;
7360     }
7362     for (my $y = 0; $y < $rows; $y++)
7363     {
7364         @four = ("", "", "", "");
7365         for (my $x = 0; $x < $cols; $x++)
7366         {
7367             last if $y + 1 == $rows && $x == $rest;
7369             my $idx = (($x > $rest)
7370                        ?  ($rows * $rest + ($rows - 1) * ($x - $rest))
7371                        : ($rows * $x));
7373             $idx += $y;
7374             $four[$x] = $lcomm[$idx];
7375         }
7376         write;
7377     }
7379     print "\nReport bugs to <bug-automake\@gnu.org>.\n";
7381     # --help always returns 0 per GNU standards.
7382     exit 0;
7386 # &version ()
7387 # -----------
7388 # Print version information
7389 sub version ()
7391   print <<EOF;
7392 automake (GNU $PACKAGE) $VERSION
7393 Written by Tom Tromey <tromey\@redhat.com>.
7395 Copyright 2004 Free Software Foundation, Inc.
7396 This is free software; see the source for copying conditions.  There is NO
7397 warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
7399   # --version always returns 0 per GNU standards.
7400   exit 0;
7403 ################################################################
7405 # Parse command line.
7406 sub parse_arguments ()
7408   # Start off as gnu.
7409   set_strictness ('gnu');
7411   my $cli_where = new Automake::Location;
7412   my %cli_options =
7413     (
7414      'libdir:s'         => \$libdir,
7415      'gnu'              => sub { set_strictness ('gnu'); },
7416      'gnits'            => sub { set_strictness ('gnits'); },
7417      'cygnus'           => sub { set_global_option ('cygnus', $cli_where); },
7418      'foreign'          => sub { set_strictness ('foreign'); },
7419      'include-deps'     => sub { unset_global_option ('no-dependencies'); },
7420      'i|ignore-deps'    => sub { set_global_option ('no-dependencies',
7421                                                     $cli_where); },
7422      'no-force'         => sub { $force_generation = 0; },
7423      'f|force-missing'  => \$force_missing,
7424      'o|output-dir:s'   => \$output_directory,
7425      'a|add-missing'    => \$add_missing,
7426      'c|copy'           => \$copy_missing,
7427      'v|verbose'        => sub { setup_channel 'verb', silent => 0; },
7428      'W|warnings:s'     => \&parse_warnings,
7429      # These long options (--Werror and --Wno-error) for backward
7430      # compatibility.  Use -Werror and -Wno-error today.
7431      'Werror'           => sub { parse_warnings 'W', 'error'; },
7432      'Wno-error'        => sub { parse_warnings 'W', 'no-error'; },
7433      );
7434   use Getopt::Long;
7435   Getopt::Long::config ("bundling", "pass_through");
7437   # See if --version or --help is used.  We want to process these before
7438   # anything else because the GNU Coding Standards require us to
7439   # `exit 0' after processing these options, and we can't guarantee this
7440   # if we treat other options first.  (Handling other options first
7441   # could produce error diagnostics, and in this condition it is
7442   # confusing if Automake does `exit 0'.)
7443   my %cli_options_1st_pass =
7444     (
7445      'version' => \&version,
7446      'help'    => \&usage,
7447      # Recognize all other options (and their arguments) but do nothing.
7448      map { $_ => sub {} } (keys %cli_options)
7449      );
7450   my @ARGV_backup = @ARGV;
7451   Getopt::Long::GetOptions %cli_options_1st_pass
7452     or exit 1;
7453   @ARGV = @ARGV_backup;
7455   # Now *really* process the options.  This time we know
7456   # that --help and --version are not present.
7457   Getopt::Long::GetOptions %cli_options
7458     or exit 1;
7460   if (defined $output_directory)
7461     {
7462       msg 'obsolete', "`--output-dir' is deprecated\n";
7463     }
7464   else
7465     {
7466       # In the next release we'll remove this entirely.
7467       $output_directory = '.';
7468     }
7470   my $errspec = 0;
7471   foreach my $arg (@ARGV)
7472     {
7473       if ($arg =~ /^-./)
7474         {
7475           fatal ("unrecognized option `$arg'\n"
7476                  . "Try `$0 --help' for more information.");
7477         }
7479       # Handle $local:$input syntax.
7480       my ($local, @rest) = split (/:/, $arg);
7481       @rest = ("$local.in",) unless @rest;
7482       my $input = locate_am @rest;
7483       if ($input)
7484         {
7485           push @input_files, $input;
7486           $output_files{$input} = join (':', ($local, @rest));
7487         }
7488       else
7489         {
7490           error "no Automake input file found for `$arg'";
7491           $errspec = 1;
7492         }
7493     }
7494   fatal "no input file found among supplied arguments"
7495     if $errspec && ! @input_files;
7498 ################################################################
7500 # Parse the WARNINGS environment variable.
7501 parse_WARNINGS;
7503 # Parse command line.
7504 parse_arguments;
7506 $configure_ac = require_configure_ac;
7508 # Do configure.ac scan only once.
7509 scan_autoconf_files;
7511 if (! @input_files)
7512   {
7513     my $msg = '';
7514     $msg = "\nDid you forget AC_CONFIG_FILES([Makefile]) in $configure_ac?"
7515       if -f 'Makefile.am';
7516     fatal ("no `Makefile.am' found for any configure output$msg");
7517   }
7519 # Now do all the work on each file.
7520 foreach my $file (@input_files)
7521   {
7522     ($am_file = $file) =~ s/\.in$//;
7523     if (! -f ($am_file . '.am'))
7524       {
7525         error "`$am_file.am' does not exist";
7526       }
7527     else
7528       {
7529         # Any warning setting now local to this Makefile.am.
7530         dup_channel_setup;
7532         generate_makefile ($am_file . '.am', $file);
7534         # Back out any warning setting.
7535         drop_channel_setup;
7536       }
7537   }
7539 exit $exit_code;
7542 ### Setup "GNU" style for perl-mode and cperl-mode.
7543 ## Local Variables:
7544 ## perl-indent-level: 2
7545 ## perl-continued-statement-offset: 2
7546 ## perl-continued-brace-offset: 0
7547 ## perl-brace-offset: 0
7548 ## perl-brace-imaginary-offset: 0
7549 ## perl-label-offset: -2
7550 ## cperl-indent-level: 2
7551 ## cperl-brace-offset: 0
7552 ## cperl-continued-brace-offset: 0
7553 ## cperl-label-offset: -2
7554 ## cperl-extra-newline-before-brace: t
7555 ## cperl-merge-trailing-else: nil
7556 ## cperl-continued-statement-offset: 2
7557 ## End: