* configure.in: Release 1.6.3.
[automake.git] / automake.in
blob6e5ef45f194d944a99bfd85c28c8bc44c036f6dd
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 # 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 $prefix = "@prefix@";
35   my $perllibdir = $ENV{'perllibdir'} || "@datadir@/@PACKAGE@-@APIVERSION@";
36   unshift @INC, "$perllibdir";
39 use Automake::Struct;
40 struct (# Short name of the language (c, f77...).
41         'name' => "\$",
42         # Nice name of the language (C, Fortran 77...).
43         'Name' => "\$",
45         # List of configure variables which must be defined.
46         'config_vars' => '@',
48         'ansi'    => "\$",
49         # `pure' is `1' or `'.  A `pure' language is one where, if
50         # all the files in a directory are of that language, then we
51         # do not require the C compiler or any code to call it.
52         'pure'   => "\$",
54         'autodep' => "\$",
56         # Name of the compiling variable (COMPILE).
57         'compiler'  => "\$",
58         # Content of the compiling variable.
59         'compile'  => "\$",
60         # Flag to require compilation without linking (-c).
61         'compile_flag' => "\$",
62         'extensions'      => '@',
63         'flags' => "\$",
64         # Should the flag be defined as a configure variable.
65         # Defaults to true.  FIXME: this should go away once
66         # we move to autoconf tracing.
67         'define_flag' => "\$",
69         # The file to use when generating rules for this language.
70         # The default is 'depend2'.
71         'rule_file' => "\$",
73         # Name of the linking variable (LINK).
74         'linker' => "\$",
75         # Content of the linking variable.
76         'link' => "\$",
78         # Name of the linker variable (LD).
79         'lder' => "\$",
80         # Content of the linker variable ($(CC)).
81         'ld' => "\$",
83         # Flag to specify the output file (-o).
84         'output_flag' => "\$",
85         '_finish' => "\$",
87         # This is a subroutine which is called whenever we finally
88         # determine the context in which a source file will be
89         # compiled.
90         '_target_hook' => "\$");
93 sub finish ($)
95   my ($self) = @_;
96   if (defined $self->_finish)
97     {
98       &{$self->_finish} ();
99     }
102 sub target_hook ($$$$)
104     my ($self) = @_;
105     if (defined $self->_target_hook)
106     {
107         &{$self->_target_hook} (@_);
108     }
111 package Automake;
113 use strict 'vars', 'subs';
114 use Automake::General;
115 use Automake::XFile;
116 use File::Basename;
117 use Carp;
119 ## ----------- ##
120 ## Constants.  ##
121 ## ----------- ##
123 # Parameters set by configure.  Not to be changed.  NOTE: assign
124 # VERSION as string so that eg version 0.30 will print correctly.
125 my $VERSION = "@VERSION@";
126 my $PACKAGE = "@PACKAGE@";
127 my $prefix = "@prefix@";
128 my $libdir = "@datadir@/@PACKAGE@-@APIVERSION@";
130 # String constants.
131 my $IGNORE_PATTERN = '^\s*##([^#\n].*)?\n';
132 my $WHITE_PATTERN = '^\s*$';
133 my $COMMENT_PATTERN = '^#';
134 my $TARGET_PATTERN='[$a-zA-Z_.@][-.a-zA-Z0-9_(){}/$+@]*';
135 # A rule has three parts: a list of targets, a list of dependencies,
136 # and optionally actions.
137 my $RULE_PATTERN =
138   "^($TARGET_PATTERN(?:(?:\\\\\n|\\s)+$TARGET_PATTERN)*) *:([^=].*|)\$";
140 my $SUFFIX_RULE_PATTERN = '^(\.[a-zA-Z0-9_(){}$+@]+)(\.[a-zA-Z0-9_(){}$+@]+)$';
141 # Only recognize leading spaces, not leading tabs.  If we recognize
142 # leading tabs here then we need to make the reader smarter, because
143 # otherwise it will think rules like `foo=bar; \' are errors.
144 my $MACRO_PATTERN = '^[A-Za-z0-9_@]+$';
145 my $ASSIGNMENT_PATTERN = '^ *([^ \t=:+]*)\s*([:+]?)=\s*(.*)$';
146 # This pattern recognizes a Gnits version id and sets $1 if the
147 # release is an alpha release.  We also allow a suffix which can be
148 # used to extend the version number with a "fork" identifier.
149 my $GNITS_VERSION_PATTERN = '\d+\.\d+([a-z]|\.\d+)?(-[A-Za-z0-9]+)?';
150 my $IF_PATTERN =          '^if\s+(!?)\s*([A-Za-z][A-Za-z0-9_]*)\s*(?:#.*)?$';
151 my $ELSE_PATTERN =   '^else(?:\s+(!?)\s*([A-Za-z][A-Za-z0-9_]*))?\s*(?:#.*)?$';
152 my $ENDIF_PATTERN = '^endif(?:\s+(!?)\s*([A-Za-z][A-Za-z0-9_]*))?\s*(?:#.*)?$';
153 my $PATH_PATTERN='(\w|[/.-])+';
154 # This will pass through anything not of the prescribed form.
155 my $INCLUDE_PATTERN = ('^include\s+'
156                        . '((\$\(top_srcdir\)/' . $PATH_PATTERN . ')'
157                        . '|(\$\(srcdir\)/' . $PATH_PATTERN . ')'
158                        . '|([^/\$]' . $PATH_PATTERN. '))\s*(#.*)?$');
160 # Some regular expressions.  One reason to put them here is that it
161 # makes indentation work better in Emacs.
162 my $AC_CONFIG_AUX_DIR_PATTERN = 'AC_CONFIG_AUX_DIR\(([^)]+)\)';
163 my $AM_INIT_AUTOMAKE_PATTERN = 'AM_INIT_AUTOMAKE\([^,]*,([^,)]+)[,)]';
164 my $AC_INIT_PATTERN = 'AC_INIT\([^,]*,([^,)]+)[,)]';
165 my $AM_PACKAGE_VERSION_PATTERN = '^\s*\[?([^]\s]+)\]?\s*$';
167 # This handles substitution references like ${foo:.a=.b}.
168 my $SUBST_REF_PATTERN = "^([^:]*):([^=]*)=(.*)\$";
170 # Note that there is no AC_PATH_TOOL.  But we don't really care.
171 my $AC_CHECK_PATTERN = 'AC_(CHECK|PATH)_(PROG|PROGS|TOOL)\(\[?(\w+)';
172 my $AM_MISSING_PATTERN = 'AM_MISSING_PROG\(\[?(\w+)';
173 # Just check for alphanumeric in AC_SUBST.  If you do AC_SUBST(5),
174 # then too bad.
175 my $AC_SUBST_PATTERN = 'AC_SUBST\(\[?(\w+)';
176 my $AM_CONDITIONAL_PATTERN = 'AM_CONDITIONAL\(\[?(\w+)';
177 # Match `-d' as a command-line argument in a string.
178 my $DASH_D_PATTERN = "(^|\\s)-d(\\s|\$)";
179 # Directories installed during 'install-exec' phase.
180 my $EXEC_DIR_PATTERN =
181     '^(?:bin|sbin|libexec|sysconf|localstate|lib|pkglib|.*exec.*)$'; #'
183 # Constants to define the "strictness" level.
184 use constant FOREIGN => 0;
185 use constant GNU     => 1;
186 use constant GNITS   => 2;
188 # Values for AC_CANONICAL_*
189 use constant AC_CANONICAL_HOST   => 1;
190 use constant AC_CANONICAL_SYSTEM => 2;
192 # Values indicating when something should be cleaned.  Right now we
193 # only need to handle `mostly'- and `dist'-clean; add more as
194 # required.
195 use constant MOSTLY_CLEAN => 0;
196 use constant DIST_CLEAN   => 1;
198 # Libtool files.
199 my @libtool_files = qw(ltmain.sh config.guess config.sub);
200 # ltconfig appears here for compatibility with old versions of libtool.
201 my @libtool_sometimes = qw(ltconfig ltcf-c.sh ltcf-cxx.sh ltcf-gcj.sh);
203 # Commonly found files we look for and automatically include in
204 # DISTFILES.
205 my @common_files =
206     (qw(ABOUT-GNU ABOUT-NLS AUTHORS BACKLOG COPYING COPYING.DOC COPYING.LIB
207         ChangeLog INSTALL NEWS README THANKS TODO acinclude.m4
208         ansi2knr.1 ansi2knr.c compile config.guess config.rpath config.sub
209         configure configure.ac configure.in depcomp elisp-comp
210         install-sh libversion.in mdate-sh missing mkinstalldirs
211         py-compile texinfo.tex ylwrap),
212      @libtool_files, @libtool_sometimes);
214 # Commonly used files we auto-include, but only sometimes.
215 my @common_sometimes =
216     qw(aclocal.m4 acconfig.h config.h.top config.h.bot stamp-vti);
218 # Standard directories from the GNU Coding Standards, and additional
219 # pkg* directories from Automake.  Stored in a hash for fast member check.
220 my %standard_prefix =
221     map { $_ => 1 } (qw(bin data exec include info lib libexec lisp
222                         localstate man man1 man2 man3 man4 man5 man6
223                         man7 man8 man9 oldinclude pkgdatadir
224                         pkgincludedir pkglibdir sbin sharedstate
225                         sysconf));
227 # Copyright on generated Makefile.ins.
228 my $gen_copyright = "\
229 # Copyright 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002
230 # Free Software Foundation, Inc.
231 # This Makefile.in is free software; the Free Software Foundation
232 # gives unlimited permission to copy and/or distribute it,
233 # with or without modifications, as long as this notice is preserved.
235 # This program is distributed in the hope that it will be useful,
236 # but WITHOUT ANY WARRANTY, to the extent permitted by law; without
237 # even the implied warranty of MERCHANTABILITY or FITNESS FOR A
238 # PARTICULAR PURPOSE.
241 # These constants are returned by lang_*_rewrite functions.
242 # LANG_SUBDIR means that the resulting object file should be in a
243 # subdir if the source file is.  In this case the file name cannot
244 # have `..' components.
245 my $LANG_IGNORE = 0;
246 my $LANG_PROCESS = 1;
247 my $LANG_SUBDIR = 2;
249 # These are used when keeping track of whether an object can be built
250 # by two different paths.
251 my $COMPILE_LIBTOOL = 1;
252 my $COMPILE_ORDINARY = 2;
254 # Map from obsolete macros to hints for new macros.
255 # If you change this, change the corresponding list in aclocal.in.
256 # FIXME: should just put this into a single file.
257 my %obsolete_macros =
258     (
259      'AC_FEATURE_CTYPE'         => "use `AC_HEADER_STDC'",
260      'AC_FEATURE_ERRNO'         => "add `strerror' to `AC_REPLACE_FUNCS(...)'",
261      'AC_FEATURE_EXIT'          => '',
262      'AC_SYSTEM_HEADER'         => '',
264      # Note that we do not handle this one, because it is still run
265      # from AM_CONFIG_HEADER.  So we deal with it specially in
266      # &scan_autoconf_files.
267      # 'AC_CONFIG_HEADER'       => "use `AM_CONFIG_HEADER'",
269      'fp_C_PROTOTYPES'          => "use `AM_C_PROTOTYPES'",
270      'fp_PROG_CC_STDC'          => "use `AM_PROG_CC_STDC'",
271      'fp_PROG_INSTALL'          => "use `AC_PROG_INSTALL'",
272      'fp_WITH_DMALLOC'          => "use `AM_WITH_DMALLOC'",
273      'fp_WITH_REGEX'            => "use `AM_WITH_REGEX'",
274      'gm_PROG_LIBTOOL'          => "use `AM_PROG_LIBTOOL'",
275      'jm_MAINTAINER_MODE'       => "use `AM_MAINTAINER_MODE'",
276      'md_TYPE_PTRDIFF_T'        => "add `ptrdiff_t' to `AC_CHECK_TYPES(...)'",
277      'ud_PATH_LISPDIR'          => "use `AM_PATH_LISPDIR'",
278      'ud_GNU_GETTEXT'           => "use `AM_GNU_GETTEXT'",
280      # Now part of autoconf proper, under a different name.
281      'fp_FUNC_FNMATCH'          => "use `AC_FUNC_FNMATCH'",
282      'AM_SANITY_CHECK_CC'       => "automatically done by `AC_PROG_CC'",
283      'AM_PROG_INSTALL'          => "use `AC_PROG_INSTALL'",
284      'AM_EXEEXT'                => "automatically done by `AC_PROG_(CC|CXX|F77)'",
285      'AM_CYGWIN32'              => "use `AC_CYGWIN'",
286      'AM_MINGW32'               => "use `AC_MINGW32'",
287      'AM_FUNC_MKTIME'           => "use `AC_FUNC_MKTIME'",
288      );
290 # Regexp to match the above macros.
291 my $obsolete_rx = '\b(' . join ('|', keys %obsolete_macros) . ')\b';
295 ## ---------------------------------- ##
296 ## Variables related to the options.  ##
297 ## ---------------------------------- ##
299 # TRUE if we should always generate Makefile.in.
300 my $force_generation = 1;
302 # Strictness level as set on command line.
303 my $default_strictness = GNU;
305 # Name of strictness level, as set on command line.
306 my $default_strictness_name = 'gnu';
308 # This is TRUE if automatic dependency generation code should be
309 # included in generated Makefile.in.
310 my $cmdline_use_dependencies = 1;
312 # This holds our (eventual) exit status.  We don't actually exit until
313 # we have processed all input files.
314 my $exit_status = 0;
316 # From the Perl manual.
317 my $symlink_exists = (eval 'symlink ("", "");', $@ eq '');
319 # TRUE if missing standard files should be installed.
320 my $add_missing = 0;
322 # TRUE if we should copy missing files; otherwise symlink if possible.
323 my $copy_missing = 0;
325 # TRUE if we should always update files that we know about.
326 my $force_missing = 0;
329 ## ---------------------------------------- ##
330 ## Variables filled during files scanning.  ##
331 ## ---------------------------------------- ##
333 # Name of the top autoconf input: `configure.ac' or `configure.in'.
334 my $configure_ac = '';
336 # Files found by scanning configure.ac for LIBOBJS.
337 my %libsources = ();
339 # True if AM_C_PROTOTYPES appears in configure.ac.
340 my $am_c_prototypes = 0;
342 # Names used in AC_CONFIG_HEADER call.
343 my @config_headers = ();
344 # Where AC_CONFIG_HEADER appears.
345 my $config_header_location;
347 # Directory where output files go.  Actually, output files are
348 # relative to this directory.
349 my $output_directory;
351 # List of Makefile.am's to process, and their corresponding outputs.
352 my @input_files = ();
353 my %output_files = ();
355 # Complete list of Makefile.am's that exist.
356 my @configure_input_files = ();
358 # List of files in AC_CONFIG_FILES/AC_OUTPUT without Makefile.am's,
359 # and their outputs.
360 my @other_input_files = ();
361 # Where the last AC_CONFIG_FILES/AC_OUTPUT appears.
362 my $ac_config_files_location;
364 # List of directories to search for configure-required files.  This
365 # can be set by AC_CONFIG_AUX_DIR.
366 my @config_aux_path = qw(. .. ../..);
367 my $config_aux_dir = '';
368 my $config_aux_dir_set_in_configure_in = 0;
370 # Whether AM_GNU_GETTEXT has been seen in configure.ac.
371 my $seen_gettext = 0;
372 # Whether AM_GNU_GETTEXT([external]) is used.
373 my $seen_gettext_external = 0;
374 # Where AM_GNU_GETTEXT appears.
375 my $ac_gettext_location;
377 # TRUE if AC_PROG_LEX or AM_PROG_LEX were seen.
378 my $seen_prog_lex = 0;
380 # TRUE if we've seen AC_CANONICAL_(HOST|SYSTEM).
381 my $seen_canonical = 0;
382 my $canonical_location;
384 # Where AC_PROG_LIBTOOL appears.
385 my $seen_libtool;
387 # Where AM_MAINTAINER_MODE appears.
388 my $seen_maint_mode;
390 # Actual version we've seen.
391 my $package_version = '';
393 # Where version is defined.
394 my $package_version_location;
396 # Where AM_PATH_LISPDIR appears.
397 my $am_lispdir_location;
399 # Where AM_PATH_PYTHON appears.
400 my $pythondir_location;
402 # TRUE if we've seen AC_ENABLE_MULTILIB.
403 my $seen_multilib = 0;
405 # TRUE if we've seen AM_PROG_CC_C_O
406 my $seen_cc_c_o = 0;
408 # Where AM_INIT_AUTOMAKE is called;
409 my $seen_init_automake = 0;
411 # TRUE if we've seen AM_AUTOMAKE_VERSION.
412 my $seen_automake_version = 0;
414 # Hash table of discovered configure substitutions.  Keys are names,
415 # values are `FILE:LINE' strings which are used by error message
416 # generation.
417 my %configure_vars = ();
419 # This is used to keep track of which variable definitions we are
420 # scanning.  It is only used in certain limited ways, but it has to be
421 # global.  It is declared just for documentation purposes.
422 my %vars_scanned = ();
424 # TRUE if --cygnus seen.
425 my $cygnus_mode = 0;
427 # Hash table of AM_CONDITIONAL variables seen in configure.
428 my %configure_cond = ();
430 # This maps extensions onto language names.
431 my %extension_map = ();
433 # List of the DIST_COMMON files we discovered while reading
434 # configure.in
435 my $configure_dist_common = '';
437 # This maps languages names onto objects.
438 my %languages = ();
440 # List of targets we must always output.
441 # FIXME: Complete, and remove falsely required targets.
442 my %required_targets =
443   (
444    'all'          => 1,
445    'dvi'          => 1,
446    'info'         => 1,
447    'install-info' => 1,
448    'install'      => 1,
449    'install-data' => 1,
450    'install-exec' => 1,
451    'uninstall'    => 1,
453    # FIXME: Not required, temporary hacks.
454    # Well, actually they are sort of required: the -recursive
455    # targets will run them anyway...
456    'dvi-am'          => 1,
457    'info-am'         => 1,
458    'install-data-am' => 1,
459    'install-exec-am' => 1,
460    'installcheck-am' => 1,
461    'uninstall-am' => 1,
463    'install-man' => 1,
464   );
466 # This is set to 1 when Automake needs to be run again.
467 # (For instance, this happens when an auxiliary file such as
468 # depcomp is added after the toplevel Makefile.in -- which
469 # should distribute depcomp -- has been generated.)
470 my $automake_needs_to_reprocess_all_files = 0;
472 # Options set via AM_INIT_AUTOMAKE.
473 my $global_options = '';
475 # If a file name appears as a key in this hash, then it has already
476 # been checked for.  This variable is local to the "require file"
477 # functions.
478 my %require_file_found = ();
481 ################################################################
483 ## ------------------------------------------ ##
484 ## Variables reset by &initialize_per_input.  ##
485 ## ------------------------------------------ ##
487 # Basename and relative dir of the input file.
488 my $am_file_name;
489 my $am_relative_dir;
491 # Same but wrt Makefile.in.
492 my $in_file_name;
493 my $relative_dir;
495 # These two variables are used when generating each Makefile.in.
496 # They hold the Makefile.in until it is ready to be printed.
497 my $output_rules;
498 my $output_vars;
499 my $output_trailer;
500 my $output_all;
501 my $output_header;
503 # Suffixes found during a run.
504 my @suffixes;
506 # Handling the variables.
508 # For a $VAR:
509 # - $var_value{$VAR}{$COND} is its value associated to $COND,
510 # - $var_location{$VAR} is where it was defined,
511 # - $var_comment{$VAR} are the comments associated to it.
512 # - $var_type{$VAR} is how it has been defined (`', `+', or `:'),
513 # - $var_is_am{$VAR} is true if the variable is owned by Automake.
514 my %var_value;
515 my %var_location;
516 my %var_comment;
517 my %var_type;
518 my %var_is_am;
520 # This holds a 1 if a particular variable was examined.
521 my %content_seen;
523 # This holds the names which are targets.  These also appear in
524 # %contents.
525 my %targets;
527 # Same as %VAR_VALUE, but for targets.
528 my %target_conditional;
530 # This is the conditional stack.
531 my @cond_stack;
533 # This holds the set of included files.
534 my @include_stack;
536 # This holds a list of directories which we must create at `dist'
537 # time.  This is used in some strange scenarios involving weird
538 # AC_OUTPUT commands.
539 my %dist_dirs;
541 # List of dependencies for the obvious targets.
542 my @all;
543 my @check;
544 my @check_tests;
546 # Holds the dependencies of targets which dependencies are factored.
547 # Typically, `.PHONY' will appear in plenty of *.am files, but must
548 # be output once.  Arguably all pure dependencies could be subject
549 # to this factorization, but it is not unpleasant to have paragraphs
550 # in Makefile: keeping related stuff altogether.
551 my %dependencies;
553 # Holds the factored actions.  Tied to %DEPENDENCIES, i.e., filled
554 # only when keys exists in %DEPENDENCIES.
555 my %actions;
557 # A list of files deleted by `maintainer-clean'.
558 my @maintainer_clean_files;
560 # Keys in this hash table are object files or other files in
561 # subdirectories which need to be removed.  This only holds files
562 # which are created by compilations.  The value in the hash indicates
563 # when the file should be removed.
564 my %compile_clean_files;
566 # Keys in this hash table are directories where we expect to build a
567 # libtool object.  We use this information to decide what directories
568 # to delete.
569 my %libtool_clean_directories;
571 # Value of `$(SOURCES)', used by tags.am.
572 my @sources;
573 # Sources which go in the distribution.
574 my @dist_sources;
576 # This hash maps object file names onto their corresponding source
577 # file names.  This is used to ensure that each object is created
578 # by a single source file.
579 my %object_map;
581 # This hash maps object file names onto an integer value representing
582 # whether this object has been built via ordinary compilation or
583 # libtool compilation (the COMPILE_* constants).
584 my %object_compilation_map;
587 # This keeps track of the directories for which we've already
588 # created `.dirstamp' code.
589 my %directory_map;
591 # All .P files.
592 my %dep_files;
594 # Strictness levels.
595 my $strictness;
596 my $strictness_name;
598 # Options from AUTOMAKE_OPTIONS.
599 my %options;
601 # Whether or not dependencies are handled.  Can be further changed
602 # in handle_options.
603 my $use_dependencies;
605 # This is a list of all targets to run during "make dist".
606 my @dist_targets;
608 # Keys in this hash are the basenames of files which must depend on
609 # ansi2knr.  Values are either the empty string, or the directory in
610 # which the ANSI source file appears; the directory must have a
611 # trailing `/'.
612 my %de_ansi_files;
614 # This maps the source extension of a suffix rule to its
615 # corresponding output extension.
616 # FIXME: because this hash maps one input extension to one output
617 # extension, Automake cannot handle two suffix rules with the same
618 # input extension.
619 my %suffix_rules;
621 # This is the name of the redirect `all' target to use.
622 my $all_target;
624 # This keeps track of which extensions we've seen (that we care
625 # about).
626 my %extension_seen;
628 # This is random scratch space for the language finish functions.
629 # Don't randomly overwrite it; examine other uses of keys first.
630 my %language_scratch;
632 # We keep track of which objects need special (per-executable)
633 # handling on a per-language basis.
634 my %lang_specific_files;
636 # This is set when `handle_dist' has finished.  Once this happens,
637 # we should no longer push on dist_common.
638 my $handle_dist_run;
640 # Used to store a set of linkers needed to generate the sources currently
641 # under consideration.
642 my %linkers_used;
644 # True if we need `LINK' defined.  This is a hack.
645 my $need_link;
647 # This is the list of such variables to output.
648 # FIXME: Might be useless actually.
649 my @var_list;
651 # Was get_object_extension run?
652 # FIXME: This is a hack. a better switch should be found.
653 my $get_object_extension_was_run;
655 # Contains a stack of `from' parts of variable substitutions currently in
656 # force.
657 my @substfroms;
659 # Contains a stack of `to' parts of variable substitutions currently in
660 # force.
661 my @substtos;
663 # This keeps track of all variables defined by subobjname.
664 # The value stored is the variable names.
665 # The key has the form "(COND1)VAL1(COND2)VAL2..." where VAL1 and VAL2
666 # are the values of the variable for condition COND1 and COND2.
667 my %subobjvar = ();
669 ## --------------------------------- ##
670 ## Forward subroutine declarations.  ##
671 ## --------------------------------- ##
672 sub register_language (%);
673 sub file_contents_internal ($$%);
674 sub define_objects_from_sources ($$$$$$$);
677 # &initialize_per_input ()
678 # ------------------------
679 # (Re)-Initialize per-Makefile.am variables.
680 sub initialize_per_input ()
682     $am_file_name = '';
683     $am_relative_dir = '';
685     $in_file_name = '';
686     $relative_dir = '';
688     $output_rules = '';
689     $output_vars = '';
690     $output_trailer = '';
691     $output_all = '';
692     $output_header = '';
694     @suffixes = ();
696     %var_value = ();
697     %var_location = ();
698     %var_comment = ();
699     %var_type = ();
700     %var_is_am = ();
702     %content_seen = ();
704     %targets = ();
706     %target_conditional = ();
708     @cond_stack = ();
710     @include_stack = ();
712     %dist_dirs = ();
714     @all = ();
715     @check = ();
716     @check_tests = ();
718     %dependencies =
719       (
720        # Texinfoing.
721        'dvi'      => [],
722        'dvi-am'   => [],
723        'info'     => [],
724        'info-am'  => [],
726        # Installing/uninstalling.
727        'install-data-am'      => [],
728        'install-exec-am'      => [],
729        'uninstall-am'         => [],
731        'install-man'          => [],
732        'uninstall-man'        => [],
734        'install-info'         => [],
735        'install-info-am'      => [],
736        'uninstall-info'       => [],
738        'installcheck-am'      => [],
740        # Cleaning.
741        'clean-am'             => [],
742        'mostlyclean-am'       => [],
743        'maintainer-clean-am'  => [],
744        'distclean-am'         => [],
745        'clean'                => [],
746        'mostlyclean'          => [],
747        'maintainer-clean'     => [],
748        'distclean'            => [],
750        # Tarballing.
751        'dist-all'             => [],
753        # Phoning.
754        '.PHONY'               => []
755       );
756     %actions = ();
758     @maintainer_clean_files = ();
760     @sources = ();
761     @dist_sources = ();
763     %object_map = ();
764     %object_compilation_map = ();
766     %directory_map = ();
768     %dep_files = ();
770     $strictness = $default_strictness;
771     $strictness_name = $default_strictness_name;
773     %options = ();
775     $use_dependencies = $cmdline_use_dependencies;
777     @dist_targets = ();
779     %de_ansi_files = ();
781     %suffix_rules = ();
783     $all_target = '';
785     %extension_seen = ();
787     %language_scratch = ();
789     %lang_specific_files = ();
791     $handle_dist_run = 0;
793     $need_link = 0;
795     @var_list = ();
797     $get_object_extension_was_run = 0;
799     %compile_clean_files = ();
801     # We always include `.'.  This isn't strictly correct.
802     %libtool_clean_directories = ('.' => 1);
804     %subobjvar = ();
808 ################################################################
810 # Initialize our list of languages that are internally supported.
812 # C.
813 register_language ('name' => 'c',
814                    'Name' => 'C',
815                    'config_vars' => ['CC'],
816                    'ansi' => 1,
817                    'autodep' => '',
818                    'flags' => 'CFLAGS',
819                    'compiler' => 'COMPILE',
820                    'compile' => '$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS)',
821                    'lder' => 'CCLD',
822                    'ld' => '$(CC)',
823                    'linker' => 'LINK',
824                    'link' => '$(CCLD) $(AM_CFLAGS) $(CFLAGS) $(AM_LDFLAGS) $(LDFLAGS) -o $@',
825                    'compile_flag' => '-c',
826                    'extensions' => ['.c'],
827                    '_finish' => \&lang_c_finish);
829 # C++.
830 register_language ('name' => 'cxx',
831                    'Name' => 'C++',
832                    'config_vars' => ['CXX'],
833                    'linker' => 'CXXLINK',
834                    'link' => '$(CXXLD) $(AM_CXXFLAGS) $(CXXFLAGS) $(AM_LDFLAGS) $(LDFLAGS) -o $@',
835                    'autodep' => 'CXX',
836                    'flags' => 'CXXFLAGS',
837                    'compile' => '$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS)',
838                    'compiler' => 'CXXCOMPILE',
839                    'compile_flag' => '-c',
840                    'output_flag' => '-o',
841                    'lder' => 'CXXLD',
842                    'ld' => '$(CXX)',
843                    'pure' => 1,
844                    'extensions' => ['.c++', '.cc', '.cpp', '.cxx', '.C']);
846 # Objective C.
847 register_language ('name' => 'objc',
848                    'Name' => 'Objective C',
849                    'config_vars' => ['OBJC'],
850                    'linker' => 'OBJCLINK',,
851                    'link' => '$(OBJCLD) $(AM_OBJCFLAGS) $(OBJCFLAGS) $(AM_LDFLAGS) $(LDFLAGS) -o $@',
852                    'autodep' => 'OBJC',
853                    'flags' => 'OBJCFLAGS',
854                    'compile' => '$(OBJC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_OBJCFLAGS) $(OBJCFLAGS)',
855                    'compiler' => 'OBJCCOMPILE',
856                    'compile_flag' => '-c',
857                    'output_flag' => '-o',
858                    'lder' => 'OBJCLD',
859                    'ld' => '$(OBJC)',
860                    'pure' => 1,
861                    'extensions' => ['.m']);
863 # Headers.
864 register_language ('name' => 'header',
865                    'Name' => 'Header',
866                    'extensions' => ['.h', '.H', '.hxx', '.h++', '.hh',
867                                     '.hpp', '.inc'],
868                    # Nothing to do.
869                    '_finish' => sub { });
871 # Yacc (C & C++).
872 register_language ('name' => 'yacc',
873                    'Name' => 'Yacc',
874                    'config_vars' => ['YACC'],
875                    'flags' => 'YFLAGS',
876                    'define_flag' => 0,
877                    'compile' => '$(YACC) $(YFLAGS) $(AM_YFLAGS)',
878                    'compiler' => 'YACCCOMPILE',
879                    'extensions' => ['.y'],
880                    'rule_file' => 'yacc',
881                    '_finish' => \&lang_yacc_finish,
882                    '_target_hook' => \&lang_yacc_target_hook);
883 register_language ('name' => 'yaccxx',
884                    'Name' => 'Yacc (C++)',
885                    'config_vars' => ['YACC'],
886                    'rule_file' => 'yacc',
887                    'flags' => 'YFLAGS',
888                    'define_flag' => 0,
889                    'compiler' => 'YACCCOMPILE',
890                    'compile' => '$(YACC) $(YFLAGS) $(AM_YFLAGS)',
891                    'extensions' => ['.y++', '.yy', '.yxx', '.ypp'],
892                    '_finish' => \&lang_yacc_finish,
893                    '_target_hook' => \&lang_yacc_target_hook);
895 # Lex (C & C++).
896 register_language ('name' => 'lex',
897                    'Name' => 'Lex',
898                    'config_vars' => ['LEX'],
899                    'rule_file' => 'lex',
900                    'flags' => 'LFLAGS',
901                    'define_flag' => 0,
902                    'compile' => '$(LEX) $(LFLAGS) $(AM_LFLAGS)',
903                    'compiler' => 'LEXCOMPILE',
904                    'extensions' => ['.l'],
905                    '_finish' => \&lang_lex_finish,
906                    '_target_hook' => \&lang_lex_target_hook);
907 register_language ('name' => 'lexxx',
908                    'Name' => 'Lex (C++)',
909                    'config_vars' => ['LEX'],
910                    'rule_file' => 'lex',
911                    'flags' => 'LFLAGS',
912                    'define_flag' => 0,
913                    'compile' => '$(LEX) $(LFLAGS) $(AM_LFLAGS)',
914                    'compiler' => 'LEXCOMPILE',
915                    'extensions' => ['.l++', '.ll', '.lxx', '.lpp'],
916                    '_finish' => \&lang_lex_finish,
917                    '_target_hook' => \&lang_lex_target_hook);
919 # Assembler.
920 register_language ('name' => 'asm',
921                    'Name' => 'Assembler',
922                    'config_vars' => ['CCAS', 'CCASFLAGS'],
924                    'flags' => 'CCASFLAGS',
925                    # Users can set AM_ASFLAGS to includes DEFS, INCLUDES,
926                    # or anything else required.  They can also set AS.
927                    'compile' => '$(CCAS) $(AM_CCASFLAGS) $(CCASFLAGS)',
928                    'compiler' => 'CCASCOMPILE',
929                    'compile_flag' => '-c',
930                    'extensions' => ['.s', '.S'],
932                    # With assembly we still use the C linker.
933                    '_finish' => \&lang_c_finish);
935 # Fortran 77
936 register_language ('name' => 'f77',
937                    'Name' => 'Fortran 77',
938                    'linker' => 'F77LINK',
939                    'link' => '$(F77LD) $(AM_FFLAGS) $(FFLAGS) $(AM_LDFLAGS) $(LDFLAGS) -o $@',
940                    'flags' => 'FFLAGS',
941                    'compile' => '$(F77) $(AM_FFLAGS) $(FFLAGS)',
942                    'compiler' => 'F77COMPILE',
943                    'compile_flag' => '-c',
944                    'output_flag' => '-o',
945                    'lder' => 'F77LD',
946                    'ld' => '$(F77)',
947                    'pure' => 1,
948                    'extensions' => ['.f', '.for', '.f90']);
950 # Preprocessed Fortran 77
952 # The current support for preprocessing Fortran 77 just involves
953 # passing `$(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS)
954 # $(CPPFLAGS)' as additional flags to the Fortran 77 compiler, since
955 # this is how GNU Make does it; see the `GNU Make Manual, Edition 0.51
956 # for `make' Version 3.76 Beta' (specifically, from info file
957 # `(make)Catalogue of Rules').
959 # A better approach would be to write an Autoconf test
960 # (i.e. AC_PROG_FPP) for a Fortran 77 preprocessor, because not all
961 # Fortran 77 compilers know how to do preprocessing.  The Autoconf
962 # macro AC_PROG_FPP should test the Fortran 77 compiler first for
963 # preprocessing capabilities, and then fall back on cpp (if cpp were
964 # available).
965 register_language ('name' => 'ppf77',
966                    'Name' => 'Preprocessed Fortran 77',
967                    'config_vars' => ['F77'],
968                    'linker' => 'F77LINK',
969                    'link' => '$(F77LD) $(AM_FFLAGS) $(FFLAGS) $(AM_LDFLAGS) $(LDFLAGS) -o $@',
970                    'lder' => 'F77LD',
971                    'ld' => '$(F77)',
972                    'flags' => 'FFLAGS',
973                    'compiler' => 'PPF77COMPILE',
974                    'compile' => '$(F77) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_FFLAGS) $(FFLAGS)',
975                    'compile_flag' => '-c',
976                    'output_flag' => '-o',
977                    'pure' => 1,
978                    'extensions' => ['.F']);
980 # Ratfor.
981 register_language ('name' => 'ratfor',
982                    'Name' => 'Ratfor',
983                    'config_vars' => ['F77'],
984                    'linker' => 'F77LINK',
985                    'link' => '$(F77LD) $(AM_FFLAGS) $(FFLAGS) $(AM_LDFLAGS) $(LDFLAGS) -o $@',
986                    'lder' => 'F77LD',
987                    'ld' => '$(F77)',
988                    'flags' => 'RFLAGS',
989                    # FIXME also FFLAGS.
990                    'compile' => '$(F77) $(AM_FFLAGS) $(FFLAGS) $(AM_RFLAGS) $(RFLAGS)',
991                    'compiler' => 'RCOMPILE',
992                    'compile_flag' => '-c',
993                    'output_flag' => '-o',
994                    'pure' => 1,
995                    'extensions' => ['.r']);
997 # Java via gcj.
998 register_language ('name' => 'java',
999                    'Name' => 'Java',
1000                    'config_vars' => ['GCJ'],
1001                    'linker' => 'GCJLINK',
1002                    'link' => '$(GCJLD) $(AM_GCJFLAGS) $(GCJFLAGS) $(AM_LDFLAGS) $(LDFLAGS) -o $@',
1003                    'autodep' => 'GCJ',
1004                    'flags' => 'GCJFLAGS',
1005                    'compile' => '$(GCJ) $(AM_GCJFLAGS) $(GCJFLAGS)',
1006                    'compiler' => 'GCJCOMPILE',
1007                    'compile_flag' => '-c',
1008                    'output_flag' => '-o',
1009                    'lder' => 'GCJLD',
1010                    'ld' => '$(GCJ)',
1011                    'pure' => 1,
1012                    'extensions' => ['.java', '.class', '.zip', '.jar']);
1014 ################################################################
1016 # Parse command line.
1017 &parse_arguments;
1019 # Do configure.ac scan only once.
1020 &scan_autoconf_files;
1022 die "$me: no `Makefile.am' found or specified\n"
1023     if ! @input_files;
1025 my $automake_has_run = 0;
1029     if ($automake_has_run)
1030     {
1031         verbose "processing Makefiles another time to fix them up.\n";
1032         &prog_error ("running more than two times should never be needed.")
1033             if $automake_has_run >= 2;
1034     }
1035     $automake_needs_to_reprocess_all_files = 0;
1037     # Now do all the work on each file.
1038     # This guy must be local otherwise it's private to the loop.
1039     use vars '$am_file';
1040     local $am_file;
1041     foreach $am_file (@input_files)
1042     {
1043         if (! -f ($am_file . '.am'))
1044         {
1045             &am_error ("`" . $am_file . ".am' does not exist");
1046         }
1047         else
1048         {
1049             &generate_makefile ($output_files{$am_file}, $am_file);
1050         }
1051     }
1052     ++$automake_has_run;
1054 while ($automake_needs_to_reprocess_all_files);
1056 exit $exit_status;
1058 ################################################################
1060 # prog_error (@PRINT-ME)
1061 # ----------------------
1062 # Signal a programming error, display PRINT-ME, and exit 1.
1063 sub prog_error (@)
1065     print STDERR "$me: programming error: @_\n";
1066     exit 1;
1070 # subst ($TEXT)
1071 # -------------
1072 # Return a configure-style substitution using the indicated text.
1073 # We do this to avoid having the substitutions directly in automake.in;
1074 # when we do that they are sometimes removed and this causes confusion
1075 # and bugs.
1076 sub subst ($)
1078     my ($text) = @_;
1079     return '@' . $text . '@';
1082 ################################################################
1085 # $BACKPATH
1086 # &backname ($REL-DIR)
1087 # --------------------
1088 # If I `cd $REL-DIR', then to come back, I should `cd $BACKPATH'.
1089 # For instance `src/foo' => `../..'.
1090 # Works with non strictly increasing paths, i.e., `src/../lib' => `..'.
1091 sub backname ($)
1093     my ($file) = @_;
1094     my @res;
1095     foreach (split (/\//, $file))
1096     {
1097         next if $_ eq '.' || $_ eq '';
1098         if ($_ eq '..')
1099         {
1100             pop @res;
1101         }
1102         else
1103         {
1104             push (@res, '..');
1105         }
1106     }
1107     return join ('/', @res) || '.';
1110 ################################################################
1112 # Pattern that matches all know input extensions (i.e. extensions used
1113 # by the languages supported by Automake).  Using this pattern
1114 # (instead of `\..*$') to match extensions allows Automake to support
1115 # dot-less extensions.
1116 my $KNOWN_EXTENSIONS_PATTERN = "";
1117 my @known_extensions_list = ();
1119 # accept_extensions (@EXTS)
1120 # -------------------------
1121 # Update $KNOWN_EXTENSIONS_PATTERN to recognize the extensions
1122 # listed @EXTS.  Extensions should contain a dot if needed.
1123 sub accept_extensions (@)
1125     push @known_extensions_list, @_;
1126     $KNOWN_EXTENSIONS_PATTERN =
1127         '(?:' . join ('|', map (quotemeta, @known_extensions_list)) . ')';
1130 # var_SUFFIXES_trigger ($TYPE, $VALUE)
1131 # ------------------------------------
1132 # This is called automagically by define_macro() when SUFFIXES
1133 # is defined ($TYPE eq '') or appended ($TYPE eq '+').
1134 # The work here needs to be performed as a side-effect of the
1135 # define_macro() call because SUFFIXES definitions impact
1136 # on $KNOWN_EXTENSIONS_PATTERN, and $KNOWN_EXTENSIONS_PATTERN
1137 # are used when parsing the input am file.
1138 sub var_SUFFIXES_trigger ($$)
1140     my ($type, $value) = @_;
1141     accept_extensions (split (' ', $value));
1144 ################################################################
1146 # Parse command line.
1147 sub parse_arguments ()
1149     # Start off as gnu.
1150     &set_strictness ('gnu');
1152     use Getopt::Long;
1153     Getopt::Long::config ("bundling", "pass_through");
1154     Getopt::Long::GetOptions
1155       (
1156        'version'        => \&version,
1157        'help'           => \&usage,
1158        'libdir:s'       => \$libdir,
1159        'gnu'            => sub { &set_strictness ('gnu'); },
1160        'gnits'          => sub { &set_strictness ('gnits'); },
1161        'cygnus'         => \$cygnus_mode,
1162        'foreign'        => sub { &set_strictness ('foreign'); },
1163        'include-deps'   => sub { $cmdline_use_dependencies = 1; },
1164        'i|ignore-deps'  => sub { $cmdline_use_dependencies = 0; },
1165        'no-force'       => sub { $force_generation = 0; },
1166        'f|force-missing'=> \$force_missing,
1167        'o|output-dir:s' => \$output_directory,
1168        'a|add-missing'  => \$add_missing,
1169        'c|copy'         => \$copy_missing,
1170        'v|verbose'      => \$verbose,
1171        'Werror'         => sub { $SIG{"__WARN__"} = sub { die $_[0] } },
1172        'Wno-error'      => sub { $SIG{"__WARN__"} = 'DEFAULT' }
1173       )
1174         or exit 1;
1176     if (defined $output_directory)
1177     {
1178         print STDERR "$0: `--output-dir' is deprecated\n";
1179     }
1180     else
1181     {
1182         # In the next release we'll remove this entirely.
1183         $output_directory = '.';
1184     }
1186     foreach my $arg (@ARGV)
1187     {
1188       if ($arg =~ /^-./)
1189         {
1190           print STDERR "$0: unrecognized option `$arg'\n";
1191           print STDERR "Try `$0 --help' for more information.\n";
1192           exit (1);
1193         }
1195       # Handle $local:$input syntax.  Note that we only examine the
1196       # first ":" file to see if it is automake input; the rest are
1197       # just taken verbatim.  We still keep all the files around for
1198       # dependency checking, however.
1199       my ($local, $input, @rest) = split (/:/, $arg);
1200       if (! $input)
1201         {
1202           $input = $local;
1203         }
1204       else
1205         {
1206           # Strip .in; later on .am is tacked on.  That is how the
1207           # automake input file is found.  Maybe not the best way, but
1208           # it is easy to explain.
1209           $input =~ s/\.in$//
1210             or die "$me: invalid input file name `$arg'\n.";
1211         }
1212       push (@input_files, $input);
1213       $output_files{$input} = join (':', ($local, @rest));
1214     }
1216     # Take global strictness from whatever we currently have set.
1217     $default_strictness = $strictness;
1218     $default_strictness_name = $strictness_name;
1221 ################################################################
1223 # Generate a Makefile.in given the name of the corresponding Makefile and
1224 # the name of the file output by config.status.
1225 sub generate_makefile
1227     my ($output, $makefile) = @_;
1229     # Reset all the Makefile.am related variables.
1230     &initialize_per_input;
1232     # Name of input file ("Makefile.am") and output file
1233     # ("Makefile.in").  These have no directory components.
1234     $am_file_name = basename ($makefile) . '.am';
1235     $in_file_name = basename ($makefile) . '.in';
1237     # $OUTPUT is encoded.  If it contains a ":" then the first element
1238     # is the real output file, and all remaining elements are input
1239     # files.  We don't scan or otherwise deal with these input file,
1240     # other than to mark them as dependencies.  See
1241     # &scan_autoconf_files for details.
1242     my (@secondary_inputs);
1243     ($output, @secondary_inputs) = split (/:/, $output);
1245     $relative_dir = dirname ($output);
1246     $am_relative_dir = dirname ($makefile);
1248     &read_main_am_file ($makefile . '.am');
1249     if (&handle_options)
1250     {
1251         # Fatal error.  Just return, so we can continue with next file.
1252         return;
1253     }
1255     # There are a few install-related variables that you should not define.
1256     foreach my $var ('PRE_INSTALL', 'POST_INSTALL', 'NORMAL_INSTALL')
1257     {
1258         if (variable_defined ($var) && !$var_is_am{$var})
1259         {
1260             macro_error ($var, "`$var' should not be defined");
1261         }
1262     }
1264     # At the toplevel directory, we might need config.guess, config.sub
1265     # or libtool scripts (ltconfig and ltmain.sh).
1266     if ($relative_dir eq '.')
1267     {
1268         # AC_CANONICAL_HOST and AC_CANONICAL_SYSTEM need config.guess and
1269         # config.sub.
1270         require_conf_file ($canonical_location, FOREIGN,
1271                            'config.guess', 'config.sub')
1272           if $seen_canonical;
1273     }
1275     # We still need Makefile.in here, because sometimes the `dist'
1276     # target doesn't re-run automake.
1277     if ($am_relative_dir eq $relative_dir)
1278     {
1279         # Only distribute the files if they are in the same subdir as
1280         # the generated makefile.
1281         &push_dist_common ($in_file_name, $am_file_name);
1282     }
1284     push (@sources, '$(SOURCES)')
1285         if variable_defined ('SOURCES');
1287     # Must do this after reading .am file.  See read_main_am_file to
1288     # understand weird tricks we play there with variables.
1289     &define_variable ('subdir', $relative_dir);
1291     # Check first, because we might modify some state.
1292     &check_cygnus;
1293     &check_gnu_standards;
1294     &check_gnits_standards;
1296     &handle_configure ($output, $makefile, @secondary_inputs);
1297     &handle_gettext;
1298     &handle_libraries;
1299     &handle_ltlibraries;
1300     &handle_programs;
1301     &handle_scripts;
1303     # This must run first so that the ANSI2KNR definition is generated
1304     # before it is used by the _.c rules.  We have to do this because
1305     # a variable which is used in a dependency must be defined before
1306     # the target, or else make won't properly see it.
1307     &handle_compile;
1308     # This must be run after all the sources are scanned.
1309     &handle_languages;
1311     # We have to run this after dealing with all the programs.
1312     &handle_libtool;
1314     # Re-init SOURCES.  FIXME: other code shouldn't depend on this
1315     # (but currently does).
1316     macro_define ('SOURCES', 1, '', 'TRUE', "@sources", 'internal');
1317     define_pretty_variable ('DIST_SOURCES', '', @dist_sources);
1319     &handle_multilib;
1320     &handle_texinfo;
1321     &handle_emacs_lisp;
1322     &handle_python;
1323     &handle_java;
1324     &handle_man_pages;
1325     &handle_data;
1326     &handle_headers;
1327     &handle_subdirs;
1328     &handle_tags;
1329     &handle_minor_options;
1330     &handle_tests;
1332     # This must come after most other rules.
1333     &handle_dist ($makefile);
1335     &handle_footer;
1336     &do_check_merge_target;
1337     &handle_all ($output);
1339     # FIXME: Gross!
1340     if (variable_defined ('lib_LTLIBRARIES') &&
1341         variable_defined ('bin_PROGRAMS'))
1342     {
1343         $output_rules .= "install-binPROGRAMS: install-libLTLIBRARIES\n\n";
1344     }
1346     &handle_installdirs;
1347     &handle_clean;
1348     &handle_factored_dependencies;
1350     check_typos ();
1352     if (! -d ($output_directory . '/' . $am_relative_dir))
1353     {
1354         mkdir ($output_directory . '/' . $am_relative_dir, 0755);
1355     }
1357     my ($out_file) = $output_directory . '/' . $makefile . ".in";
1358     if (! $force_generation && -e $out_file)
1359     {
1360         my ($am_time) = (stat ($makefile . '.am'))[9];
1361         my ($in_time) = (stat ($out_file))[9];
1362         # FIXME: should cache these times.
1363         my ($conf_time) = (stat ($configure_ac))[9];
1364         # FIXME: how to do unsigned comparison?
1365         if ($am_time < $in_time || $am_time < $conf_time)
1366         {
1367             # No need to update.
1368             return;
1369         }
1370         if (-f 'aclocal.m4')
1371         {
1372             my ($acl_time) = (stat _)[9];
1373             return if ($am_time < $acl_time);
1374         }
1375     }
1377     if (-e "$out_file")
1378     {
1379         unlink ($out_file)
1380             or die "$me: cannot remove $out_file: $!\n";
1381     }
1382     my $gm_file = new Automake::XFile "> $out_file";
1383     verbose "creating ", $makefile, ".in";
1385     print $gm_file $output_vars;
1386     # We make sure that `all:' is the first target.
1387     print $gm_file $output_all;
1388     print $gm_file $output_header;
1389     print $gm_file $output_rules;
1390     print $gm_file $output_trailer;
1393 ################################################################
1395 # A version is a string that looks like
1396 #   MAJOR.MINOR[.MICRO][ALPHA][-FORK]
1397 # where
1398 #   MAJOR, MINOR, and MICRO are digits, ALPHA is a character, and
1399 # FORK any alphanumeric word.
1400 # Usually, ALPHA is used to label alpha releases or intermediate snapshots,
1401 # FORK is used for CVS branches or patched releases, and MICRO is used
1402 # for bug fixes releases on the MAJOR.MINOR branch.
1404 # For the purpose of ordering, 1.4 is the same as 1.4.0, but 1.4g is
1405 # the same as 1.4.99g.  The FORK identifier is ignored in the
1406 # ordering, except when it looks like -pMINOR[ALPHA]: some versions
1407 # were labelled like 1.4-p3a, this is the same as an alpha release
1408 # labelled 1.4.3a.  Yes it's horrible, but Automake did not support
1409 # two-dot versions in the past.
1411 # version_split (VERSION)
1412 # -----------------------
1413 # Split a version string into the corresponding (MAJOR, MINOR, MICRO,
1414 # ALPHA, FORK) tuple.  For instance "1.4g" would be split into
1415 # (1, 4, 99, 'g', '').
1416 # Return () on error.
1417 sub version_split ($)
1419     my ($ver) = @_;
1421     # Special case for versions like 1.4-p2a.
1422     if ($ver =~ /^(\d+)\.(\d+)(?:-p(\d+)([a-z]+)?)$/)
1423     {
1424         return ($1, $2, $3, $4 || '', '');
1425     }
1426     # Common case.
1427     elsif ($ver =~ /^(\d+)\.(\d+)(?:\.(\d+))?([a-z])?(?:-([A-Za-z0-9]+))?$/)
1428     {
1429         return ($1, $2, $3 || (defined $4 ? 99 : 0), $4 || '', $5 || '');
1430     }
1431     return ();
1434 # version_compare (\@LVERSION, \@RVERSION)
1435 # ----------------------------------------
1436 # Return 1 if LVERSION > RVERSION,
1437 #       -1 if LVERSION < RVERSION,
1438 #        0 if LVERSION = RVERSION.
1439 sub version_compare (\@\@)
1441     my @l = @{$_[0]};
1442     my @r = @{$_[1]};
1444     for my $i (0, 1, 2)
1445     {
1446         return 1  if ($l[$i] > $r[$i]);
1447         return -1 if ($l[$i] < $r[$i]);
1448     }
1449     for my $i (3, 4)
1450     {
1451         return 1  if ($l[$i] gt $r[$i]);
1452         return -1 if ($l[$i] lt $r[$i]);
1453     }
1454     return 0;
1457 # Handles the logic of requiring a version number in AUTOMAKE_OPTIONS.
1458 # Return 0 if the required version is satisfied, 1 otherwise.
1459 sub version_check ($)
1461     my ($required) = @_;
1462     my @version = version_split $VERSION;
1463     my @required = version_split $required;
1465     prog_error ("version is incorrect: $VERSION")
1466         if $#version == -1;
1468     # This should not happen, because process_option_list and split_version
1469     # use similar regexes.
1470     prog_error ("required version is incorrect: $required")
1471         if $#required == -1;
1473     # If we require 3.4n-foo then we require something
1474     # >= 3.4n, with the `foo' fork identifier.
1475     return 1
1476         if ($required[4] ne '' && $required[4] ne $version[4]);
1478     return 0 > version_compare @version, @required;
1481 # $BOOL
1482 # process_option_list ($CONFIG, @OPTIONS)
1483 # ------------------------------
1484 # Process a list of options.  Return 1 on error, 0 otherwise.
1485 # This is a helper for handle_options.  CONFIG is true if we're
1486 # handling global options.
1487 sub process_option_list
1489     my ($config, @list) = @_;
1490     foreach (@list)
1491     {
1492         $options{$_} = 1;
1493         if ($_ eq 'gnits' || $_ eq 'gnu' || $_ eq 'foreign')
1494         {
1495             &set_strictness ($_);
1496         }
1497         elsif ($_ eq 'cygnus')
1498         {
1499             $cygnus_mode = 1;
1500         }
1501         elsif (/^(.*\/)?ansi2knr$/)
1502         {
1503             # An option like "../lib/ansi2knr" is allowed.  With no
1504             # path prefix, we assume the required programs are in this
1505             # directory.  We save the actual option for later.
1506             $options{'ansi2knr'} = $_;
1507         }
1508         elsif ($_ eq 'no-installman' || $_ eq 'no-installinfo'
1509                || $_ eq 'dist-shar' || $_ eq 'dist-zip'
1510                || $_ eq 'dist-tarZ' || $_ eq 'dist-bzip2'
1511                || $_ eq 'dejagnu' || $_ eq 'no-texinfo.tex'
1512                || $_ eq 'readme-alpha' || $_ eq 'check-news'
1513                || $_ eq 'subdir-objects' || $_ eq 'nostdinc'
1514                || $_ eq 'no-exeext' || $_ eq 'no-define')
1515         {
1516             # Explicitly recognize these.
1517         }
1518         elsif ($_ eq 'no-dependencies')
1519         {
1520             $use_dependencies = 0;
1521         }
1522         elsif (/^\d+\.\d+(?:\.\d+)?[a-z]?(?:-[A-Za-z0-9]+)?$/)
1523         {
1524             # Got a version number.
1525             if (version_check $&)
1526             {
1527                 if ($config)
1528                 {
1529                     file_error ($seen_init_automake,
1530                                 "require version $_, but have $VERSION");
1531                     # Arrange to process this global option only once, otherwise
1532                     # the error message would be printed for each Makefile.
1533                     $global_options =~ s/(?:^| )$_(?: |$)/ /g;
1534                 }
1535                 else
1536                 {
1537                     macro_error ('AUTOMAKE_OPTIONS',
1538                                  "require version $_, but have $VERSION");
1539                 }
1540                 return 1;
1541             }
1542         }
1543         else
1544         {
1545             if ($config)
1546             {
1547                 file_error ($seen_init_automake,
1548                             "option `" . $_ . "\' not recognized");
1549             }
1550             else
1551             {
1552                 macro_error ('AUTOMAKE_OPTIONS',
1553                              "option `" . $_ . "\' not recognized");
1554             }
1555             return 1;
1556         }
1557     }
1560 # Handle AUTOMAKE_OPTIONS variable.  Return 1 on error, 0 otherwise.
1561 sub handle_options
1563     # Process global options first so that more specific options can
1564     # override.
1565     if (&process_option_list (1, split (' ', $global_options)))
1566     {
1567         return 1;
1568     }
1570     if (variable_defined ('AUTOMAKE_OPTIONS'))
1571     {
1572         if (&process_option_list (0, &variable_value_as_list_recursive ('AUTOMAKE_OPTIONS', '')))
1573         {
1574             return 1;
1575         }
1576     }
1578     if ($strictness == GNITS)
1579     {
1580         $options{'readme-alpha'} = 1;
1581         $options{'check-news'} = 1;
1582     }
1584     return 0;
1588 # get_object_extension ($OUT)
1589 # ---------------------------
1590 # Return object extension.  Just once, put some code into the output.
1591 # OUT is the name of the output file
1592 sub get_object_extension
1594     my ($out) = @_;
1596     # Maybe require libtool library object files.
1597     my $extension = '.$(OBJEXT)';
1598     $extension = '.lo' if ($out =~ /\.la$/);
1600     # Check for automatic de-ANSI-fication.
1601     $extension = '$U' . $extension
1602       if defined $options{'ansi2knr'};
1604     $get_object_extension_was_run = 1;
1606     return $extension;
1610 # Call finish function for each language that was used.
1611 sub handle_languages
1613     if ($use_dependencies)
1614     {
1615         # Include auto-dep code.  Don't include it if DEP_FILES would
1616         # be empty.
1617         if (&saw_sources_p (0) && keys %dep_files)
1618         {
1619             # Set location of depcomp.
1620             &define_variable ('depcomp', "\$(SHELL) $config_aux_dir/depcomp");
1621             &define_variable ('am__depfiles_maybe', 'depfiles');
1623             require_conf_file ("$am_file.am", FOREIGN, 'depcomp');
1625             my @deplist = sort keys %dep_files;
1627             # We define this as a conditional variable because BSD
1628             # make can't handle backslashes for continuing comments on
1629             # the following line.
1630             define_pretty_variable ('DEP_FILES', 'AMDEP_TRUE', @deplist);
1632             # Generate each `include' individually.  Irix 6 make will
1633             # not properly include several files resulting from a
1634             # variable expansion; generating many separate includes
1635             # seems safest.
1636             $output_rules .= "\n";
1637             foreach my $iter (@deplist)
1638             {
1639                 $output_rules .= (subst ('AMDEP_TRUE')
1640                                   . subst ('am__include')
1641                                   . ' '
1642                                   . subst ('am__quote')
1643                                   . $iter
1644                                   . subst ('am__quote')
1645                                   . "\n");
1646             }
1648             # Compute the set of directories to remove in distclean-depend.
1649             my @depdirs = uniq (map { dirname ($_) } @deplist);
1650             $output_rules .= &file_contents ('depend',
1651                                              DEPDIRS => "@depdirs");
1652         }
1653     }
1654     else
1655     {
1656         &define_variable ('depcomp', '');
1657         &define_variable ('am__depfiles_maybe', '');
1658     }
1660     my %done;
1662     # Is the c linker needed?
1663     my $needs_c = 0;
1664     foreach my $ext (sort keys %extension_seen)
1665     {
1666         next unless $extension_map{$ext};
1668         my $lang = $languages{$extension_map{$ext}};
1670         my $rule_file = $lang->rule_file || 'depend2';
1672         # Get information on $LANG.
1673         my $pfx = $lang->autodep;
1674         my $fpfx = ($pfx eq '') ? 'CC' : $pfx;
1676         my $AMDEP = (($use_dependencies && $lang->autodep ne 'no')
1677                      ? 'AMDEP' : 'FALSE');
1679         my %transform = ('EXT'     => $ext,
1680                          'PFX'     => $pfx,
1681                          'FPFX'    => $fpfx,
1682                          'LIBTOOL' => defined $seen_libtool,
1683                          'AMDEP'   => $AMDEP,
1684                          '-c'      => $lang->compile_flag || '',
1685                          'MORE-THAN-ONE'
1686                                    => (count_files_for_language ($lang->name) > 1));
1688         # Generate the appropriate rules for this extension.
1689         if (($use_dependencies && $lang->autodep ne 'no')
1690             || defined $lang->compile)
1691         {
1692             # Some C compilers don't support -c -o.  Use it only if really
1693             # needed.
1694             my $output_flag = $lang->output_flag || '';
1695             $output_flag = '-o'
1696               if (! $output_flag
1697                   && $lang->flags eq 'CFLAGS'
1698                   && defined $options{'subdir-objects'});
1700             # FIXME: this is a temporary hack to compute a possible
1701             # derived extension.  This is not used by depend2.am.
1702             (my $der_ext = $ext) =~ tr/yl/cc/;
1704             # Another yacc/lex hack.
1705             my $destfile = '$*' . $der_ext;
1707             $output_rules .=
1708               file_contents ($rule_file,
1709                              %transform,
1710                              'GENERIC'   => 1,
1712                              'DERIVED-EXT' => $der_ext,
1714                              # In this situation we know that the
1715                              # object is in this directory, so
1716                              # $(DEPDIR) is the correct location for
1717                              # dependencies.
1718                              'DEPBASE'   => '$(DEPDIR)/$*',
1719                              'BASE'      => '$*',
1720                              'SOURCE'    => '$<',
1721                              'OBJ'       => '$@',
1722                              'OBJOBJ'    => '$@',
1723                              'LTOBJ'     => '$@',
1725                              'COMPILE'   => '$(' . $lang->compiler . ')',
1726                              'LTCOMPILE' => '$(LT' . $lang->compiler . ')',
1727                              '-o'        => $output_flag);
1728         }
1730         # Now include code for each specially handled object with this
1731         # language.
1732         my %seen_files = ();
1733         foreach my $file (@{$lang_specific_files{$lang->name}})
1734         {
1735             my ($derived, $source, $obj, $myext) = split (' ', $file);
1737             # For any specially-generated object, we must respect the
1738             # ansi2knr setting so that we don't inadvertently try to
1739             # use the default rule.
1740             if ($lang->ansi && defined $options{'ansi2knr'})
1741             {
1742                 $myext = '$U' . $myext;
1743             }
1745             # We might see a given object twice, for instance if it is
1746             # used under different conditions.
1747             next if defined $seen_files{$obj};
1748             $seen_files{$obj} = 1;
1750             my $flags = $lang->flags || '';
1751             my $val = "${derived}_${flags}";
1753             prog_error ("found $lang->name in handle_languages, but compiler not defined")
1754                 unless defined $lang->compile;
1756             (my $obj_compile = $lang->compile) =~ s/\(AM_$flags/\($val/;
1757             my $obj_ltcompile = '$(LIBTOOL) --mode=compile ' . $obj_compile;
1759             # We _need_ `-o' for per object rules.
1760             my $output_flag = $lang->output_flag || '-o';
1762             my $depbase = dirname ($obj);
1763             $depbase = ''
1764                 if $depbase eq '.';
1765             $depbase .= '/'
1766                 unless $depbase eq '';
1767             $depbase .= '$(DEPDIR)/' . basename ($obj);
1769             # Generate a transform which will turn suffix targets in
1770             # depend2.am into real targets for the particular objects we
1771             # are building.
1772             $output_rules .=
1773               file_contents ($rule_file,
1774                              (%transform,
1775                               'GENERIC'   => 0,
1777                               'DEPBASE'   => $depbase,
1778                               'BASE'      => $obj,
1779                               'SOURCE'    => $source,
1780                               # Use $myext and not `.o' here, in case
1781                               # we are actually building a new source
1782                               # file -- e.g. via yacc.
1783                               'OBJ'       => "$obj$myext",
1784                               'OBJOBJ'    => "$obj.obj",
1785                               'LTOBJ'     => "$obj.lo",
1787                               'COMPILE'   => $obj_compile,
1788                               'LTCOMPILE' => $obj_ltcompile,
1789                               '-o'        => $output_flag));
1790         }
1792         # The rest of the loop is done once per language.
1793         next if defined $done{$lang};
1794         $done{$lang} = 1;
1796         # Load the language dependent Makefile chunks.
1797         my %lang = map { uc ($_) => 0 } keys %languages;
1798         $lang{uc ($lang->name)} = 1;
1799         $output_rules .= file_contents ('lang-compile', %transform, %lang);
1801         # If the source to a program consists entirely of code from a
1802         # `pure' language, for instance C++ for Fortran 77, then we
1803         # don't need the C compiler code.  However if we run into
1804         # something unusual then we do generate the C code.  There are
1805         # probably corner cases here that do not work properly.
1806         # People linking Java code to Fortran code deserve pain.
1807         $needs_c ||= ! $lang->pure;
1809         define_compiler_variable ($lang)
1810           if ($lang->compile);
1812         define_linker_variable ($lang)
1813           if ($lang->link);
1815         foreach my $var (@{$lang->config_vars})
1816           {
1817             am_error ($lang->Name
1818                       . " source seen but `$var' not defined in"
1819                       . " `$configure_ac'")
1820               if !exists $configure_vars{$var};
1821           }
1823         # The compiler's flag must be a configure variable.
1824         define_configure_variable ($lang->flags)
1825             if defined $lang->flags && $lang->define_flag;
1827         # Call the finisher.
1828         $lang->finish;
1829     }
1831     # If the project is entirely C++ or entirely Fortran 77 (i.e., 1
1832     # suffix rule was learned), don't bother with the C stuff.  But if
1833     # anything else creeps in, then use it.
1834     $needs_c = 1
1835       if $need_link || scalar keys %suffix_rules > 1;
1837     if ($needs_c)
1838       {
1839         if (! defined $done{$languages{'c'}})
1840           {
1841             &define_configure_variable ($languages{'c'}->flags);
1842             &define_compiler_variable ($languages{'c'});
1843           }
1844         define_linker_variable ($languages{'c'});
1845       }
1848 # Check to make sure a source defined in LIBOBJS is not explicitly
1849 # mentioned.  This is a separate function (as opposed to being inlined
1850 # in handle_source_transform) because it isn't always appropriate to
1851 # do this check.
1852 sub check_libobjs_sources
1854     my ($one_file, $unxformed) = @_;
1856     foreach my $prefix ('', 'EXTRA_', 'dist_', 'nodist_',
1857                         'dist_EXTRA_', 'nodist_EXTRA_')
1858     {
1859         my @files;
1860         if (variable_defined ($prefix . $one_file . '_SOURCES'))
1861         {
1862             @files = &variable_value_as_list_recursive (
1863                                 ($prefix . $one_file . '_SOURCES'),
1864                                 'all');
1865         }
1866         elsif ($prefix eq '')
1867         {
1868             @files = ($unxformed . '.c');
1869         }
1870         else
1871         {
1872             next;
1873         }
1875         foreach my $file (@files)
1876         {
1877           macro_error ($prefix . $one_file . '_SOURCES',
1878                        "automatically discovered file `$file' should not be explicitly mentioned")
1879             if defined $libsources{$file};
1880         }
1881     }
1885 # @OBJECTS
1886 # handle_single_transform_list ($VAR, $TOPPARENT, $DERIVED, $OBJ, @FILES)
1887 # -----------------------------------------------------------------------
1888 # Does much of the actual work for handle_source_transform.
1889 # Arguments are:
1890 #   $VAR is the name of the variable that the source filenames come from
1891 #   $TOPPARENT is the name of the _SOURCES variable which is being processed
1892 #   $DERIVED is the name of resulting executable or library
1893 #   $OBJ is the object extension (e.g., `$U.lo')
1894 #   @FILES is the list of source files to transform
1895 # Result is a list of the names of objects
1896 # %linkers_used will be updated with any linkers needed
1897 sub handle_single_transform_list ($$$$@)
1899     my ($var, $topparent, $derived, $obj, @files) = @_;
1900     my @result = ();
1901     my $nonansi_obj = $obj;
1902     $nonansi_obj =~ s/\$U//g;
1904     # Turn sources into objects.  We use a while loop like this
1905     # because we might add to @files in the loop.
1906     while (scalar @files > 0)
1907     {
1908         $_ = shift @files;
1910         # Configure substitutions in _SOURCES variables are errors.
1911         if (/^\@.*\@$/)
1912         {
1913             macro_error ($var,
1914                          "`$var' includes configure substitution `$_', and is referred to from `$topparent': configure substitutions not allowed in _SOURCES variables");
1915             next;
1916         }
1918         # If the source file is in a subdirectory then the `.o' is put
1919         # into the current directory, unless the subdir-objects option
1920         # is in effect.
1922         # Split file name into base and extension.
1923         next if ! /^(?:(.*)\/)?([^\/]*)($KNOWN_EXTENSIONS_PATTERN)$/;
1924         my $full = $_;
1925         my $directory = $1 || '';
1926         my $base = $2;
1927         my $extension = $3;
1929         # We must generate a rule for the object if it requires its own flags.
1930         my $renamed = 0;
1931         my ($linker, $object);
1933         # This records whether we've seen a derived source file (eg,
1934         # yacc output).
1935         my $derived_source = 0;
1937         # This holds the `aggregate context' of the file we are
1938         # currently examining.  If the file is compiled with
1939         # per-object flags, then it will be the name of the object.
1940         # Otherwise it will be `AM'.  This is used by the target hook
1941         # language function.
1942         my $aggregate = 'AM';
1944         $extension = &derive_suffix ($extension, $nonansi_obj);
1945         my $lang;
1946         if ($extension_map{$extension} &&
1947             ($lang = $languages{$extension_map{$extension}}))
1948         {
1949             # Found the language, so see what it says.
1950             &saw_extension ($extension);
1952             # Note: computed subr call.  The language rewrite function
1953             # should return one of the $LANG_* constants.  It could
1954             # also return a list whose first value is such a constant
1955             # and whose second value is a new source extension which
1956             # should be applied.  This means this particular language
1957             # generates another source file which we must then process
1958             # further.
1959             my $subr = 'lang_' . $lang->name . '_rewrite';
1960             my ($r, $source_extension)
1961                 = & $subr ($directory, $base, $extension);
1962             # Skip this entry if we were asked not to process it.
1963             next if $r == $LANG_IGNORE;
1965             # Now extract linker and other info.
1966             $linker = $lang->linker;
1968             my $this_obj_ext;
1969             if (defined $source_extension)
1970             {
1971                 $this_obj_ext = $source_extension;
1972                 $derived_source = 1;
1973             }
1974             elsif ($lang->ansi)
1975             {
1976                 $this_obj_ext = $obj;
1977             }
1978             else
1979             {
1980                 $this_obj_ext = $nonansi_obj;
1981             }
1982             $object = $base . $this_obj_ext;
1984             if (defined $lang->flags
1985                 && variable_defined ($derived . '_' . $lang->flags))
1986             {
1987                 # We have a per-executable flag in effect for this
1988                 # object.  In this case we rewrite the object's
1989                 # name to ensure it is unique.  We also require
1990                 # the `compile' program to deal with compilers
1991                 # where `-c -o' does not work.
1993                 # We choose the name `DERIVED_OBJECT' to ensure
1994                 # (1) uniqueness, and (2) continuity between
1995                 # invocations.  However, this will result in a
1996                 # name that is too long for losing systems, in
1997                 # some situations.  So we provide _SHORTNAME to
1998                 # override.
2000                 my $dname = $derived;
2001                 if (variable_defined ($derived . '_SHORTNAME'))
2002                 {
2003                     # FIXME: should use the same conditional as
2004                     # the _SOURCES variable.  But this is really
2005                     # silly overkill -- nobody should have
2006                     # conditional shortnames.
2007                     $dname = &variable_value ($derived . '_SHORTNAME');
2008                 }
2009                 $object = $dname . '-' . $object;
2011                 require_conf_file ("$am_file.am", FOREIGN, 'compile')
2012                     if $lang->name eq 'c';
2014                 prog_error ("$lang->name flags defined without compiler")
2015                     if ! defined $lang->compile;
2017                 $renamed = 1;
2018             }
2020             # If rewrite said it was ok, put the object into a
2021             # subdir.
2022             if ($r == $LANG_SUBDIR && $directory ne '')
2023             {
2024                 $object = $directory . '/' . $object;
2025             }
2027             # If doing dependency tracking, then we can't print
2028             # the rule.  If we have a subdir object, we need to
2029             # generate an explicit rule.  Actually, in any case
2030             # where the object is not in `.' we need a special
2031             # rule.  The per-object rules in this case are
2032             # generated later, by handle_languages.
2033             if ($renamed || $directory ne '')
2034             {
2035                 my $obj_sans_ext = substr ($object, 0,
2036                                            - length ($this_obj_ext));
2037                 my $val = ("$full $obj_sans_ext "
2038                            # Only use $this_obj_ext in the derived
2039                            # source case because in the other case we
2040                            # *don't* want $(OBJEXT) to appear here.
2041                            . ($derived_source ? $this_obj_ext : '.o'));
2043                 # If we renamed the object then we want to use the
2044                 # per-executable flag name.  But if this is simply a
2045                 # subdir build then we still want to use the AM_ flag
2046                 # name.
2047                 if ($renamed)
2048                 {
2049                     $val = "$derived $val";
2050                     $aggregate = $derived;
2051                 }
2052                 else
2053                 {
2054                     $val = "AM $val";
2055                 }
2057                 # Each item on this list is a string consisting of
2058                 # four space-separated values: the derived flag prefix
2059                 # (eg, for `foo_CFLAGS', it is `foo'), the name of the
2060                 # source file, the base name of the output file, and
2061                 # the extension for the object file.
2062                 push (@{$lang_specific_files{$lang->name}}, $val);
2063             }
2064         }
2065         elsif ($extension eq $nonansi_obj)
2066         {
2067             # This is probably the result of a direct suffix rule.
2068             # In this case we just accept the rewrite.
2069             $object = "$base$extension";
2070             $linker = '';
2071         }
2072         else
2073         {
2074             # No error message here.  Used to have one, but it was
2075             # very unpopular.
2076             # FIXME: we could potentially do more processing here,
2077             # perhaps treating the new extension as though it were a
2078             # new source extension (as above).  This would require
2079             # more restructuring than is appropriate right now.
2080             next;
2081         }
2083         if (defined $object_map{$object})
2084         {
2085             if ($object_map{$object} ne $full)
2086             {
2087                 am_error ("object `$object' created by `$full' and `$object_map{$object}'");
2088             }
2089         }
2091         my $comp_val = (($object =~ /\.lo$/)
2092                         ? $COMPILE_LIBTOOL : $COMPILE_ORDINARY);
2093         (my $comp_obj = $object) =~ s/\.lo$/.\$(OBJEXT)/;
2094         if (defined $object_compilation_map{$comp_obj}
2095             && $object_compilation_map{$comp_obj} != 0
2096             # Only see the error once.
2097             && ($object_compilation_map{$comp_obj}
2098                 != ($COMPILE_LIBTOOL | $COMPILE_ORDINARY))
2099             && $object_compilation_map{$comp_obj} != $comp_val)
2100         {
2101             am_error ("object `$object' created both with libtool and without");
2102         }
2103         $object_compilation_map{$comp_obj} |= $comp_val;
2105         if (defined $lang)
2106         {
2107             # Let the language do some special magic if required.
2108             $lang->target_hook ($aggregate, $object, $full);
2109         }
2111         if ($derived_source)
2112         {
2113             prog_error ("$lang->name has automatic dependency tracking")
2114                 if $lang->autodep ne 'no';
2115             # Make sure this new source file is handled next.  That will
2116             # make it appear to be at the right place in the list.
2117             unshift (@files, $object);
2118             # Distribute derived sources unless the source they are
2119             # derived from is not.
2120             &push_dist_common ($object)
2121                 unless ($topparent =~ /^(?:nobase_)?nodist_/);
2122             next;
2123         }
2125         $linkers_used{$linker} = 1;
2127         push (@result, $object);
2129         if (! defined $object_map{$object})
2130         {
2131             my @dep_list = ();
2132             $object_map{$object} = $full;
2134             # If file is in subdirectory, we need explicit
2135             # dependency.
2136             if ($directory ne '' || $renamed)
2137             {
2138                 push (@dep_list, $full);
2139             }
2141             # If resulting object is in subdir, we need to make
2142             # sure the subdir exists at build time.
2143             if ($object =~ /\//)
2144             {
2145                 # FIXME: check that $DIRECTORY is somewhere in the
2146                 # project
2148                 # For Java, the way we're handling it right now, a
2149                 # `..' component doesn't make sense.
2150                 if ($lang->name eq 'java' && $object =~ /(\/|^)\.\.\//)
2151                 {
2152                     am_error ("`$full' contains `..' component but should not");
2153                 }
2155                 # Make sure object is removed by `make mostlyclean'.
2156                 $compile_clean_files{$object} = MOSTLY_CLEAN;
2157                 # If we have a libtool object then we also must remove
2158                 # the ordinary .o.
2159                 if ($object =~ /\.lo$/)
2160                 {
2161                     (my $xobj = $object) =~ s,lo$,\$(OBJEXT),;
2162                     $compile_clean_files{$xobj} = MOSTLY_CLEAN;
2164                     $libtool_clean_directories{$directory} = 1;
2165                 }
2167                 push (@dep_list, require_build_directory ($directory));
2169                 # If we're generating dependencies, we also want
2170                 # to make sure that the appropriate subdir of the
2171                 # .deps directory is created.
2172                 push (@dep_list,
2173                       require_build_directory ($directory . '/$(DEPDIR)'))
2174                     if $use_dependencies;
2175             }
2177             &pretty_print_rule ($object . ':', "\t", @dep_list)
2178                 if scalar @dep_list > 0;
2179         }
2181         # Transform .o or $o file into .P file (for automatic
2182         # dependency code).
2183         if ($lang && $lang->autodep ne 'no')
2184         {
2185             my $depfile = $object;
2186             $depfile =~ s/\.([^.]*)$/.P$1/;
2187             $depfile =~ s/\$\(OBJEXT\)$/o/;
2188             $dep_files{dirname ($depfile) . '/$(DEPDIR)/'
2189                            . basename ($depfile)} = 1;
2190         }
2191     }
2193     return @result;
2196 # ($LINKER, $OBJVAR)
2197 # define_objects_from_sources ($VAR, $OBJVAR, $NODEFINE, $ONE_FILE,
2198 #                              $OBJ, $PARENT, $TOPPARENT)
2199 # ---------------------------------------------------------------------
2200 # Define an _OBJECTS variable for a _SOURCES variable (or subvariable)
2202 # Arguments are:
2203 #   $VAR is the name of the _SOURCES variable
2204 #   $OBJVAR is the name of the _OBJECTS variable if known (otherwise
2205 #     it will be generated and returned).
2206 #   $NODEFINE is a boolean: if true, $OBJVAR will not be defined (but
2207 #     work done to determine the linker will be).
2208 #   $ONE_FILE is the canonical (transformed) name of object to build
2209 #   $OBJ is the object extension (ie either `.o' or `.lo').
2210 #   $PARENT is the variable in which $VAR is used, or $VAR if not applicable.
2211 #   $TOPPARENT is the _SOURCES variable being processed.
2213 # Result is a pair ($LINKER, $OBJVAR):
2214 #    $LINKER is a boolean, true if a linker is needed to deal with the objects,
2215 #    $OBJVAR is the name of the variable defined to hold the objects.
2217 # %linkers_used, %vars_scanned, @substfroms and @substtos should be cleared
2218 # before use:
2219 #   %linkers_used variable will be set to contain the linkers desired.
2220 #   %vars_scanned will be used to check for recursive definitions.
2221 #   @substfroms and @substtos will be used to keep a stack of variable
2222 #   substitutions to be applied.
2224 sub define_objects_from_sources ($$$$$$$)
2226     my ($var, $objvar, $nodefine, $one_file, $obj, $parent, $topparent) = @_;
2228     if (defined $vars_scanned{$var})
2229     {
2230         macro_error ($var, "variable `$var' recursively defined");
2231         return "";
2232     }
2233     $vars_scanned{$var} = 1;
2235     my $needlinker = "";
2236     my @allresults = ();
2237     foreach my $cond (variable_conditions ($var))
2238     {
2239         my @result;
2240         foreach my $val (&variable_value_as_list ($var, $cond, $parent))
2241         {
2242             # If $val is a variable (i.e. ${foo} or $(bar), not a filename),
2243             # handle the sub variable recursively.
2244             if ($val =~ /^\$\{([^}]*)\}$/ || $val =~ /^\$\(([^)]*)\)$/)
2245             {
2246                 my $subvar = $1;
2248                 # If the user uses a losing variable name, just ignore it.
2249                 # This isn't ideal, but people have requested it.
2250                 next if ($subvar =~ /\@.*\@/);
2252                 # See if the variable is actually a substitution reference
2253                 my ($from, $to);
2254                 my @temp_list;
2255                 if ($subvar =~ /$SUBST_REF_PATTERN/o)
2256                 {
2257                     $subvar = $1;
2258                     $to = $3;
2259                     $from = quotemeta $2;
2260                 }
2261                 push @substfroms, $from;
2262                 push @substtos, $to;
2264                 my ($temp, $varname)
2265                     = define_objects_from_sources ($subvar, undef,
2266                                                    $nodefine, $one_file,
2267                                                    $obj, $var, $topparent);
2269                 push (@result, '$('. $varname . ')');
2270                 $needlinker ||= $temp;
2272                 pop @substfroms;
2273                 pop @substtos;
2274             }
2275             else # $var is a filename
2276             {
2277                 my $substnum=$#substfroms;
2278                 while ($substnum >= 0)
2279                 {
2280                     $val =~ s/$substfroms[$substnum]$/$substtos[$substnum]/
2281                         if defined $substfroms[$substnum];
2282                     $substnum -= 1;
2283                 }
2285                 my (@transformed) =
2286                       &handle_single_transform_list ($var, $topparent, $one_file, $obj, $val);
2287                 push (@result, @transformed);
2288                 $needlinker = "true" if @transformed;
2289             }
2290         }
2291         push (@allresults, [$cond, @result]);
2292     }
2293     # Find a name for the variable, unless imposed.
2294     $objvar = subobjname (@allresults) unless defined $objvar;
2295     # Define _OBJECTS conditionally
2296     unless ($nodefine)
2297     {
2298         foreach my $pair (@allresults)
2299         {
2300             my ($cond, @result) = @$pair;
2301             define_pretty_variable ($objvar, $cond, @result);
2302         }
2303     }
2305     delete $vars_scanned{$var};
2306     return ($needlinker, $objvar);
2310 # $VARNAME
2311 # subobjname (@DEFINITIONS)
2312 # -------------------------
2313 # Return a name for an object variable that with definitions @DEFINITIONS.
2314 # @DEFINITIONS is a list of pair [$COND, @OBJECTS].
2316 # If we already have an object variable containing @DEFINITIONS, reuse it.
2317 # This way, we avoid combinatorial explosion of the generated
2318 # variables.  Especially, in a Makefile such as:
2320 # | if FOO1
2321 # | A1=1
2322 # | endif
2323 # |
2324 # | if FOO2
2325 # | A2=2
2326 # | endif
2327 # |
2328 # | ...
2329 # |
2330 # | if FOON
2331 # | AN=N
2332 # | endif
2333 # |
2334 # | B=$(A1) $(A2) ... $(AN)
2335 # |
2336 # | c_SOURCES=$(B)
2337 # | d_SOURCES=$(B)
2339 # The generated c_OBJECTS and d_OBJECTS will share the same variable
2340 # definitions.
2342 # This setup can be the case of a testsuite containing lots (>100) of
2343 # small C programs, all testing the same set of source files.
2344 sub subobjname (@)
2346     my $key = '';
2347     foreach my $pair (@_)
2348     {
2349         my ($cond, @values) = @$pair;
2350         $key .= "($cond)@values";
2351     }
2353     return $subobjvar{$key} if exists $subobjvar{$key};
2355     my $num = 1 + keys (%subobjvar);
2356     my $name = "am__objects_${num}";
2357     $subobjvar{$key} = $name;
2358     return $name;
2362 # Handle SOURCE->OBJECT transform for one program or library.
2363 # Arguments are:
2364 #   canonical (transformed) name of object to build
2365 #   actual name of object to build
2366 #   object extension (ie either `.o' or `$o'.
2367 # Return result is name of linker variable that must be used.
2368 # Empty return means just use `LINK'.
2369 sub handle_source_transform
2371     # one_file is canonical name.  unxformed is given name.  obj is
2372     # object extension.
2373     my ($one_file, $unxformed, $obj) = @_;
2375     my ($linker) = '';
2377     if (variable_defined ($one_file . "_OBJECTS"))
2378     {
2379         macro_error ($one_file . '_OBJECTS',
2380                      $one_file . '_OBJECTS', 'should not be defined');
2381         # No point in continuing.
2382         return;
2383     }
2385     my %used_pfx = ();
2386     my $needlinker;
2387     %linkers_used = ();
2388     foreach my $prefix ('', 'EXTRA_', 'dist_', 'nodist_',
2389                         'dist_EXTRA_', 'nodist_EXTRA_')
2390     {
2391         my $var = $prefix . $one_file . "_SOURCES";
2392         next
2393           if !variable_defined ($var);
2395         # We are going to define _OBJECTS variables using the prefix.
2396         # Then we glom them all together.  So we can't use the null
2397         # prefix here as we need it later.
2398         my $xpfx = ($prefix eq '') ? 'am_' : $prefix;
2400         # Keep track of which prefixes we saw.
2401         $used_pfx{$xpfx} = 1
2402           unless $prefix =~ /EXTRA_/;
2404         push @sources, "\$($var)";
2405         push @dist_sources, "\$($var)"
2406           unless $prefix =~ /^nodist_/;
2408         @substfroms = ();
2409         @substtos = ();
2410         %vars_scanned = ();
2411         my ($temp, $objvar) =
2412             define_objects_from_sources ($var,
2413                                          $xpfx . $one_file . '_OBJECTS',
2414                                          $prefix =~ /EXTRA_/,
2415                                          $one_file, $obj, $var, $var);
2416         $needlinker ||= $temp;
2417     }
2418     if ($needlinker)
2419     {
2420         $linker ||= &resolve_linker (%linkers_used);
2421     }
2423     my @keys = sort keys %used_pfx;
2424     if (scalar @keys == 0)
2425     {
2426         &define_variable ($one_file . "_SOURCES", $unxformed . ".c");
2427         push (@sources, $unxformed . '.c');
2428         push (@dist_sources, $unxformed . '.c');
2430         %linkers_used = ();
2431         my (@result) =
2432           &handle_single_transform_list ($one_file . '_SOURCES',
2433                                          $one_file . '_SOURCES',
2434                                          $one_file, $obj,
2435                                          "$unxformed.c");
2436         $linker ||= &resolve_linker (%linkers_used);
2437         define_pretty_variable ($one_file . "_OBJECTS", '', @result)
2438     }
2439     else
2440     {
2441         grep ($_ = '$(' . $_ . $one_file . '_OBJECTS)', @keys);
2442         define_pretty_variable ($one_file . '_OBJECTS', '', @keys);
2443     }
2445     # If we want to use `LINK' we must make sure it is defined.
2446     if ($linker eq '')
2447     {
2448         $need_link = 1;
2449     }
2451     return $linker;
2455 # handle_lib_objects ($XNAME, $VAR)
2456 # ---------------------------------
2457 # Special-case @ALLOCA@ and @LIBOBJS@ in _LDADD or _LIBADD variables.
2458 # Also, generate _DEPENDENCIES variable if appropriate.
2459 # Arguments are:
2460 #   transformed name of object being built, or empty string if no object
2461 #   name of _LDADD/_LIBADD-type variable to examine
2462 # Returns 1 if LIBOBJS seen, 0 otherwise.
2463 sub handle_lib_objects
2465     my ($xname, $var) = @_;
2467     prog_error ("handle_lib_objects: $var undefined")
2468         if ! variable_defined ($var);
2470     my $ret = 0;
2471     foreach my $cond (variable_conditions_recursive ($var))
2472       {
2473         if (&handle_lib_objects_cond ($xname, $var, $cond))
2474           {
2475             $ret = 1;
2476           }
2477       }
2478     return $ret;
2481 # Subroutine of handle_lib_objects: handle a particular condition.
2482 sub handle_lib_objects_cond
2484     my ($xname, $var, $cond) = @_;
2486     # We recognize certain things that are commonly put in LIBADD or
2487     # LDADD.
2488     my @dep_list = ();
2490     my $seen_libobjs = 0;
2491     my $flagvar = 0;
2493     foreach my $lsearch (&variable_value_as_list_recursive ($var, $cond))
2494     {
2495         # Skip -lfoo and -Ldir; these are explicitly allowed.
2496         next if $lsearch =~ /^-[lL]/;
2497         if (! $flagvar && $lsearch =~ /^-/)
2498         {
2499             if ($var =~ /^(.*)LDADD$/)
2500             {
2501                 # Skip -dlopen and -dlpreopen; these are explicitly allowed.
2502                 next if $lsearch =~ /^-dl(pre)?open$/;
2503                 my $prefix = $1 || 'AM_';
2504                 macro_error ($var,
2505                              "linker flags such as `$lsearch' belong in `${prefix}LDFLAGS");
2506             }
2507             else
2508             {
2509                 $var =~ /^(.*)LIBADD$/;
2510                 # Only get this error once.
2511                 $flagvar = 1;
2512                 macro_error ($var,
2513                              "linker flags such as `$lsearch' belong in `${1}LDFLAGS");
2514             }
2515         }
2517         # Assume we have a file of some sort, and push it onto the
2518         # dependency list.  Autoconf substitutions are not pushed;
2519         # rarely is a new dependency substituted into (eg) foo_LDADD
2520         # -- but "bad things (eg -lX11) are routinely substituted.
2521         # Note that LIBOBJS and ALLOCA are exceptions to this rule,
2522         # and handled specially below.
2523         push (@dep_list, $lsearch)
2524             unless $lsearch =~ /^\@.*\@$/;
2526         # Automatically handle @LIBOBJS@ and @ALLOCA@.  Basically this
2527         # means adding entries to dep_files.
2528         if ($lsearch =~ /^\@(LT)?LIBOBJS\@$/)
2529         {
2530             my $lt = $1 ? $1 : '';
2531             my $myobjext = ($1 ? 'l' : '') . 'o';
2533             push (@dep_list, $lsearch);
2534             $seen_libobjs = 1;
2535             if (! keys %libsources
2536                 && ! variable_defined ($lt . 'LIBOBJS'))
2537             {
2538                 macro_error ($var,
2539                              "\@$lt" . "LIBOBJS\@ seen but never set in `$configure_ac'");
2540             }
2542             foreach my $iter (keys %libsources)
2543             {
2544                 if ($iter =~ /\.[cly]$/)
2545                 {
2546                     &saw_extension ($&);
2547                     &saw_extension ('.c');
2548                 }
2550                 if ($iter =~ /\.h$/)
2551                 {
2552                     require_file_with_macro ($var, FOREIGN, $iter);
2553                 }
2554                 elsif ($iter ne 'alloca.c')
2555                 {
2556                     my $rewrite = $iter;
2557                     $rewrite =~ s/\.c$/.P$myobjext/;
2558                     $dep_files{'$(DEPDIR)/' . $rewrite} = 1;
2559                     $rewrite = "^" . quotemeta ($iter) . "\$";
2560                     # Only require the file if it is not a built source.
2561                     if (! variable_defined ('BUILT_SOURCES')
2562                         || ! grep (/$rewrite/,
2563                                    &variable_value_as_list_recursive (
2564                                         'BUILT_SOURCES', 'all')))
2565                     {
2566                         require_file_with_macro ($var, FOREIGN, $iter);
2567                     }
2568                 }
2569             }
2570         }
2571         elsif ($lsearch =~ /^\@(LT)?ALLOCA\@$/)
2572         {
2573             my $lt = $1 ? $1 : '';
2574             my $myobjext = ($1 ? 'l' : '') . 'o';
2576             push (@dep_list, $lsearch);
2577             macro_error ($var,
2578                          "\@$lt" . "ALLOCA\@ seen but `AC_FUNC_ALLOCA' not in `$configure_ac'")
2579                 if ! defined $libsources{'alloca.c'};
2580             $dep_files{'$(DEPDIR)/alloca.P' . $myobjext} = 1;
2581             require_file_with_macro ($var, FOREIGN, 'alloca.c');
2582             &saw_extension ('c');
2583         }
2584     }
2586     if ($xname ne '')
2587     {
2588         if (conditional_ambiguous_p ($xname . '_DEPENDENCIES', $cond) ne '')
2589         {
2590             # Note that we've examined this.
2591             &examine_variable ($xname . '_DEPENDENCIES');
2592         }
2593         else
2594         {
2595             define_pretty_variable ($xname . '_DEPENDENCIES', $cond,
2596                                     @dep_list);
2597         }
2598     }
2600     return $seen_libobjs;
2603 # Canonicalize the input parameter
2604 sub canonicalize
2606     my ($string) = @_;
2607     $string =~ tr/A-Za-z0-9_\@/_/c;
2608     return $string;
2611 # Canonicalize a name, and check to make sure the non-canonical name
2612 # is never used.  Returns canonical name.  Arguments are name and a
2613 # list of suffixes to check for.
2614 sub check_canonical_spelling
2616     my ($name, @suffixes) = @_;
2618     my $xname = &canonicalize ($name);
2619     if ($xname ne $name)
2620     {
2621         foreach my $xt (@suffixes)
2622         {
2623             macro_error ("$name$xt",
2624                          "invalid variable `$name$xt'; should be `$xname$xt'")
2625                 if variable_defined ("$name$xt");
2626         }
2627     }
2629     return $xname;
2633 # handle_compile ()
2634 # -----------------
2635 # Set up the compile suite.
2636 sub handle_compile ()
2638     return
2639       unless $get_object_extension_was_run;
2641     # Boilerplate.
2642     my $default_includes = '';
2643     if (! defined $options{'nostdinc'})
2644       {
2645         $default_includes = ' -I. -I$(srcdir)';
2647         if (variable_defined ('CONFIG_HEADER'))
2648           {
2649             foreach my $hdr (split (' ', &variable_value ('CONFIG_HEADER')))
2650               {
2651                 $default_includes .= ' -I' . dirname ($hdr);
2652               }
2653           }
2654       }
2656     my (@mostly_rms, @dist_rms);
2657     foreach my $item (sort keys %compile_clean_files)
2658     {
2659         if ($compile_clean_files{$item} == MOSTLY_CLEAN)
2660         {
2661             push (@mostly_rms, "\t-rm -f $item");
2662         }
2663         elsif ($compile_clean_files{$item} == DIST_CLEAN)
2664         {
2665             push (@dist_rms, "\t-rm -f $item");
2666         }
2667         else
2668         {
2669             prog_error ("invalid entry in \%compile_clean_files");
2670         }
2671     }
2673     my ($coms, $vars, $rules) =
2674       &file_contents_internal (1, "$libdir/am/compile.am",
2675                                ('DEFAULT_INCLUDES' => $default_includes,
2676                                 'MOSTLYRMS' => join ("\n", @mostly_rms),
2677                                 'DISTRMS' => join ("\n", @dist_rms)));
2678     $output_vars .= $vars;
2679     $output_rules .= "$coms$rules";
2681     # Check for automatic de-ANSI-fication.
2682     if (defined $options{'ansi2knr'})
2683       {
2684         if (! $am_c_prototypes)
2685           {
2686             macro_error ('AUTOMAKE_OPTIONS',
2687                          "option `ansi2knr' in use but `AM_C_PROTOTYPES' not in `$configure_ac'");
2688             &keyed_aclocal_warning ('AM_C_PROTOTYPES');
2689             # Only give this error once.
2690             $am_c_prototypes = 1;
2691           }
2693         # topdir is where ansi2knr should be.
2694         if ($options{'ansi2knr'} eq 'ansi2knr')
2695           {
2696             # Only require ansi2knr files if they should appear in
2697             # this directory.
2698             require_file_with_macro ('AUTOMAKE_OPTIONS', FOREIGN,
2699                                      'ansi2knr.c', 'ansi2knr.1');
2701             # ansi2knr needs to be built before subdirs, so unshift it.
2702             unshift (@all, '$(ANSI2KNR)');
2703           }
2705         my $ansi2knr_dir = '';
2706         $ansi2knr_dir = dirname ($options{'ansi2knr'})
2707           if $options{'ansi2knr'} ne 'ansi2knr';
2709         $output_rules .= &file_contents ('ansi2knr',
2710                                          ('ANSI2KNR-DIR' => $ansi2knr_dir));
2712     }
2715 # handle_libtool ()
2716 # -----------------
2717 # Handle libtool rules.
2718 sub handle_libtool
2720     return unless $seen_libtool;
2722     # Libtool requires some files, but only at top level.
2723     require_conf_file ($seen_libtool, FOREIGN, @libtool_files)
2724         if $relative_dir eq '.';
2726     my @libtool_rms;
2727     foreach my $item (sort keys %libtool_clean_directories)
2728     {
2729         my $dir = ($item eq '.') ? '' : "$item/";
2730         # .libs is for Unix, _libs for DOS.
2731         push (@libtool_rms, "\t-rm -rf ${dir}.libs ${dir}_libs");
2732     }
2734     # Output the libtool compilation rules.
2735     $output_rules .= &file_contents ('libtool',
2736                                      ('LTRMS' => join ("\n", @libtool_rms)));
2739 # handle_programs ()
2740 # ------------------
2741 # Handle C programs.
2742 sub handle_programs
2744     my @proglist = &am_install_var ('progs', 'PROGRAMS',
2745                                     'bin', 'sbin', 'libexec', 'pkglib',
2746                                     'noinst', 'check');
2747     return if ! @proglist;
2749     my $seen_libobjs = 0;
2750     foreach my $one_file (@proglist)
2751     {
2752         my $obj = &get_object_extension ($one_file);
2754         # Canonicalize names and check for misspellings.
2755         my $xname = &check_canonical_spelling ($one_file, '_LDADD', '_LDFLAGS',
2756                                                '_SOURCES', '_OBJECTS',
2757                                                '_DEPENDENCIES');
2759         my $linker = &handle_source_transform ($xname, $one_file, $obj);
2761         my $xt = '';
2762         if (variable_defined ($xname . "_LDADD"))
2763         {
2764             if (&handle_lib_objects ($xname, $xname . '_LDADD'))
2765             {
2766                 $seen_libobjs = 1;
2767             }
2768             $xt = '_LDADD';
2769         }
2770         else
2771         {
2772             # User didn't define prog_LDADD override.  So do it.
2773             &define_variable ($xname . '_LDADD', '$(LDADD)');
2775             # This does a bit too much work.  But we need it to
2776             # generate _DEPENDENCIES when appropriate.
2777             if (variable_defined ('LDADD'))
2778             {
2779                 if (&handle_lib_objects ($xname, 'LDADD'))
2780                 {
2781                     $seen_libobjs = 1;
2782                 }
2783             }
2784             elsif (! variable_defined ($xname . '_DEPENDENCIES'))
2785             {
2786                 &define_variable ($xname . '_DEPENDENCIES', '');
2787             }
2788             $xt = '_SOURCES'
2789         }
2791         if (variable_defined ($xname . '_LIBADD'))
2792         {
2793             macro_error ($xname . '_LIBADD',
2794                          "use `" . $xname . "_LDADD', not `"
2795                          . $xname . "_LIBADD'");
2796         }
2798         if (! variable_defined ($xname . '_LDFLAGS'))
2799         {
2800             # Define the prog_LDFLAGS variable.
2801             &define_variable ($xname . '_LDFLAGS', '');
2802         }
2804         # Determine program to use for link.
2805         my $xlink;
2806         if (variable_defined ($xname . '_LINK'))
2807         {
2808             $xlink = $xname . '_LINK';
2809         }
2810         else
2811         {
2812             $xlink = $linker ? $linker : 'LINK';
2813         }
2815         # If the resulting program lies into a subdirectory,
2816         # make sure this directory will exist.
2817         my $dirstamp = require_build_directory_maybe ($one_file);
2819         # Don't add $(EXEEXT) if user already did.
2820         my $extension = ($one_file !~ /\$\(EXEEXT\)$/
2821                          ? "\$(EXEEXT)"
2822                          : '');
2824         $output_rules .= &file_contents ('program',
2825                                          ('PROGRAM'  => $one_file,
2826                                           'XPROGRAM' => $xname,
2827                                           'XLINK'    => $xlink,
2828                                           'DIRSTAMP' => $dirstamp,
2829                                           'EXEEXT'   => $extension));
2830     }
2832     if (variable_defined ('LDADD') && &handle_lib_objects ('', 'LDADD'))
2833     {
2834         $seen_libobjs = 1;
2835     }
2837     if ($seen_libobjs)
2838     {
2839         foreach my $one_file (@proglist)
2840         {
2841             my $xname = &canonicalize ($one_file);
2843             if (variable_defined ($xname . '_LDADD'))
2844             {
2845                 &check_libobjs_sources ($xname, $xname . '_LDADD');
2846             }
2847             elsif (variable_defined ('LDADD'))
2848             {
2849                 &check_libobjs_sources ($xname, 'LDADD');
2850             }
2851         }
2852     }
2856 # handle_libraries ()
2857 # -------------------
2858 # Handle libraries.
2859 sub handle_libraries
2861     my @liblist = &am_install_var ('libs', 'LIBRARIES',
2862                                    'lib', 'pkglib', 'noinst', 'check');
2863     return if ! @liblist;
2865     my @prefix = am_primary_prefixes ('LIBRARIES', 0, 'lib', 'pkglib',
2866                                       'noinst', 'check');
2867     if (! defined $configure_vars{'RANLIB'}
2868         && @prefix)
2869       {
2870         macro_error ($prefix[0] . '_LIBRARIES',
2871                      "library used but `RANLIB' not defined in `$configure_ac'");
2872         # Only get this error once.  If this is ever printed, we have
2873         # a bug.
2874         $configure_vars{'RANLIB'} = 'BUG';
2875       }
2877     my $seen_libobjs = 0;
2878     foreach my $onelib (@liblist)
2879     {
2880         # Check that the library fits the standard naming convention.
2881         if (basename ($onelib) !~ /^lib.*\.a/)
2882         {
2883             # FIXME should put line number here.  That means mapping
2884             # from library name back to variable name.
2885             &am_error ("`$onelib' is not a standard library name");
2886         }
2888         my $obj = &get_object_extension ($onelib);
2890         # Canonicalize names and check for misspellings.
2891         my $xlib = &check_canonical_spelling ($onelib, '_LIBADD', '_SOURCES',
2892                                               '_OBJECTS', '_DEPENDENCIES',
2893                                               '_AR');
2895         if (! variable_defined ($xlib . '_AR'))
2896         {
2897             &define_variable ($xlib . '_AR', '$(AR) cru');
2898         }
2900         if (variable_defined ($xlib . '_LIBADD'))
2901         {
2902             if (&handle_lib_objects ($xlib, $xlib . '_LIBADD'))
2903             {
2904                 $seen_libobjs = 1;
2905             }
2906         }
2907         else
2908         {
2909             # Generate support for conditional object inclusion in
2910             # libraries.
2911             &define_variable ($xlib . "_LIBADD", '');
2912         }
2914         if (variable_defined ($xlib . '_LDADD'))
2915         {
2916             macro_error ($xlib . '_LDADD',
2917                          "use `" . $xlib . "_LIBADD', not `"
2918                          . $xlib . "_LDADD'");
2919         }
2921         # Make sure we at look at this.
2922         &examine_variable ($xlib . '_DEPENDENCIES');
2924         &handle_source_transform ($xlib, $onelib, $obj);
2926         # If the resulting library lies into a subdirectory,
2927         # make sure this directory will exist.
2928         my $dirstamp = require_build_directory_maybe ($onelib);
2930         $output_rules .= &file_contents ('library',
2931                                          ('LIBRARY'  => $onelib,
2932                                           'XLIBRARY' => $xlib,
2933                                           'DIRSTAMP' => $dirstamp));
2934     }
2936     if ($seen_libobjs)
2937     {
2938         foreach my $onelib (@liblist)
2939         {
2940             my $xlib = &canonicalize ($onelib);
2941             if (variable_defined ($xlib . '_LIBADD'))
2942             {
2943                 &check_libobjs_sources ($xlib, $xlib . '_LIBADD');
2944             }
2945         }
2946     }
2950 # handle_ltlibraries ()
2951 # ---------------------
2952 # Handle shared libraries.
2953 sub handle_ltlibraries
2955     my @liblist = &am_install_var ('ltlib', 'LTLIBRARIES',
2956                                    'noinst', 'lib', 'pkglib', 'check');
2957     return if ! @liblist;
2959     my %instdirs;
2960     my @prefix = am_primary_prefixes ('LTLIBRARIES', 0, 'lib', 'pkglib',
2961                                       'noinst', 'check');
2963     foreach my $key (@prefix)
2964       {
2965         if (!$seen_libtool)
2966           {
2967             macro_error ($key . '_LTLIBRARIES',
2968                          "library used but `LIBTOOL' not defined in `$configure_ac'");
2969             # Only get this error once.  If this is ever printed,
2970             # we have a bug.
2971             $configure_vars{'LIBTOOL'} = 'BUG';
2972             $seen_libtool = $var_location{$key . '_LTLIBRARIES'};
2973           }
2975         # Get the installation directory of each library.
2976         (my $dir = $key) =~ s/^nobase_//;
2977         for (variable_value_as_list_recursive ($key . '_LTLIBRARIES', 'all'))
2978           {
2979             if ($instdirs{$_})
2980               {
2981                 am_error ("`$_' is already going to be installed in `$instdirs{$_}'");
2982               }
2983             else
2984               {
2985                 $instdirs{$_} = $dir;
2986               }
2987           }
2988       }
2990     my $seen_libobjs = 0;
2991     foreach my $onelib (@liblist)
2992     {
2993         my $obj = &get_object_extension ($onelib);
2995         # Canonicalize names and check for misspellings.
2996         my $xlib = &check_canonical_spelling ($onelib, '_LIBADD', '_LDFLAGS',
2997                                               '_SOURCES', '_OBJECTS',
2998                                               '_DEPENDENCIES');
3000         if (! variable_defined ($xlib . '_LDFLAGS'))
3001         {
3002             # Define the lib_LDFLAGS variable.
3003             &define_variable ($xlib . '_LDFLAGS', '');
3004         }
3006         # Check that the library fits the standard naming convention.
3007         my $libname_rx = "^lib.*\.la";
3008         if ((variable_defined ($xlib . '_LDFLAGS')
3009              && grep (/-module/, &variable_value_as_list_recursive (
3010                                         $xlib . '_LDFLAGS', 'all')))
3011             || (variable_defined ('LDFLAGS')
3012                 && grep (/-module/, &variable_value_as_list_recursive (
3013                                         'LDFLAGS', 'all'))))
3014         {
3015                 # Relax name checking for libtool modules.
3016                 $libname_rx = "\.la";
3017         }
3018         if (basename ($onelib) !~ /$libname_rx$/)
3019         {
3020             # FIXME this should only be a warning for foreign packages
3021             # FIXME should put line number here.  That means mapping
3022             # from library name back to variable name.
3023             &am_error ("`$onelib' is not a standard libtool library name");
3024         }
3026         if (variable_defined ($xlib . '_LIBADD'))
3027         {
3028             if (&handle_lib_objects ($xlib, $xlib . '_LIBADD'))
3029             {
3030                 $seen_libobjs = 1;
3031             }
3032         }
3033         else
3034         {
3035             # Generate support for conditional object inclusion in
3036             # libraries.
3037             &define_variable ($xlib . "_LIBADD", '');
3038         }
3040         if (variable_defined ($xlib . '_LDADD'))
3041         {
3042             macro_error ($xlib . '_LDADD',
3043                          "use `" . $xlib . "_LIBADD', not `"
3044                          . $xlib . "_LDADD'");
3045         }
3047         # Make sure we at look at this.
3048         &examine_variable ($xlib . '_DEPENDENCIES');
3050         my $linker = &handle_source_transform ($xlib, $onelib, $obj);
3052         # Determine program to use for link.
3053         my $xlink;
3054         if (variable_defined ($xlib . '_LINK'))
3055         {
3056             $xlink = $xlib . '_LINK';
3057         }
3058         else
3059         {
3060             $xlink = $linker ? $linker : 'LINK';
3061         }
3063         my $rpath;
3064         if ($instdirs{$onelib} eq 'EXTRA'
3065             || $instdirs{$onelib} eq 'noinst'
3066             || $instdirs{$onelib} eq 'check')
3067         {
3068             # It's an EXTRA_ library, so we can't specify -rpath,
3069             # because we don't know where the library will end up.
3070             # The user probably knows, but generally speaking automake
3071             # doesn't -- and in fact configure could decide
3072             # dynamically between two different locations.
3073             $rpath = '';
3074         }
3075         else
3076         {
3077             $rpath = ('-rpath $(' . $instdirs{$onelib} . 'dir)');
3078         }
3080         # If the resulting library lies into a subdirectory,
3081         # make sure this directory will exist.
3082         my $dirstamp = require_build_directory_maybe ($onelib);
3084         $output_rules .= &file_contents ('ltlibrary',
3085                                          ('LTLIBRARY'  => $onelib,
3086                                           'XLTLIBRARY' => $xlib,
3087                                           'RPATH'      => $rpath,
3088                                           'XLINK'      => $xlink,
3089                                           'DIRSTAMP'   => $dirstamp));
3090     }
3092     if ($seen_libobjs)
3093     {
3094         foreach my $onelib (@liblist)
3095         {
3096             my $xlib = &canonicalize ($onelib);
3097             if (variable_defined ($xlib . '_LIBADD'))
3098             {
3099                 &check_libobjs_sources ($xlib, $xlib . '_LIBADD');
3100             }
3101         }
3102     }
3105 # See if any _SOURCES variable were misspelled.  Also, make sure that
3106 # EXTRA_ variables don't contain configure substitutions.
3107 sub check_typos ()
3109     # It is ok if the user sets this particular variable.
3110     &examine_variable ('AM_LDFLAGS');
3112     foreach my $varname (keys %var_value)
3113     {
3114         foreach my $primary ('_SOURCES', '_LIBADD', '_LDADD', '_LDFLAGS',
3115                              '_DEPENDENCIES')
3116         {
3117             macro_error ($varname,
3118                          "invalid unused variable name: `$varname'")
3119                 # Note that a configure variable is always legitimate.
3120                 # It is natural to name such variables after the
3121                 # primary, so we explicitly allow it.
3122                 if $varname =~ /$primary$/ && ! $content_seen{$varname}
3123                    && ! exists $configure_vars{$varname};
3124         }
3125     }
3129 # Handle scripts.
3130 sub handle_scripts
3132     # NOTE we no longer automatically clean SCRIPTS, because it is
3133     # useful to sometimes distribute scripts verbatim.  This happens
3134     # eg in Automake itself.
3135     &am_install_var ('-candist', 'scripts', 'SCRIPTS',
3136                      'bin', 'sbin', 'libexec', 'pkgdata',
3137                      'noinst', 'check');
3141 # ($OUTFILE, $VFILE, @CLEAN_FILES)
3142 # &scan_texinfo_file ($FILENAME)
3143 # ------------------------------
3144 # $OUTFILE is the name of the info file produced by $FILENAME.
3145 # $VFILE is the name of the version.texi file used (empty if none).
3146 # @CLEAN_FILES is the list of by products (indexes etc.)
3147 sub scan_texinfo_file
3149     my ($filename) = @_;
3151     # These are always created, no matter whether indexes are used or not.
3152     # (Actually tmp is only created if an @macro is used and a certain e-TeX
3153     # feature is not available.)
3154     my @clean_suffixes = qw(aux dvi log ps toc tmp
3155                             cp fn ky vr tp pg); # grep new.*index texinfo.tex
3157     # There are predefined indexes which don't follow the regular rules.
3158     my %predefined_index = qw(c cps
3159                               f fns
3160                               k kys
3161                               v vrs
3162                               t tps
3163                               p pgs);
3165     # There are commands which include a hidden index command.
3166     my %hidden_index = (tp => 'tps');
3167     $hidden_index{$_} = 'fns' foreach qw(fn un typefn typefun max spec
3168                                          op typeop method typemethod);
3169     $hidden_index{$_} = 'vrs' foreach qw(vr var typevr typevar opt cv
3170                                          ivar typeivar);
3172     # Indexes stored into another one.  In this case, the *.??s file
3173     # is not created.
3174     my @syncodeindexes = ();
3176     my $texi = new Automake::XFile "< $filename";
3177     verbose "reading $filename";
3179     my ($outfile, $vfile);
3180     while ($_ = $texi->getline)
3181     {
3182       if (/^\@setfilename +(\S+)/)
3183       {
3184         $outfile = $1;
3185         if ($outfile =~ /\.(.+)$/ && $1 ne 'info')
3186           {
3187             file_error ("$filename:$.",
3188                         "output `$outfile' has unrecognized extension");
3189             return;
3190           }
3191       }
3192       # A "version.texi" file is actually any file whose name
3193       # matches "vers*.texi".
3194       elsif (/^\@include\s+(vers[^.]*\.texi)\s*$/)
3195       {
3196         $vfile = $1;
3197       }
3199       # Try to find what are the indexes which are used.
3201       # Creating a new category of index.
3202       elsif (/^\@def(code)?index (\w+)/)
3203       {
3204         push @clean_suffixes, $2;
3205       }
3207       # Storing in a predefined index.
3208       elsif (/^\@([cfkvtp])index /)
3209       {
3210         push @clean_suffixes, $predefined_index{$1};
3211       }
3212       elsif (/^\@def(\w+) /)
3213       {
3214         push @clean_suffixes, $hidden_index{$1}
3215           if defined $hidden_index{$1};
3216       }
3218       # Merging an index into an another.
3219       elsif (/^\@syn(code)?index (\w+) (\w+)/)
3220       {
3221         push @syncodeindexes, "$2s";
3222         push @clean_suffixes, "$3s";
3223       }
3225     }
3227     if ($outfile eq '')
3228       {
3229         &am_error ("`$filename' missing \@setfilename");
3230         return;
3231       }
3233     my $infobase = basename ($filename);
3234     $infobase =~ s/\.te?xi(nfo)?$//;
3235     my %clean_files = map { +"$infobase.$_" => 1 } @clean_suffixes;
3236     grep { delete $clean_files{"$infobase.$_"} } @syncodeindexes;
3237     return ($outfile, $vfile, (sort keys %clean_files));
3241 # ($DO-SOMETHING, $TEXICLEANS)
3242 # handle_texinfo_helper ()
3243 # ------------------------
3244 # Handle all Texinfo source; helper for handle_texinfo
3245 sub handle_texinfo_helper
3247     macro_error ('TEXINFOS',
3248                  "`TEXINFOS' is an anachronism; use `info_TEXINFOS'")
3249         if variable_defined ('TEXINFOS');
3250     return (0, '') if (! variable_defined ('info_TEXINFOS')
3251                        && ! variable_defined ('html_TEXINFOS'));
3253     if (variable_defined ('html_TEXINFOS'))
3254     {
3255         macro_error ('html_TEXINFOS',
3256                      "HTML generation not yet supported");
3257         return (0, '');
3258     }
3260     my @texis = &variable_value_as_list_recursive ('info_TEXINFOS', 'all');
3262     my (@info_deps_list, @dvis_list, @texi_deps);
3263     my %versions;
3264     my $done = 0;
3265     my @texi_cleans;
3266     my $canonical;
3268     my %texi_suffixes;
3269     foreach my $info_cursor (@texis)
3270     {
3271         my $infobase = $info_cursor;
3272         $infobase =~ s/\.(txi|texinfo|texi)$//;
3274         if ($infobase eq $info_cursor)
3275         {
3276             # FIXME: report line number.
3277             &am_error ("texinfo file `$info_cursor' has unrecognized extension");
3278             next;
3279         }
3280         $texi_suffixes{$1} = 1;
3282         # If 'version.texi' is referenced by input file, then include
3283         # automatic versioning capability.
3284         my ($out_file, $vtexi, @clean_files) =
3285           &scan_texinfo_file ("$relative_dir/$info_cursor")
3286             or next;
3287         push (@texi_cleans, @clean_files);
3289         if ($vtexi)
3290         {
3291             &am_error ("`$vtexi', included in `$info_cursor', also included in `$versions{$vtexi}'")
3292                 if (defined $versions{$vtexi});
3293             $versions{$vtexi} = $info_cursor;
3295             # We number the stamp-vti files.  This is doable since the
3296             # actual names don't matter much.  We only number starting
3297             # with the second one, so that the common case looks nice.
3298             my $vti = ($done ? $done : 'vti');
3299             ++$done;
3301             # This is ugly, but it is our historical practice.
3302             if ($config_aux_dir_set_in_configure_in)
3303             {
3304                 require_conf_file_with_macro ('info_TEXINFOS', FOREIGN,
3305                                               'mdate-sh');
3306             }
3307             else
3308             {
3309                 require_file_with_macro ('info_TEXINFOS', FOREIGN,
3310                                          'mdate-sh');
3311             }
3313             my $conf_dir;
3314             if ($config_aux_dir_set_in_configure_in)
3315             {
3316                 $conf_dir = $config_aux_dir;
3317                 $conf_dir .= '/' unless $conf_dir =~ /\/$/;
3318             }
3319             else
3320             {
3321                 $conf_dir = '$(srcdir)/';
3322             }
3323             $output_rules .= &file_contents ('texi-vers',
3324                                              ('TEXI'  => $info_cursor,
3325                                               'VTI'   => $vti,
3326                                               'VTEXI' => $vtexi,
3327                                               'MDDIR' => $conf_dir));
3328         }
3330         # If user specified file_TEXINFOS, then use that as explicit
3331         # dependency list.
3332         @texi_deps = ();
3333         push (@texi_deps, $info_cursor);
3334         # Prefix with $(srcdir) because some version of make won't
3335         # work if the target has it and the dependency doesn't.
3336         push (@texi_deps, '$(srcdir)/' . $vtexi) if $vtexi;
3338         my $canonical = &canonicalize ($infobase);
3339         if (variable_defined ($canonical . "_TEXINFOS"))
3340         {
3341             push (@texi_deps, '$(' . $canonical . '_TEXINFOS)');
3342             &push_dist_common ('$(' . $canonical . '_TEXINFOS)');
3343         }
3345         $output_rules .= ("\n" . $out_file . ": "
3346                           . "@texi_deps"
3347                           . "\n" . $infobase . ".dvi: "
3348                           . "@texi_deps"
3349                           . "\n");
3351         push (@info_deps_list, $out_file);
3352         push (@dvis_list, $infobase . '.dvi');
3353     }
3355     # Handle location of texinfo.tex.
3356     my $need_texi_file = 0;
3357     my $texinfodir;
3358     if ($cygnus_mode)
3359     {
3360         $texinfodir = '$(top_srcdir)/../texinfo';
3361         &define_variable ('TEXINFO_TEX', "$texinfodir/texinfo.tex");
3362     }
3363     elsif ($config_aux_dir_set_in_configure_in)
3364     {
3365         $texinfodir = $config_aux_dir;
3366         &define_variable ('TEXINFO_TEX', "$texinfodir/texinfo.tex");
3367         $need_texi_file = 2; # so that we require_conf_file later
3368     }
3369     elsif (variable_defined ('TEXINFO_TEX'))
3370     {
3371         # The user defined TEXINFO_TEX so assume he knows what he is
3372         # doing.
3373         $texinfodir = ('$(srcdir)/'
3374                        . dirname (&variable_value ('TEXINFO_TEX')));
3375     }
3376     else
3377     {
3378         $texinfodir = '$(srcdir)';
3379         $need_texi_file = 1;
3380     }
3382     foreach my $txsfx (sort keys %texi_suffixes)
3383     {
3384         $output_rules .= &file_contents ('texibuild',
3385                                          ('TEXINFODIR' => $texinfodir,
3386                                           'SUFFIX'     => $txsfx));
3387     }
3389     # The return value.
3390     my $texiclean = &pretty_print_internal ("", "\t  ", @texi_cleans);
3392     push (@dist_targets, 'dist-info');
3394     if (! defined $options{'no-installinfo'})
3395     {
3396         # Make sure documentation is made and installed first.  Use
3397         # $(INFO_DEPS), not 'info', because otherwise recursive makes
3398         # get run twice during "make all".
3399         unshift (@all, '$(INFO_DEPS)');
3400     }
3402     &define_variable ("INFO_DEPS", "@info_deps_list");
3403     &define_variable ("DVIS", "@dvis_list");
3404     # This next isn't strictly needed now -- the places that look here
3405     # could easily be changed to look in info_TEXINFOS.  But this is
3406     # probably better, in case noinst_TEXINFOS is ever supported.
3407     &define_variable ("TEXINFOS", &variable_value ('info_TEXINFOS'));
3409     # Do some error checking.  Note that this file is not required
3410     # when in Cygnus mode; instead we defined TEXINFO_TEX explicitly
3411     # up above.
3412     if ($need_texi_file && ! defined $options{'no-texinfo.tex'})
3413     {
3414         if ($need_texi_file > 1)
3415         {
3416             require_conf_file_with_macro ('info_TEXINFOS', FOREIGN,
3417                                           'texinfo.tex');
3418         }
3419         else
3420         {
3421             require_file_with_macro ('info_TEXINFOS', FOREIGN, 'texinfo.tex');
3422         }
3423     }
3425     return (1, $texiclean);
3428 # handle_texinfo ()
3429 # -----------------
3430 # Handle all Texinfo source.
3431 sub handle_texinfo
3433     my ($do_something, $texiclean) = handle_texinfo_helper ();
3434     $output_rules .=  &file_contents ('texinfos',
3435                                       ('TEXICLEAN' => $texiclean,
3436                                        'LOCAL-TEXIS' => $do_something));
3439 # Handle any man pages.
3440 sub handle_man_pages
3442     macro_error ('MANS', "`MANS' is an anachronism; use `man_MANS'")
3443         if variable_defined ('MANS');
3445     # Find all the sections in use.  We do this by first looking for
3446     # "standard" sections, and then looking for any additional
3447     # sections used in man_MANS.
3448     my (%sections, %vlist);
3449     # We handle nodist_ for uniformity.  man pages aren't distributed
3450     # by default so it isn't actually very important.
3451     foreach my $pfx ('', 'dist_', 'nodist_')
3452     {
3453         # Add more sections as needed.
3454         foreach my $section ('0'..'9', 'n', 'l')
3455         {
3456             if (variable_defined ($pfx . 'man' . $section . '_MANS'))
3457             {
3458                 $sections{$section} = 1;
3459                 $vlist{'$(' . $pfx . 'man' . $section . '_MANS)'} = 1;
3461                 &push_dist_common ('$(' . $pfx . 'man' . $section . '_MANS)')
3462                     if $pfx eq 'dist_';
3463             }
3464         }
3466         if (variable_defined ($pfx . 'man_MANS'))
3467         {
3468             $vlist{'$(' . $pfx . 'man_MANS)'} = 1;
3469             foreach (&variable_value_as_list_recursive ($pfx . 'man_MANS', 'all'))
3470             {
3471                 # A page like `foo.1c' goes into man1dir.
3472                 if (/\.([0-9a-z])([a-z]*)$/)
3473                 {
3474                     $sections{$1} = 1;
3475                 }
3476             }
3478             &push_dist_common ('$(' . $pfx . 'man_MANS)')
3479                 if $pfx eq 'dist_';
3480         }
3481     }
3483     return unless %sections;
3485     # Now for each section, generate an install and unintall rule.
3486     # Sort sections so output is deterministic.
3487     foreach my $section (sort keys %sections)
3488     {
3489         $output_rules .= &file_contents ('mans', ('SECTION' => $section));
3490     }
3492     my @mans = sort keys %vlist;
3493     $output_vars .= file_contents ('mans-vars',
3494                                    ('MANS' => "@mans"));
3496     if (! defined $options{'no-installman'})
3497     {
3498         push (@all, '$(MANS)');
3499     }
3502 # Handle DATA variables.
3503 sub handle_data
3505     &am_install_var ('-noextra', '-candist', 'data', 'DATA',
3506                      'data', 'sysconf', 'sharedstate', 'localstate',
3507                      'pkgdata', 'noinst', 'check');
3510 # Handle TAGS.
3511 sub handle_tags
3513     my @tag_deps = ();
3514     if (variable_defined ('SUBDIRS'))
3515     {
3516         $output_rules .= ("tags-recursive:\n"
3517                           . "\tlist=\'\$(SUBDIRS)\'; for subdir in \$\$list; do \\\n"
3518                           # Never fail here if a subdir fails; it
3519                           # isn't important.
3520                           . "\t  test \"\$\$subdir\" = . || (cd \$\$subdir"
3521                           . " && \$(MAKE) \$(AM_MAKEFLAGS) tags); \\\n"
3522                           . "\tdone\n");
3523         push (@tag_deps, 'tags-recursive');
3524         &depend ('.PHONY', 'tags-recursive');
3525     }
3527     if (&saw_sources_p (1)
3528         || variable_defined ('ETAGS_ARGS')
3529         || @tag_deps)
3530     {
3531         my @config;
3532         foreach my $spec (@config_headers)
3533         {
3534             my ($out, @ins) = split_config_file_spec ($spec);
3535             foreach my $in (@ins)
3536               {
3537                 # If the config header source is in this directory,
3538                 # require it.
3539                 push @config, basename ($in)
3540                   if $relative_dir eq dirname ($in);
3541               }
3542         }
3543         $output_rules .= &file_contents ('tags',
3544                                          ('CONFIG' => "@config",
3545                                           'DIRS'   => "@tag_deps"));
3546         &examine_variable ('TAGS_DEPENDENCIES');
3547     }
3548     elsif (variable_defined ('TAGS_DEPENDENCIES'))
3549     {
3550         macro_error ('TAGS_DEPENDENCIES',
3551                      "doesn't make sense to define `TAGS_DEPENDENCIES' without sources or `ETAGS_ARGS'");
3552     }
3553     else
3554     {
3555         # Every Makefile must define some sort of TAGS rule.
3556         # Otherwise, it would be possible for a top-level "make TAGS"
3557         # to fail because some subdirectory failed.
3558         $output_rules .= "tags: TAGS\nTAGS:\n\n";
3559     }
3562 # Handle multilib support.
3563 sub handle_multilib
3565     if ($seen_multilib && $relative_dir eq '.')
3566     {
3567         $output_rules .= &file_contents ('multilib');
3568     }
3572 # $BOOLEAN
3573 # &for_dist_common ($A, $B)
3574 # -------------------------
3575 # Subroutine for &handle_dist: sort files to dist.
3577 # We put README first because it then becomes easier to make a
3578 # Usenet-compliant shar file (in these, README must be first).
3580 # FIXME: do more ordering of files here.
3581 sub for_dist_common
3583     return 0
3584         if $a eq $b;
3585     return -1
3586         if $a eq 'README';
3587     return 1
3588         if $b eq 'README';
3589     return $a cmp $b;
3593 # handle_dist ($MAKEFILE)
3594 # -----------------------
3595 # Handle 'dist' target.
3596 sub handle_dist
3598     my ($makefile) = @_;
3600     # `make dist' isn't used in a Cygnus-style tree.
3601     # Omit the rules so that people don't try to use them.
3602     return if $cygnus_mode;
3604     # Look for common files that should be included in distribution.
3605     # If the aux dir is set, and it does not have a Makefile.am, then
3606     # we check for these files there as well.
3607     my $check_aux = 0;
3608     my $auxdir = '';
3609     if ($relative_dir eq '.'
3610         && $config_aux_dir_set_in_configure_in)
3611     {
3612         ($auxdir = $config_aux_dir) =~ s,^\$\(top_srcdir\)/,,;
3613         if (! &is_make_dir ($auxdir))
3614         {
3615             $check_aux = 1;
3616         }
3617     }
3618     foreach my $cfile (@common_files)
3619     {
3620         if (-f ($relative_dir . "/" . $cfile)
3621             # The file might be absent, but if it can be built it's ok.
3622             || exists $targets{$cfile})
3623         {
3624             &push_dist_common ($cfile);
3625         }
3627         # Don't use `elsif' here because a file might meaningfully
3628         # appear in both directories.
3629         if ($check_aux && -f ($auxdir . '/' . $cfile))
3630         {
3631             &push_dist_common ($auxdir . '/' . $cfile);
3632         }
3633     }
3635     # We might copy elements from $configure_dist_common to
3636     # %dist_common if we think we need to.  If the file appears in our
3637     # directory, we would have discovered it already, so we don't
3638     # check that.  But if the file is in a subdir without a Makefile,
3639     # we want to distribute it here if we are doing `.'.  Ugly!
3640     if ($relative_dir eq '.')
3641     {
3642        foreach my $file (split (' ' , $configure_dist_common))
3643        {
3644            push_dist_common ($file)
3645              unless is_make_dir (dirname ($file));
3646        }
3647     }
3651     # Files to distributed.  Don't use &variable_value_as_list_recursive
3652     # as it recursively expands `$(dist_pkgdata_DATA)' etc.
3653     check_variable_defined_unconditionally ('DIST_COMMON');
3654     my @dist_common = split (' ', variable_value ('DIST_COMMON', 'TRUE'));
3655     @dist_common = uniq (sort for_dist_common (@dist_common));
3656     pretty_print ('DIST_COMMON = ', "\t", @dist_common);
3658     # Now that we've processed DIST_COMMON, disallow further attempts
3659     # to set it.
3660     $handle_dist_run = 1;
3662     # Scan EXTRA_DIST to see if we need to distribute anything from a
3663     # subdir.  If so, add it to the list.  I didn't want to do this
3664     # originally, but there were so many requests that I finally
3665     # relented.
3666     if (variable_defined ('EXTRA_DIST'))
3667     {
3668         # FIXME: This should be fixed to work with conditionals.  That
3669         # will require only making the entries in %dist_dirs under the
3670         # appropriate condition.  This is meaningful if the nature of
3671         # the distribution should depend upon the configure options
3672         # used.
3673         foreach (&variable_value_as_list_recursive ('EXTRA_DIST', ''))
3674         {
3675             next if /^\@.*\@$/;
3676             next unless s,/+[^/]+$,,;
3677             $dist_dirs{$_} = 1
3678                 unless $_ eq '.';
3679         }
3680     }
3682     # We have to check DIST_COMMON for extra directories in case the
3683     # user put a source used in AC_OUTPUT into a subdir.
3684     foreach (&variable_value_as_list_recursive ('DIST_COMMON', 'all'))
3685     {
3686         next if /^\@.*\@$/;
3687         next unless s,/+[^/]+$,,;
3688         $dist_dirs{$_} = 1
3689             unless $_ eq '.';
3690     }
3692     # Rule to check whether a distribution is viable.
3693     my %transform = ('DISTCHECK-HOOK' => &target_defined ('distcheck-hook'),
3694                      'GETTEXT'        => $seen_gettext);
3696     # Prepend $(distdir) to each directory given.
3697     my %rewritten = map { '$(distdir)/' . "$_" => 1 } keys %dist_dirs;
3698     $transform{'DISTDIRS'} = join (' ', sort keys %rewritten);
3700     # If we have SUBDIRS, create all dist subdirectories and do
3701     # recursive build.
3702     if (variable_defined ('SUBDIRS'))
3703     {
3704         # If SUBDIRS is conditionally defined, then set DIST_SUBDIRS
3705         # to all possible directories, and use it.  If DIST_SUBDIRS is
3706         # defined, just use it.
3707         my $dist_subdir_name;
3708         # Note that we check DIST_SUBDIRS first on purpose.  At least
3709         # one project uses so many conditional subdirectories that
3710         # calling variable_conditionally_defined on SUBDIRS will cause
3711         # automake to grow to 150Mb.  Sigh.
3712         if (variable_defined ('DIST_SUBDIRS')
3713             || variable_conditionally_defined ('SUBDIRS'))
3714         {
3715             $dist_subdir_name = 'DIST_SUBDIRS';
3716             if (! variable_defined ('DIST_SUBDIRS'))
3717             {
3718                 define_pretty_variable
3719                   ('DIST_SUBDIRS', '',
3720                    uniq (&variable_value_as_list_recursive ('SUBDIRS', 'all')));
3721             }
3722         }
3723         else
3724         {
3725             $dist_subdir_name = 'SUBDIRS';
3726             # We always define this because that is what `distclean'
3727             # wants.
3728             define_pretty_variable ('DIST_SUBDIRS', '', '$(SUBDIRS)');
3729         }
3731         $transform{'DIST_SUBDIR_NAME'} = $dist_subdir_name;
3732     }
3734     # If the target `dist-hook' exists, make sure it is run.  This
3735     # allows users to do random weird things to the distribution
3736     # before it is packaged up.
3737     push (@dist_targets, 'dist-hook')
3738       if &target_defined ('dist-hook');
3739     $transform{'DIST-TARGETS'} = join(' ', @dist_targets);
3741     # Defining $(DISTDIR).
3742     $transform{'DISTDIR'} = !variable_defined('distdir');
3743     $transform{'TOP_DISTDIR'} = backname ($relative_dir);
3745     $output_rules .= &file_contents ('distdir', %transform);
3749 # Handle subdirectories.
3750 sub handle_subdirs
3752     return
3753       unless variable_defined ('SUBDIRS');
3755     # Make sure each directory mentioned in SUBDIRS actually exists.
3756     foreach my $dir (&variable_value_as_list_recursive ('SUBDIRS', 'all'))
3757     {
3758         # Skip directories substituted by configure.
3759         next if $dir =~ /^\@.*\@$/;
3761         if (! -d $am_relative_dir . '/' . $dir)
3762         {
3763             macro_error ('SUBDIRS',
3764                          "required directory $am_relative_dir/$dir does not exist");
3765             next;
3766         }
3768         macro_error ('SUBDIRS', "directory should not contain `/'")
3769             if $dir =~ /\//;
3770     }
3772     $output_rules .= &file_contents ('subdirs');
3773     variable_pretty_output ('RECURSIVE_TARGETS', 'TRUE');
3777 # ($REGEN, @DEPENDENCIES)
3778 # &scan_aclocal_m4
3779 # ----------------
3780 # If aclocal.m4 creation is automated, return the list of its dependencies.
3781 sub scan_aclocal_m4
3783     my $regen_aclocal = 0;
3785     return (0, ())
3786       unless $relative_dir eq '.';
3788     &examine_variable ('CONFIG_STATUS_DEPENDENCIES');
3789     &examine_variable ('CONFIGURE_DEPENDENCIES');
3791     if (-f 'aclocal.m4')
3792     {
3793         &define_variable ("ACLOCAL_M4", '$(top_srcdir)/aclocal.m4');
3794         &push_dist_common ('aclocal.m4');
3796         my $aclocal = new Automake::XFile "< aclocal.m4";
3797         my $line = $aclocal->getline;
3798         $regen_aclocal = $line =~ 'generated automatically by aclocal';
3799     }
3801     my @ac_deps = ();
3803     if (-f 'acinclude.m4')
3804     {
3805         $regen_aclocal = 1;
3806         push @ac_deps, 'acinclude.m4';
3807     }
3809     if (variable_defined ('ACLOCAL_M4_SOURCES'))
3810     {
3811         push (@ac_deps, '$(ACLOCAL_M4_SOURCES)');
3812     }
3813     elsif (variable_defined ('ACLOCAL_AMFLAGS'))
3814     {
3815         # Scan all -I directories for m4 files.  These are our
3816         # dependencies.
3817         my $examine_next = 0;
3818         foreach my $amdir (&variable_value_as_list_recursive ('ACLOCAL_AMFLAGS', ''))
3819         {
3820             if ($examine_next)
3821             {
3822                 $examine_next = 0;
3823                 if ($amdir !~ /^\// && -d $amdir)
3824                 {
3825                     foreach my $ac_dep (&my_glob ($amdir . '/*.m4'))
3826                     {
3827                         $ac_dep =~ s/^\.\/+//;
3828                         push (@ac_deps, $ac_dep)
3829                           unless $ac_dep eq "aclocal.m4"
3830                             || $ac_dep eq "acinclude.m4";
3831                     }
3832                 }
3833             }
3834             elsif ($amdir eq '-I')
3835             {
3836                 $examine_next = 1;
3837             }
3838         }
3839     }
3841     # Note that it might be possible that aclocal.m4 doesn't exist but
3842     # should be auto-generated.  This case probably isn't very
3843     # important.
3845     return ($regen_aclocal, @ac_deps);
3849 # @DEPENDENCY
3850 # &rewrite_inputs_into_dependencies ($ADD_SRCDIR, @INPUTS)
3851 # --------------------------------------------------------
3852 # Rewrite a list of input files into a form suitable to put on a
3853 # dependency list.  The idea is that if an input file has a directory
3854 # part the same as the current directory, then the directory part is
3855 # simply removed.  But if the directory part is different, then
3856 # $(top_srcdir) is prepended.  Among other things, this is used to
3857 # generate the dependency list for the output files generated by
3858 # AC_OUTPUT.  Consider what the dependencies should look like in this
3859 # case:
3860 #   AC_OUTPUT(src/out:src/in1:lib/in2)
3861 # The first argument, ADD_SRCDIR, is 1 if $(top_srcdir) should be added.
3862 # If 0 then files that require this addition will simply be ignored.
3863 sub rewrite_inputs_into_dependencies ($@)
3865     my ($add_srcdir, @inputs) = @_;
3866     my @newinputs;
3868     foreach my $single (@inputs)
3869     {
3870         if (dirname ($single) eq $relative_dir)
3871         {
3872             push (@newinputs, basename ($single));
3873         }
3874         elsif ($add_srcdir)
3875         {
3876             push (@newinputs, '$(top_srcdir)/' . $single);
3877         }
3878     }
3880     return @newinputs;
3883 # Handle remaking and configure stuff.
3884 # We need the name of the input file, to do proper remaking rules.
3885 sub handle_configure
3887     my ($local, $input, @secondary_inputs) = @_;
3889     my $input_base = basename ($input);
3890     my $local_base = basename ($local);
3892     my $amfile = $input_base . '.am';
3893     # We know we can always add '.in' because it really should be an
3894     # error if the .in was missing originally.
3895     my $infile = '$(srcdir)/' . $input_base . '.in';
3896     my $colon_infile = '';
3897     if ($local ne $input || @secondary_inputs)
3898     {
3899         $colon_infile = ':' . $input . '.in';
3900     }
3901     $colon_infile .= ':' . join (':', @secondary_inputs)
3902         if @secondary_inputs;
3904     my @rewritten = rewrite_inputs_into_dependencies (1, @secondary_inputs);
3906     my ($regen_aclocal_m4, @aclocal_m4_deps) = scan_aclocal_m4 ();
3908     $output_rules .=
3909       &file_contents ('configure',
3910                       ('MAKEFILE'
3911                        => $local_base,
3912                        'MAKEFILE-DEPS'
3913                        => "@rewritten",
3914                        'CONFIG-MAKEFILE'
3915                        => ((($relative_dir eq '.') ? '$@' : '$(subdir)/$@')
3916                            . $colon_infile),
3917                        'MAKEFILE-IN'
3918                        => $infile,
3919                        'MAKEFILE-IN-DEPS'
3920                        => "@include_stack",
3921                        'MAKEFILE-AM'
3922                        => $amfile,
3923                        'STRICTNESS'
3924                        => $cygnus_mode ? 'cygnus' : $strictness_name,
3925                        'USE-DEPS'
3926                        => $cmdline_use_dependencies ? '' : ' --ignore-deps',
3927                        'MAKEFILE-AM-SOURCES'
3928                        =>  "$input$colon_infile",
3929                        'REGEN-ACLOCAL-M4'
3930                        => $regen_aclocal_m4,
3931                        'ACLOCAL_M4_DEPS'
3932                        => "@aclocal_m4_deps"));
3934     if ($relative_dir eq '.')
3935     {
3936         &push_dist_common ('acconfig.h')
3937             if -f 'acconfig.h';
3938     }
3940     # If we have a configure header, require it.
3941     my $hdr_index = 0;
3942     my @distclean_config;
3943     foreach my $spec (@config_headers)
3944       {
3945         $hdr_index += 1;
3946         # $CONFIG_H_PATH: config.h from top level.
3947         my ($config_h_path, @ins) = split_config_file_spec ($spec);
3948         my $config_h_dir = dirname ($config_h_path);
3950         # If the header is in the current directory we want to build
3951         # the header here.  Otherwise, if we're at the topmost
3952         # directory and the header's directory doesn't have a
3953         # Makefile, then we also want to build the header.
3954         if ($relative_dir eq $config_h_dir
3955             || ($relative_dir eq '.' && ! &is_make_dir ($config_h_dir)))
3956         {
3957             my ($cn_sans_dir, $stamp_dir);
3958             if ($relative_dir eq $config_h_dir)
3959             {
3960                 $cn_sans_dir = basename ($config_h_path);
3961                 $stamp_dir = '';
3962             }
3963             else
3964             {
3965                 $cn_sans_dir = $config_h_path;
3966                 if ($config_h_dir eq '.')
3967                 {
3968                     $stamp_dir = '';
3969                 }
3970                 else
3971                 {
3972                     $stamp_dir = $config_h_dir . '/';
3973                 }
3974             }
3976             # Compute relative path from directory holding output
3977             # header to directory holding input header.  FIXME:
3978             # doesn't handle case where we have multiple inputs.
3979             my $in0_sans_dir;
3980             if (dirname ($ins[0]) eq $relative_dir)
3981             {
3982                 $in0_sans_dir = basename ($ins[0]);
3983             }
3984             else
3985             {
3986                 $in0_sans_dir = backname ($relative_dir) . '/' . $ins[0];
3987             }
3989             require_file ($config_header_location, FOREIGN, $in0_sans_dir);
3991             # Header defined and in this directory.
3992             my @files;
3993             if (-f $config_h_path . '.top')
3994             {
3995                 push (@files, "$cn_sans_dir.top");
3996             }
3997             if (-f $config_h_path . '.bot')
3998             {
3999                 push (@files, "$cn_sans_dir.bot");
4000             }
4002             push_dist_common (@files);
4004             # For now, acconfig.h can only appear in the top srcdir.
4005             if (-f 'acconfig.h')
4006             {
4007                 push (@files, '$(top_srcdir)/acconfig.h');
4008             }
4010             my $stamp = "${stamp_dir}stamp-h${hdr_index}";
4011             $output_rules .=
4012               file_contents ('remake-hdr',
4013                              ('FILES'         => "@files",
4014                               'CONFIG_H'      => $cn_sans_dir,
4015                               'CONFIG_HIN'    => $in0_sans_dir,
4016                               'CONFIG_H_PATH' => $config_h_path,
4017                               'STAMP'         => "$stamp"));
4019             push @distclean_config, $cn_sans_dir, $stamp;
4020         }
4021     }
4023     $output_rules .= file_contents ('clean-hdr',
4024                                     ('FILES' => "@distclean_config"))
4025       if @distclean_config;
4027     # Set location of mkinstalldirs.
4028     define_variable ('mkinstalldirs',
4029                      ('$(SHELL) ' . $config_aux_dir . '/mkinstalldirs'));
4031     macro_error ('CONFIG_HEADER',
4032                  "`CONFIG_HEADER' is an anachronism; now determined from `$configure_ac'")
4033         if variable_defined ('CONFIG_HEADER');
4035     my @config_h;
4036     foreach my $spec (@config_headers)
4037       {
4038         my ($out, @ins) = split_config_file_spec ($spec);
4039         # Generate CONFIG_HEADER define.
4040         if ($relative_dir eq dirname ($out))
4041         {
4042             push @config_h, basename ($out);
4043         }
4044         else
4045         {
4046             push @config_h, "\$(top_builddir)/$out";
4047         }
4048     }
4049     define_variable ("CONFIG_HEADER", "@config_h")
4050       if @config_h;
4052     # Now look for other files in this directory which must be remade
4053     # by config.status, and generate rules for them.
4054     my @actual_other_files = ();
4055     foreach my $lfile (@other_input_files)
4056     {
4057         my $file;
4058         my @inputs;
4059         if ($lfile =~ /^([^:]*):(.*)$/)
4060         {
4061             # This is the ":" syntax of AC_OUTPUT.
4062             $file = $1;
4063             @inputs = split (':', $2);
4064         }
4065         else
4066         {
4067             # Normal usage.
4068             $file = $lfile;
4069             @inputs = $file . '.in';
4070         }
4072         # Automake files should not be stored in here, but in %MAKE_LIST.
4073         prog_error ("$lfile in \@other_input_files")
4074           if -f $file . '.am';
4076         my $local = basename ($file);
4078         # Make sure the dist directory for each input file is created.
4079         # We only have to do this at the topmost level though.  This
4080         # is a bit ugly but it easier than spreading out the logic,
4081         # especially in cases like AC_OUTPUT(foo/out:bar/in), where
4082         # there is no Makefile in bar/.
4083         if ($relative_dir eq '.')
4084         {
4085             foreach (@inputs)
4086             {
4087                 $dist_dirs{dirname ($_)} = 1;
4088             }
4089         }
4091         # We skip files that aren't in this directory.  However, if
4092         # the file's directory does not have a Makefile, and we are
4093         # currently doing `.', then we create a rule to rebuild the
4094         # file in the subdir.
4095         my $fd = dirname ($file);
4096         if ($fd ne $relative_dir)
4097         {
4098             if ($relative_dir eq '.' && ! &is_make_dir ($fd))
4099             {
4100                 $local = $file;
4101             }
4102             else
4103             {
4104                 next;
4105             }
4106         }
4108         my @rewritten_inputs = rewrite_inputs_into_dependencies (1, @inputs);
4109         $output_rules .= ($local . ': '
4110                           . '$(top_builddir)/config.status '
4111                           . "@rewritten_inputs\n"
4112                           . "\t"
4113                           . 'cd $(top_builddir) && '
4114                           . '$(SHELL) ./config.status '
4115                           . ($relative_dir eq '.' ? '' : '$(subdir)/')
4116                           . '$@'
4117                           . "\n");
4118         push (@actual_other_files, $local);
4120         # Require all input files.
4121         require_file ($ac_config_files_location, FOREIGN,
4122                       rewrite_inputs_into_dependencies (0, @inputs));
4123     }
4125     # These files get removed by "make clean".
4126     define_pretty_variable ('CONFIG_CLEAN_FILES', '', @actual_other_files);
4129 # Handle C headers.
4130 sub handle_headers
4132     my @r = &am_install_var ('-defaultdist', 'header', 'HEADERS', 'include',
4133                              'oldinclude', 'pkginclude',
4134                              'noinst', 'check');
4135     foreach (@r)
4136     {
4137         next unless /\..*$/;
4138         &saw_extension ($&);
4139     }
4142 sub handle_gettext
4144     return if ! $seen_gettext || $relative_dir ne '.';
4146     if (! variable_defined ('SUBDIRS'))
4147     {
4148         conf_error ("AM_GNU_GETTEXT used but SUBDIRS not defined");
4149         return;
4150     }
4152     my @subdirs = &variable_value_as_list_recursive ('SUBDIRS', 'all');
4153     macro_error ('SUBDIRS',
4154                  "AM_GNU_GETTEXT used but `po' not in SUBDIRS")
4155         if ! grep ($_ eq 'po', @subdirs);
4157     # intl/ is not required when AM_GNU_GETTEXT is called with
4158     # the `external' option.
4159     macro_error ('SUBDIRS',
4160                  "AM_GNU_GETTEXT used but `intl' not in SUBDIRS")
4161         if (! $seen_gettext_external
4162             && ! grep ($_ eq 'intl', @subdirs));
4164     require_file ($ac_gettext_location, GNU, 'ABOUT-NLS');
4167 # Handle footer elements.
4168 sub handle_footer
4170     # NOTE don't use define_pretty_variable here, because
4171     # $contents{...} is already defined.
4172     $output_vars .= 'SOURCES = ' . variable_value ('SOURCES') . "\n\n"
4173       if variable_value ('SOURCES');
4176     target_error ('.SUFFIXES',
4177                   "use variable `SUFFIXES', not target `.SUFFIXES'")
4178       if target_defined ('.SUFFIXES');
4180     # Note: AIX 4.1 /bin/make will fail if any suffix rule appears
4181     # before .SUFFIXES.  So we make sure that .SUFFIXES appears before
4182     # anything else, by sticking it right after the default: target.
4183     $output_header .= ".SUFFIXES:\n";
4184     if (@suffixes || variable_defined ('SUFFIXES'))
4185     {
4186         # Make sure suffixes has unique elements.  Sort them to ensure
4187         # the output remains consistent.  However, $(SUFFIXES) is
4188         # always at the start of the list, unsorted.  This is done
4189         # because make will choose rules depending on the ordering of
4190         # suffixes, and this lets the user have some control.  Push
4191         # actual suffixes, and not $(SUFFIXES).  Some versions of make
4192         # do not like variable substitutions on the .SUFFIXES line.
4193         my @user_suffixes = (variable_defined ('SUFFIXES')
4194                              ? &variable_value_as_list_recursive ('SUFFIXES', '')
4195                              : ());
4197         my %suffixes = map { $_ => 1 } @suffixes;
4198         delete @suffixes{@user_suffixes};
4200         $output_header .= (".SUFFIXES: "
4201                            . join (' ', @user_suffixes, sort keys %suffixes)
4202                            . "\n");
4203     }
4205     $output_trailer .= file_contents ('footer');
4208 # Deal with installdirs target.
4209 sub handle_installdirs ()
4211     $output_rules .=
4212       &file_contents ('install',
4213                       ('_am_installdirs'
4214                        => variable_value ('_am_installdirs') || '',
4215                        'installdirs-local'
4216                        => (target_defined ('installdirs-local')
4217                            ? ' installdirs-local' : '')));
4221 # Deal with all and all-am.
4222 sub handle_all ($)
4224     my ($makefile) = @_;
4226     # Output `all-am'.
4228     # Put this at the beginning for the sake of non-GNU makes.  This
4229     # is still wrong if these makes can run parallel jobs.  But it is
4230     # right enough.
4231     unshift (@all, basename ($makefile));
4233     foreach my $spec (@config_headers)
4234       {
4235         my ($out, @ins) = split_config_file_spec ($spec);
4236         push (@all, basename ($out))
4237           if dirname ($out) eq $relative_dir;
4238       }
4240     # Install `all' hooks.
4241     if (&target_defined ("all-local"))
4242     {
4243       push (@all, "all-local");
4244       &depend ('.PHONY', "all-local");
4245     }
4247     &pretty_print_rule ("all-am:", "\t\t", @all);
4248     &depend ('.PHONY', 'all-am', 'all');
4251     # Output `all'.
4253     my @local_headers = ();
4254     push @local_headers, '$(BUILT_SOURCES)'
4255       if variable_defined ('BUILT_SOURCES');
4256     foreach my $spec (@config_headers)
4257       {
4258         my ($out, @ins) = split_config_file_spec ($spec);
4259         push @local_headers, basename ($out)
4260           if dirname ($out) eq $relative_dir;
4261       }
4263     if (@local_headers)
4264       {
4265         # We need to make sure config.h is built before we recurse.
4266         # We also want to make sure that built sources are built
4267         # before any ordinary `all' targets are run.  We can't do this
4268         # by changing the order of dependencies to the "all" because
4269         # that breaks when using parallel makes.  Instead we handle
4270         # things explicitly.
4271         $output_all .= ("all: @local_headers"
4272                         . "\n\t"
4273                         . '$(MAKE) $(AM_MAKEFLAGS) '
4274                         . (variable_defined ('SUBDIRS')
4275                            ? 'all-recursive' : 'all-am')
4276                         . "\n\n");
4277       }
4278     else
4279       {
4280         $output_all .= "all: " . (variable_defined ('SUBDIRS')
4281                                   ? 'all-recursive' : 'all-am') . "\n\n";
4282       }
4286 # Handle check merge target specially.
4287 sub do_check_merge_target
4289     if (&target_defined ('check-local'))
4290     {
4291         # User defined local form of target.  So include it.
4292         push (@check_tests, 'check-local');
4293         &depend ('.PHONY', 'check-local');
4294     }
4296     # In --cygnus mode, check doesn't depend on all.
4297     if ($cygnus_mode)
4298     {
4299         # Just run the local check rules.
4300         &pretty_print_rule ('check-am:', "\t\t", @check);
4301     }
4302     else
4303     {
4304         # The check target must depend on the local equivalent of
4305         # `all', to ensure all the primary targets are built.  Then it
4306         # must build the local check rules.
4307         $output_rules .= "check-am: all-am\n";
4308         &pretty_print_rule ("\t\$(MAKE) \$(AM_MAKEFLAGS)", "\t  ",
4309                             @check)
4310             if @check;
4311     }
4312     &pretty_print_rule ("\t\$(MAKE) \$(AM_MAKEFLAGS)", "\t  ",
4313                         @check_tests)
4314         if @check_tests;
4316     &depend ('.PHONY', 'check', 'check-am');
4317     $output_rules .= ("check: "
4318                       . (variable_defined ('SUBDIRS')
4319                          ? 'check-recursive' : 'check-am')
4320                       . "\n");
4323 # Handle all 'clean' targets.
4324 sub handle_clean
4326     my %transform;
4328     # Don't include `MAINTAINER'; it is handled specially below.
4329     foreach my $name ('MOSTLY', '', 'DIST')
4330     {
4331       $transform{"${name}CLEAN"} = variable_defined ("${name}CLEANFILES");
4332     }
4334     # Built sources are automatically removed by maintainer-clean.
4335     push (@maintainer_clean_files, '$(BUILT_SOURCES)')
4336         if variable_defined ('BUILT_SOURCES');
4337     push (@maintainer_clean_files, '$(MAINTAINERCLEANFILES)')
4338         if variable_defined ('MAINTAINERCLEANFILES');
4340     $output_rules .= &file_contents ('clean',
4341                                      (%transform,
4342                                       'MCFILES'
4343                                       # Join with no space to avoid
4344                                       # spurious `test -z' success at
4345                                       # runtime.
4346                                       => join ('', @maintainer_clean_files),
4347                                       'MFILES'
4348                                       # A space is required in the join here.
4349                                       => "@maintainer_clean_files"));
4353 # &depend ($CATEGORY, @DEPENDENDEES)
4354 # ----------------------------------
4355 # The target $CATEGORY depends on @DEPENDENDEES.
4356 sub depend
4358     my ($category, @dependendees) = @_;
4359     {
4360       push (@{$dependencies{$category}}, @dependendees);
4361     }
4365 # &target_cmp ($A, $B)
4366 # --------------------
4367 # Subroutine for &handle_factored_dependencies to let `.PHONY' be last.
4368 sub target_cmp
4370     return 0
4371         if $a eq $b;
4372     return -1
4373         if $b eq '.PHONY';
4374     return 1
4375         if $a eq '.PHONY';
4376     return $a cmp $b;
4380 # &handle_factored_dependencies ()
4381 # --------------------------------
4382 # Handle everything related to gathered targets.
4383 sub handle_factored_dependencies
4385     # Reject bad hooks.
4386     foreach my $utarg ('uninstall-data-local', 'uninstall-data-hook',
4387                        'uninstall-exec-local', 'uninstall-exec-hook')
4388     {
4389         if (&target_defined ($utarg))
4390         {
4391             my $x = $utarg;
4392             $x =~ s/(data|exec)-//;
4393             target_error ($utarg, "use `$x', not `$utarg'");
4394         }
4395     }
4397     if (&target_defined ('install-local'))
4398     {
4399         target_error ('install-local',
4400                       "use `install-data-local' or `install-exec-local', "
4401                       . "not `install-local'");
4402     }
4404     if (!defined $options{'no-installinfo'}
4405         && &target_defined ('install-info-local'))
4406     {
4407         target_error ('install-info-local',
4408                       "`install-info-local' target defined but "
4409                       . "`no-installinfo' option not in use");
4410     }
4412     # Install the -local hooks.
4413     foreach (keys %dependencies)
4414     {
4415       # Hooks are installed on the -am targets.
4416       s/-am$// or next;
4417       if (&target_defined ("$_-local"))
4418         {
4419           depend ("$_-am", "$_-local");
4420           &depend ('.PHONY', "$_-local");
4421         }
4422     }
4424     # Install the -hook hooks.
4425     # FIXME: Why not be as liberal as we are with -local hooks?
4426     foreach ('install-exec', 'install-data', 'uninstall')
4427     {
4428       if (&target_defined ("$_-hook"))
4429         {
4430           $actions{"$_-am"} .=
4431             ("\t\@\$(NORMAL_INSTALL)\n"
4432              . "\t" . '$(MAKE) $(AM_MAKEFLAGS) ' . "$_-hook\n");
4433         }
4434     }
4436     # All the required targets are phony.
4437     depend ('.PHONY', keys %required_targets);
4439     # Actually output gathered targets.
4440     foreach (sort target_cmp keys %dependencies)
4441     {
4442         # If there is nothing about this guy, skip it.
4443         next
4444           unless (@{$dependencies{$_}}
4445                   || $actions{$_}
4446                   || $required_targets{$_});
4447         &pretty_print_rule ("$_:", "\t",
4448                             uniq (sort @{$dependencies{$_}}));
4449         $output_rules .= $actions{$_}
4450           if defined $actions{$_};
4451         $output_rules .= "\n";
4452     }
4456 # &handle_tests_dejagnu ()
4457 # ------------------------
4458 sub handle_tests_dejagnu
4460     push (@check_tests, 'check-DEJAGNU');
4461     $output_rules .= file_contents ('dejagnu');
4465 # Handle TESTS variable and other checks.
4466 sub handle_tests
4468     if (defined $options{'dejagnu'})
4469     {
4470         &handle_tests_dejagnu;
4471     }
4472     else
4473     {
4474         foreach my $c ('DEJATOOL', 'RUNTEST', 'RUNTESTFLAGS')
4475         {
4476             macro_error ($c,
4477                          "`$c' defined but `dejagnu' not in `AUTOMAKE_OPTIONS'")
4478               if variable_defined ($c);
4479         }
4480     }
4482     if (variable_defined ('TESTS'))
4483     {
4484         push (@check_tests, 'check-TESTS');
4485         $output_rules .= &file_contents ('check');
4486     }
4489 # Handle Emacs Lisp.
4490 sub handle_emacs_lisp
4492     my @elfiles = &am_install_var ('-candist', 'lisp', 'LISP',
4493                                    'lisp', 'noinst');
4495     return if ! @elfiles;
4497     # Generate .elc files.
4498     my @elcfiles = map { $_ . 'c' } @elfiles;
4499     define_pretty_variable ('ELCFILES', '', @elcfiles);
4501     push (@all, '$(ELCFILES)');
4503     &am_error ("`lisp_LISP' defined but `AM_PATH_LISPDIR' not in `$configure_ac'")
4504       if ! $am_lispdir_location && variable_defined ('lisp_LISP');
4506     require_conf_file ($am_lispdir_location, FOREIGN, 'elisp-comp');
4507     &define_variable ('elisp_comp', $config_aux_dir . '/elisp-comp');
4510 # Handle Python
4511 sub handle_python
4513     my @pyfiles = &am_install_var ('-defaultdist', 'python', 'PYTHON',
4514                                    'python', 'noinst');
4515     return if ! @pyfiles;
4517     # Found some python.
4518     &am_error ("`python_PYTHON' defined but `AM_PATH_PYTHON' not in `$configure_ac'")
4519         if ! $pythondir_location && variable_defined ('python_PYTHON');
4521     require_conf_file ($pythondir_location, FOREIGN, 'py-compile');
4522     &define_variable ('py_compile', $config_aux_dir . '/py-compile');
4525 # Handle Java.
4526 sub handle_java
4528     my @sourcelist = &am_install_var ('-candist',
4529                                       'java', 'JAVA',
4530                                       'java', 'noinst', 'check');
4531     return if ! @sourcelist;
4533     my @prefix = am_primary_prefixes ('JAVA', 1,
4534                                       'java', 'noinst', 'check');
4536     my $dir;
4537     foreach my $curs (@prefix)
4538       {
4539         next
4540           if $curs eq 'EXTRA';
4542         macro_error ($curs . '_JAVA',
4543                      "multiple _JAVA primaries in use")
4544           if defined $dir;
4545         $dir = $curs;
4546       }
4549     push (@all, 'class' . $dir . '.stamp');
4553 # Handle some of the minor options.
4554 sub handle_minor_options
4556     if (defined $options{'readme-alpha'})
4557     {
4558         if ($relative_dir eq '.')
4559         {
4560             if ($package_version !~ /^$GNITS_VERSION_PATTERN$/)
4561             {
4562                 # FIXME: allow real filename.
4563                 file_error ($package_version_location,
4564                             "version `$package_version' doesn't follow Gnits standards");
4565             }
4566             elsif (defined $1 && -f 'README-alpha')
4567             {
4568                 # This means we have an alpha release.  See
4569                 # GNITS_VERSION_PATTERN for details.
4570                 require_file_with_macro ('AUTOMAKE_OPTIONS',
4571                                          FOREIGN, 'README-alpha');
4572             }
4573         }
4574     }
4577 ################################################################
4579 # ($OUTPUT, @INPUTS)
4580 # &split_config_file_spec ($SPEC)
4581 # -------------------------------
4582 # Decode the Autoconf syntax for config files (files, headers, links
4583 # etc.).
4584 sub split_config_file_spec ($)
4586   my ($spec) = @_;
4587   my ($output, @inputs) = split (/:/, $spec);
4589   push @inputs, "$output.in"
4590     unless @inputs;
4592   return ($output, @inputs);
4596 my %make_list;
4598 # &scan_autoconf_config_files ($CONFIG-FILES)
4599 # -------------------------------------------
4600 # Study $CONFIG-FILES which is the first argument to AC_CONFIG_FILES
4601 # (or AC_OUTPUT).
4602 sub scan_autoconf_config_files
4604     my ($config_files) = @_;
4605     # Look at potential Makefile.am's.
4606     foreach (split ' ', $config_files)
4607     {
4608         # Must skip empty string for Perl 4.
4609         next if $_ eq "\\" || $_ eq '';
4611         # Handle $local:$input syntax.  Note that we ignore
4612         # every input file past the first, though we keep
4613         # those around for later.
4614         my ($local, $input, @rest) = split (/:/);
4615         if (! $input)
4616         {
4617             $input = $local;
4618         }
4619         else
4620         {
4621             # FIXME: should be error if .in is missing.
4622             $input =~ s/\.in$//;
4623         }
4625         if (-f $input . '.am')
4626         {
4627             # We have a file that automake should generate.
4628             $make_list{$input} = join (':', ($local, @rest));
4629         }
4630         else
4631         {
4632             # We have a file that automake should cause to be
4633             # rebuilt, but shouldn't generate itself.
4634             push (@other_input_files, $_);
4635         }
4636     }
4640 # &scan_autoconf_traces ($FILENAME)
4641 # ---------------------------------
4642 # FIXME: For the time being, we don't care about the FILENAME.
4643 sub scan_autoconf_traces ($)
4645   my ($filename) = @_;
4647   my @traced = qw(AC_CANONICAL_HOST
4648                   AC_CANONICAL_SYSTEM
4649                   AC_CONFIG_AUX_DIR
4650                   AC_CONFIG_FILES
4651                   AC_INIT
4652                   AC_LIBSOURCE
4653                   AC_PROG_LEX
4654                   AC_PROG_LIBTOOL AM_PROG_LIBTOOL
4655                   AC_SUBST
4656                   AM_AUTOMAKE_VERSION
4657                   AM_CONDITIONAL
4658                   AM_CONFIG_HEADER
4659                   AM_C_PROTOTYPES
4660                   AM_GNU_GETTEXT
4661                   AM_INIT_AUTOMAKE
4662                   AM_MAINTAINER_MODE
4663                   AM_PATH_LISPDIR
4664                   AM_PATH_PYTHON
4665                   AM_PROG_CC_C_O);
4667   my $traces = "$ENV{amtraces} ";
4669   # Use a separator unlikely to be used, not `:', the default, which
4670   # has a precise meaning for AC_CONFIG_FILES and so on.
4671   $traces .= join (' ',
4672                    map { "--trace=$_" . ':\$f:\$l::\$n::\${::}%' } @traced);
4674   my $tracefh = new Automake::XFile ("$traces |");
4675   verbose "reading $traces";
4677   while ($_ = $tracefh->getline)
4678     {
4679       chomp;
4680       my ($here, @args) = split /::/;
4681       my $macro = $args[0];
4683       # Alphabetical ordering please.
4684       if ($macro eq 'AC_CANONICAL_HOST')
4685         {
4686           if (! $seen_canonical)
4687             {
4688               $seen_canonical = AC_CANONICAL_HOST;
4689               $canonical_location = $here;
4690             };
4691         }
4692       elsif ($macro eq 'AC_CANONICAL_SYSTEM')
4693         {
4694           $seen_canonical = AC_CANONICAL_SYSTEM;
4695           $canonical_location = $here;
4696         }
4697       elsif ($macro eq 'AC_CONFIG_AUX_DIR')
4698         {
4699           @config_aux_path = $args[1];
4700           $config_aux_dir_set_in_configure_in = 1;
4701         }
4702       elsif ($macro eq 'AC_CONFIG_FILES')
4703         {
4704           # Look at potential Makefile.am's.
4705           $ac_config_files_location = $here;
4706           &scan_autoconf_config_files ($args[1]);
4707         }
4708       elsif ($macro eq 'AC_INIT')
4709         {
4710           if (defined $args[2])
4711             {
4712               $package_version = $args[2];
4713               $package_version_location = $here;
4714             }
4715         }
4716       elsif ($macro eq 'AC_LIBSOURCE')
4717         {
4718           $libsources{$args[1]} = $here;
4719         }
4720       elsif ($macro =~ /^A(C|M)_PROG_LIBTOOL$/)
4721         {
4722           $seen_libtool = $here;
4723         }
4724       elsif ($macro eq 'AC_PROG_LEX')
4725         {
4726           $seen_prog_lex = $here;
4727         }
4728       elsif ($macro eq 'AC_SUBST')
4729         {
4730           # Just check for alphanumeric in AC_SUBST.  If you do
4731           # AC_SUBST(5), then too bad.
4732           $configure_vars{$args[1]} = $here
4733             if $args[1] =~ /^\w+$/;
4734         }
4735       elsif ($macro eq 'AM_AUTOMAKE_VERSION')
4736         {
4737           file_error ($here,
4738                       "version mismatch.  This is Automake $VERSION,\n" .
4739                       "but the definition used by this AM_INIT_AUTOMAKE\n" .
4740                       "comes from Automake $args[1].  You should recreate\n" .
4741                       "aclocal.m4 with aclocal and run automake again.\n")
4742               if ($VERSION ne $args[1]);
4744           $seen_automake_version = 1;
4745         }
4746       elsif ($macro eq 'AM_CONDITIONAL')
4747         {
4748           $configure_cond{$args[1]} = $here;
4749         }
4750       elsif ($macro eq 'AM_CONFIG_HEADER')
4751         {
4752           $config_header_location = $here;
4753           push @config_headers, split (' ', $args[1]);
4754         }
4755       elsif ($macro eq 'AM_C_PROTOTYPES')
4756         {
4757           $am_c_prototypes = $here;
4758         }
4759       elsif ($macro eq 'AM_GNU_GETTEXT')
4760         {
4761           $seen_gettext = $here;
4762           $ac_gettext_location = $here;
4763           $seen_gettext_external = grep ($_ eq 'external', @args);
4764         }
4765       elsif ($macro eq 'AM_INIT_AUTOMAKE')
4766         {
4767           $seen_init_automake = $here;
4768           if (defined $args[2])
4769             {
4770               $package_version = $args[2];
4771               $package_version_location = $here;
4772             }
4773           elsif (defined $args[1])
4774             {
4775               $global_options = $args[1];
4776             }
4777         }
4778       elsif ($macro eq 'AM_MAINTAINER_MODE')
4779         {
4780           $seen_maint_mode = $here;
4781         }
4782       elsif ($macro eq 'AM_PATH_LISPDIR')
4783         {
4784           $am_lispdir_location = $here;
4785         }
4786       elsif ($macro eq 'AM_PATH_PYTHON')
4787         {
4788           $pythondir_location = $here;
4789         }
4790       elsif ($macro eq 'AM_PROG_CC_C_O')
4791         {
4792           $seen_cc_c_o = $here;
4793         }
4794    }
4798 # &scan_one_autoconf_file ($FILENAME)
4799 # -----------------------------------
4800 # Scan one file for interesting things.  Subroutine of
4801 # &scan_autoconf_files.
4802 sub scan_one_autoconf_file
4804     my ($filename) = @_;
4806     # Some macros already provide the right traces to enable generic
4807     # code and specific arguments, instead of dedicated code.  But
4808     # currently we don't handle traces.  Rewrite these dedicated
4809     # macros handling into the generic macro invocation, and let our
4810     # generic case handle them.
4812     my %generalize =
4813       (
4814        'AC_FUNC_ALLOCA'           => 'AC_LIBSOURCES([alloca.c])',
4815        'AC_FUNC_GETLOADAVG'       => 'AC_LIBSOURCES([getloadavg.c])',
4816        'AC_FUNC_MEMCMP'           => 'AC_LIBSOURCES([memcmp.c])',
4817        'AC_STRUCT_ST_BLOCKS'      => 'AC_LIBSOURCES([fileblocks.c])',
4818        'A[CM]_REPLACE_GNU_GETOPT' => 'AC_LIBSOURCES([getopt.c, getopt1.c])',
4819        'A[CM]_FUNC_STRTOD'        => 'AC_LIBSOURCES([strtod.c])',
4820        'AM_WITH_REGEX'      => 'AC_LIBSOURCES([rx.c, rx.h, regex.c, regex.h])',
4821        'AC_FUNC_MKTIME'           => 'AC_LIBSOURCES([mktime.c])',
4822        'A[CM]_FUNC_ERROR_AT_LINE' => 'AC_LIBSOURCES([error.c, error.h])',
4823        'A[CM]_FUNC_OBSTACK'       => 'AC_LIBSOURCES([obstack.c, obstack.h])',
4824       );
4826     my $configfh = new Automake::XFile ("< $filename");
4827     verbose "reading $filename";
4829     my ($in_ac_output, $in_ac_replace) = (0, 0);
4830     while ($_ = $configfh->getline)
4831     {
4832         # Remove comments from current line.
4833         s/\bdnl\b.*$//;
4834         s/\#.*$//;
4836         # Skip macro definitions.  Otherwise we might be confused into
4837         # thinking that a macro that was only defined was actually
4838         # used.
4839         next if /AC_DEFUN/;
4841         # Follow includes.  This is a weirdness commonly in use at
4842         # Cygnus and hopefully nowhere else.
4843         if (/\b(?:m4_)?s?include\((.*)\)/ && -f $1)
4844         {
4845             # $_ being local, if we don't preserve it, when coming
4846             # back we will have $_ undefined, which is bad for the
4847             # the rest of this routine.
4848             my $underscore = $_;
4849             &scan_one_autoconf_file (unquote_m4_arg ($1));
4850             $_ = $underscore;
4851         }
4853         for my $generalize (keys %generalize)
4854           {
4855             s/\b$generalize\b/$generalize{$generalize}/g;
4856           }
4859         my $here = "$filename:$.";
4861         # Populate libobjs array.
4862         if (/LIBOBJS="(.*)\s+\$LIBOBJS"/
4863                || /LIBOBJS="\$LIBOBJS\s+(.*)"/)
4864         {
4865             foreach my $libobj_iter (split (' ', $1))
4866             {
4867                 if ($libobj_iter =~ /^(.*)\.o(bj)?$/
4868                     || $libobj_iter =~ /^(.*)\.\$ac_objext$/
4869                     || $libobj_iter =~ /^(.*)\.\$\{ac_objext\}$/)
4870                 {
4871                     $libsources{$1 . '.c'} = $here;
4872                 }
4873             }
4874         }
4875         elsif (/AC_LIBOBJ\(([^)]+)\)/)
4876         {
4877             $libsources{unquote_m4_arg ($1) . ".c"} = $here;
4878         }
4879         elsif (/AC_LIBSOURCE\(([^)]+)\)/)
4880         {
4881             $libsources{&unquote_m4_arg ($1)} = $here;
4882         }
4883         elsif (/AC_LIBSOURCES\(([^)]+)\)/)
4884         {
4885             foreach my $lc_iter (split (/[, ]+/, &unquote_m4_arg ($1)))
4886             {
4887                 $libsources{$lc_iter} = $here;
4888             }
4889         }
4891         if (! $in_ac_replace && s/AC_REPLACE_FUNCS\s*\(\[?//)
4892         {
4893             $in_ac_replace = 1;
4894         }
4895         if ($in_ac_replace)
4896         {
4897             $in_ac_replace = 0 if s/[\]\)].*$//;
4898             # Remove trailing backslash.
4899             s/\\$//;
4900             foreach (split)
4901             {
4902                 # Need to skip empty elements for Perl 4.
4903                 next if $_ eq '';
4904                 $libsources{$_ . '.c'} = $here;
4905             }
4906         }
4908         if (/$obsolete_rx/o)
4909         {
4910             my $hint = '';
4911             if ($obsolete_macros{$1} ne '')
4912             {
4913                 $hint = '; ' . $obsolete_macros{$1};
4914             }
4915             file_error ($here, "`$1' is obsolete$hint");
4916         }
4918         # Process the AC_OUTPUT and AC_CONFIG_FILES macros.
4919         if (! $in_ac_output && s/(AC_(OUTPUT|CONFIG_FILES))\s*\(\[?//)
4920         {
4921             $in_ac_output = $1;
4922             $ac_config_files_location = $here;
4923         }
4924         if ($in_ac_output)
4925         {
4926             my $closing = 0;
4927             if (s/[\]\),].*$//)
4928             {
4929                 $in_ac_output = 0;
4930                 $closing = 1;
4931             }
4933             # Look at potential Makefile.am's.
4934             &scan_autoconf_config_files ($_);
4936             if ($closing
4937                 && scalar keys %make_list == 0
4938                 && @other_input_files == 0)
4939             {
4940                 file_error ($ac_config_files_location,
4941                             "no files mentioned in `$in_ac_output'");
4942                 exit 1;
4943             }
4944         }
4946         if (/$AC_CONFIG_AUX_DIR_PATTERN/o)
4947         {
4948             @config_aux_path = &unquote_m4_arg ($1);
4949             $config_aux_dir_set_in_configure_in = $here;
4950         }
4952         # Check for ansi2knr.
4953         $am_c_prototypes = $here if /AM_C_PROTOTYPES/;
4955         # Check for `-c -o' code.
4956         $seen_cc_c_o = $here if /AM_PROG_CC_C_O/;
4958         # Check for NLS support.
4959         if (/\bAM_GNU_GETTEXT\b/)
4960         {
4961             $seen_gettext = $here;
4962             $ac_gettext_location = $here;
4963             $seen_gettext_external = 1
4964                 if /\bAM_GNU_GETTEXT\([^\)]*\bexternal\b/;
4965         }
4967         # Handle configuration headers.  A config header of `[$1]'
4968         # means we are actually scanning AM_CONFIG_HEADER from
4969         # aclocal.m4.  Same thing with a leading underscore.
4970         if (/(?<!_)A([CM])_CONFIG_HEADERS?\s*\((.*)\)/
4971             && $2 ne '[$1]')
4972         {
4973             file_error ($here,
4974                "`automake requires `AM_CONFIG_HEADER', not `AC_CONFIG_HEADER'")
4975               if $1 eq 'C';
4977             $config_header_location = $here;
4978             push @config_headers, split (' ', unquote_m4_arg ($2));
4979         }
4981         # Handle AC_CANONICAL_*.  Always allow upgrading to
4982         # AC_CANONICAL_SYSTEM, but never downgrading.
4983         if (/AC_CANONICAL_HOST/ || /AC_CYGWIN/ || /AC_EMXOS2/ || /AC_MINGW32/)
4984           {
4985             if (! $seen_canonical)
4986               {
4987                 $seen_canonical = AC_CANONICAL_HOST;
4988                 $canonical_location = $here;
4989               }
4990           }
4991         if (/AC_CANONICAL_SYSTEM/)
4992           {
4993             $seen_canonical = AC_CANONICAL_SYSTEM;
4994             $canonical_location = $here;
4995           }
4997         # If using X, include some extra variable definitions.  NOTE
4998         # we don't want to force these into CFLAGS or anything,
4999         # because not all programs will necessarily use X.
5000         if (/AC_PATH_XTRA/)
5001           {
5002             foreach my $var (qw(X_CFLAGS X_LIBS X_EXTRA_LIBS X_PRE_LIBS))
5003               {
5004                 $configure_vars{$var} = $here;
5005               }
5006           }
5008         # AM_INIT_AUTOMAKE with any number of argument
5009         if (/AM_INIT_AUTOMAKE/)
5010         {
5011             $seen_init_automake = $here;
5012         }
5014         # AC_INIT or AM_INIT_AUTOMAKE with two arguments
5015         if (/$AC_INIT_PATTERN/o || /$AM_INIT_AUTOMAKE_PATTERN/o)
5016         {
5017             if ($1 =~ /$AM_PACKAGE_VERSION_PATTERN/o)
5018             {
5019                 $package_version = $1;
5020                 $package_version_location = $here;
5021             }
5022         }
5024         # AM_INIT_AUTOMAKE with one argument.
5025         if (/AM_INIT_AUTOMAKE\(([^),]+)\)/)
5026         {
5027             $global_options = &unquote_m4_arg ($1);
5028         }
5030         if (/AM_AUTOMAKE_VERSION\(([^)]+)\)/)
5031         {
5032             my $vers = &unquote_m4_arg ($1);
5033             file_error ($here,
5034                         "version mismatch.  This is Automake $VERSION, " .
5035                         "but $filename\nwas generated for Automake $vers.  " .
5036                         "You should recreate\n$filename with aclocal and " .
5037                         "run automake again.\n")
5038                     if ($VERSION ne $vers);
5040             $seen_automake_version = 1;
5041         }
5043         if (/AM_PROG_LEX/)
5044         {
5045             $configure_vars{'LEX'} = $here;
5046             $configure_vars{'LEX_OUTPUT_ROOT'} = $here;
5047             $configure_vars{'LEXLIB'} = $here;
5048             $seen_prog_lex = $here;
5049         }
5050         if (/AC_PROG_LEX/ && $filename =~ /configure\.(ac|in)$/)
5051         {
5052             $configure_vars{'LEX'} = $here;
5053             $configure_vars{'LEX_OUTPUT_ROOT'} = $here;
5054             $configure_vars{'LEXLIB'} = $here;
5055             $seen_prog_lex = $here;
5056             file_warning ($here,
5057                    "automake requires `AM_PROG_LEX', not `AC_PROG_LEX'");
5058         }
5060         if (/AC_PROG_(F77|YACC|RANLIB|CC|CXXCPP|CXX|LEX|AWK|CPP|LN_S)/)
5061         {
5062             $configure_vars{$1} = $here;
5063         }
5064         if (/$AC_CHECK_PATTERN/o)
5065         {
5066             $configure_vars{$3} = $here;
5067         }
5068         if (/$AM_MISSING_PATTERN/o
5069             && $1 ne 'ACLOCAL'
5070             && $1 ne 'AUTOCONF'
5071             && $1 ne 'AUTOMAKE'
5072             && $1 ne 'AUTOHEADER'
5073             # AM_INIT_AUTOMAKE is AM_MISSING_PROG'ing MAKEINFO.  But
5074             # we handle it elsewhere.
5075             && $1 ne 'MAKEINFO')
5076         {
5077             $configure_vars{$1} = $here;
5078         }
5080         # Explicitly avoid ANSI2KNR -- we AC_SUBST that in protos.m4,
5081         # but later define it elsewhere.  This is pretty hacky.  We
5082         # also explicitly avoid INSTALL_SCRIPT and some other
5083         # variables because they are defined in header-vars.am.
5084         # AMDEPBACKSLASH might be subst'd by `\', which certainly would
5085         # not be appreciated by Make.
5086         if (/$AC_SUBST_PATTERN/o
5087             && $1 ne 'ANSI2KNR'
5088             && $1 ne 'INSTALL_SCRIPT'
5089             && $1 ne 'INSTALL_DATA'
5090             && $1 ne 'AMDEPBACKSLASH')
5091         {
5092             $configure_vars{$1} = $here;
5093         }
5095         if (/AM_MAINTAINER_MODE/)
5096         {
5097             $seen_maint_mode = $here;
5098             $configure_cond{'MAINTAINER_MODE'} = $here;
5099         }
5101         $am_lispdir_location = $here if /AM_PATH_LISPDIR/;
5103         if (/AM_PATH_PYTHON/)
5104           {
5105             $pythondir_location = $here;
5106             $configure_vars{'pythondir'} = $here;
5107             $configure_vars{'PYTHON'} = $here;
5108           }
5110         if (/A(C|M)_PROG_LIBTOOL/)
5111         {
5112             # We're not ready for this yet.  People still use a
5113             # libtool with no AC_PROG_LIBTOOL.  Once that is the
5114             # dominant version we can reenable this code -- but next
5115             # time by mentioning the macro in %obsolete_macros, both
5116             # here and in aclocal.in.
5118             # if (/AM_PROG_LIBTOOL/)
5119             # {
5120             #   file_warning ($here, "`AM_PROG_LIBTOOL' is obsolete, use `AC_PROG_LIBTOOL' instead");
5121             # }
5122             $seen_libtool = $here;
5123             $configure_vars{'LIBTOOL'} = $here;
5124             $configure_vars{'RANLIB'} = $here;
5125             $configure_vars{'CC'} = $here;
5126             # AC_PROG_LIBTOOL runs AC_CANONICAL_HOST.  Make sure we
5127             # never downgrade (if we've seen AC_CANONICAL_SYSTEM).
5128             $seen_canonical = AC_CANONICAL_HOST if ! $seen_canonical;
5129         }
5131         $seen_multilib = $here if (/AM_ENABLE_MULTILIB/);
5133         if (/$AM_CONDITIONAL_PATTERN/o)
5134         {
5135             $configure_cond{$1} = $here;
5136         }
5138         # Check for Fortran 77 intrinsic and run-time libraries.
5139         if (/AC_F77_LIBRARY_LDFLAGS/)
5140         {
5141             $configure_vars{'FLIBS'} = $here;
5142         }
5143     }
5147 # &scan_autoconf_files ()
5148 # -----------------------
5149 # Check whether we use `configure.ac' or `configure.in'.
5150 # Scan it (and possibly `aclocal.m4') for interesting things.
5151 # We must scan aclocal.m4 because there might be AC_SUBSTs and such there.
5152 sub scan_autoconf_files
5154     # Reinitialize libsources here.  This isn't really necessary,
5155     # since we currently assume there is only one configure.ac.  But
5156     # that won't always be the case.
5157     %libsources = ();
5159     $configure_ac = find_configure_ac;
5160     die "$me: `configure.ac' or `configure.in' is required\n"
5161         if !$configure_ac;
5163     if (defined $ENV{'amtraces'})
5164     {
5165         print STDERR "$me: Autoconf traces is an experimental feature\n";
5166         print STDERR "$me: use at your own risks\n";
5168         scan_autoconf_traces ($configure_ac);
5169     }
5170     else
5171       {
5172         scan_one_autoconf_file ($configure_ac);
5173         scan_one_autoconf_file ('aclocal.m4')
5174           if -f 'aclocal.m4';
5175       }
5177     # Set input and output files if not specified by user.
5178     if (! @input_files)
5179     {
5180         @input_files = sort keys %make_list;
5181         %output_files = %make_list;
5182     }
5184     @configure_input_files = sort keys %make_list;
5186     conf_error ("`AM_INIT_AUTOMAKE' must be used")
5187         if ! $seen_init_automake;
5189     if (! $seen_automake_version)
5190     {
5191         if (-f 'aclocal.m4')
5192         {
5193             file_error ($seen_init_automake || $me,
5194                         "your implementation of AM_INIT_AUTOMAKE comes from " .
5195                         "an\nold Automake version.  You should recreate " .
5196                         "aclocal.m4\nwith aclocal and run automake again.\n");
5197         }
5198         else
5199         {
5200             file_error ($seen_init_automake || $me,
5201                         "no proper implementation of AM_INIT_AUTOMAKE was " .
5202                         "found,\nprobably because aclocal.m4 is missing...\n" .
5203                         "You should run aclocal to create this file, then\n" .
5204                         "run automake again.\n");
5205         }
5206     }
5208     # Look for some files we need.  Always check for these.  This
5209     # check must be done for every run, even those where we are only
5210     # looking at a subdir Makefile.  We must set relative_dir so that
5211     # the file-finding machinery works.
5212     # FIXME: Is this broken because it needs dynamic scopes.
5213     # My tests seems to show it's not the case.
5214     $relative_dir = '.';
5215     require_conf_file ($configure_ac, FOREIGN,
5216                        'install-sh', 'mkinstalldirs', 'missing');
5217     am_error ("`install.sh' is an anachronism; use `install-sh' instead")
5218         if -f $config_aux_path[0] . '/install.sh';
5220     require_conf_file ($pythondir_location, FOREIGN, 'py-compile')
5221       if $pythondir_location;
5223     # Preserve dist_common for later.
5224     $configure_dist_common = variable_value ('DIST_COMMON', 'TRUE') || '';
5227 ################################################################
5229 # Set up for Cygnus mode.
5230 sub check_cygnus
5232     return unless $cygnus_mode;
5234     &set_strictness ('foreign');
5235     $options{'no-installinfo'} = 1;
5236     $options{'no-dependencies'} = 1;
5237     $use_dependencies = 0;
5239     conf_error ("`AM_MAINTAINER_MODE' required when --cygnus specified")
5240       if !$seen_maint_mode;
5243 # Do any extra checking for GNU standards.
5244 sub check_gnu_standards
5246     if ($relative_dir eq '.')
5247     {
5248         # In top level (or only) directory.
5249         require_file ("$am_file.am", GNU,
5250                       qw(INSTALL NEWS README COPYING AUTHORS ChangeLog));
5251     }
5253     if ($strictness >= GNU
5254         && defined $options{'no-installman'})
5255     {
5256         macro_error ('AUTOMAKE_OPTIONS',
5257                      "option `no-installman' disallowed by GNU standards");
5258     }
5260     if ($strictness >= GNU
5261         && defined $options{'no-installinfo'})
5262     {
5263         macro_error ('AUTOMAKE_OPTIONS',
5264                      "option `no-installinfo' disallowed by GNU standards");
5265     }
5268 # Do any extra checking for GNITS standards.
5269 sub check_gnits_standards
5271     if ($relative_dir eq '.')
5272     {
5273         # In top level (or only) directory.
5274         require_file ("$am_file.am", GNITS, 'THANKS');
5275     }
5278 ################################################################
5280 # Functions to handle files of each language.
5282 # Each `lang_X_rewrite($DIRECTORY, $BASE, $EXT)' function follows a
5283 # simple formula: Return value is $LANG_SUBDIR if the resulting object
5284 # file should be in a subdir if the source file is, $LANG_PROCESS if
5285 # file is to be dealt with, $LANG_IGNORE otherwise.
5287 # Much of the actual processing is handled in
5288 # handle_single_transform_list.  These functions exist so that
5289 # auxiliary information can be recorded for a later cleanup pass.
5290 # Note that the calls to these functions are computed, so don't bother
5291 # searching for their precise names in the source.
5293 # This is just a convenience function that can be used to determine
5294 # when a subdir object should be used.
5295 sub lang_sub_obj
5297     return defined $options{'subdir-objects'} ? $LANG_SUBDIR : $LANG_PROCESS;
5300 # Rewrite a single C source file.
5301 sub lang_c_rewrite
5303     my ($directory, $base, $ext) = @_;
5305     if (defined $options{'ansi2knr'} && $base =~ /_$/)
5306     {
5307         # FIXME: include line number in error.
5308         am_error ("C source file `$base.c' would be deleted by ansi2knr rules");
5309     }
5311     my $r = $LANG_PROCESS;
5312     if (defined $options{'subdir-objects'})
5313     {
5314         $r = $LANG_SUBDIR;
5315         $base = $directory . '/' . $base
5316             unless $directory eq '.' || $directory eq '';
5318         if (! $seen_cc_c_o)
5319         {
5320             # Only give error once.
5321             $seen_cc_c_o = 1;
5322             # FIXME: line number.
5323             am_error ("C objects in subdir but `AM_PROG_CC_C_O' not in `$configure_ac'");
5324         }
5326         require_conf_file ("$am_file.am", FOREIGN, 'compile');
5328         # In this case we already have the directory information, so
5329         # don't add it again.
5330         $de_ansi_files{$base} = '';
5331     }
5332     else
5333     {
5334         $de_ansi_files{$base} = (($directory eq '.' || $directory eq '')
5335                                  ? ''
5336                                  : "$directory/");
5337     }
5339     return $r;
5342 # Rewrite a single C++ source file.
5343 sub lang_cxx_rewrite
5345     return &lang_sub_obj;
5348 # Rewrite a single header file.
5349 sub lang_header_rewrite
5351     # Header files are simply ignored.
5352     return $LANG_IGNORE;
5355 # Rewrite a single yacc file.
5356 sub lang_yacc_rewrite
5358     my ($directory, $base, $ext) = @_;
5360     my $r = &lang_sub_obj;
5361     (my $newext = $ext) =~ tr/y/c/;
5362     return ($r, $newext);
5365 # Rewrite a single yacc++ file.
5366 sub lang_yaccxx_rewrite
5368     my ($directory, $base, $ext) = @_;
5370     my $r = &lang_sub_obj;
5371     (my $newext = $ext) =~ tr/y/c/;
5372     return ($r, $newext);
5375 # Rewrite a single lex file.
5376 sub lang_lex_rewrite
5378     my ($directory, $base, $ext) = @_;
5380     my $r = &lang_sub_obj;
5381     (my $newext = $ext) =~ tr/l/c/;
5382     return ($r, $newext);
5385 # Rewrite a single lex++ file.
5386 sub lang_lexxx_rewrite
5388     my ($directory, $base, $ext) = @_;
5390     my $r = &lang_sub_obj;
5391     (my $newext = $ext) =~ tr/l/c/;
5392     return ($r, $newext);
5395 # Rewrite a single assembly file.
5396 sub lang_asm_rewrite
5398     return &lang_sub_obj;
5401 # Rewrite a single Fortran 77 file.
5402 sub lang_f77_rewrite
5404     return $LANG_PROCESS;
5407 # Rewrite a single preprocessed Fortran 77 file.
5408 sub lang_ppf77_rewrite
5410     return $LANG_PROCESS;
5413 # Rewrite a single ratfor file.
5414 sub lang_ratfor_rewrite
5416     return $LANG_PROCESS;
5419 # Rewrite a single Objective C file.
5420 sub lang_objc_rewrite
5422     return &lang_sub_obj;
5425 # Rewrite a single Java file.
5426 sub lang_java_rewrite
5428     return $LANG_SUBDIR;
5431 # The lang_X_finish functions are called after all source file
5432 # processing is done.  Each should handle defining rules for the
5433 # language, etc.  A finish function is only called if a source file of
5434 # the appropriate type has been seen.
5436 sub lang_c_finish
5438     # Push all libobjs files onto de_ansi_files.  We actually only
5439     # push files which exist in the current directory, and which are
5440     # genuine source files.
5441     foreach my $file (keys %libsources)
5442     {
5443         if ($file =~ /^(.*)\.[cly]$/ && -f "$relative_dir/$file")
5444         {
5445             $de_ansi_files{$1} = (($relative_dir eq '.' || $relative_dir eq '')
5446                                   ? ''
5447                                   : "$relative_dir/");
5448         }
5449     }
5451     if (defined $options{'ansi2knr'} && keys %de_ansi_files)
5452     {
5453         # Make all _.c files depend on their corresponding .c files.
5454         my @objects;
5455         foreach my $base (sort keys %de_ansi_files)
5456         {
5457             # Each _.c file must depend on ansi2knr; otherwise it
5458             # might be used in a parallel build before it is built.
5459             # We need to support files in the srcdir and in the build
5460             # dir (because these files might be auto-generated.  But
5461             # we can't use $< -- some makes only define $< during a
5462             # suffix rule.
5463             my $ansfile = $de_ansi_files{$base} . $base . '.c';
5464             $output_rules .= ($base . "_.c: $ansfile \$(ANSI2KNR)\n\t"
5465                               . '$(CPP) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) '
5466                               . '`if test -f $(srcdir)/' . $ansfile
5467                               . '; then echo $(srcdir)/' . $ansfile
5468                               . '; else echo ' . $ansfile . '; fi` '
5469                               . "| sed 's/^# \\([0-9]\\)/#line \\1/' "
5470                               . '| $(ANSI2KNR) > ' . $base . "_.c"
5471                               # If ansi2knr fails then we shouldn't
5472                               # create the _.c file
5473                               . " || rm -f ${base}_.c\n");
5474             push (@objects, $base . '_.$(OBJEXT)');
5475             push (@objects, $base . '_.lo')
5476               if $seen_libtool;
5477         }
5479         # Make all _.o (and _.lo) files depend on ansi2knr.
5480         # Use a sneaky little hack to make it print nicely.
5481         &pretty_print_rule ('', '', @objects, ':', '$(ANSI2KNR)');
5482     }
5485 # This is a yacc helper which is called whenever we have decided to
5486 # compile a yacc file.
5487 sub lang_yacc_target_hook
5489     my ($self, $aggregate, $output, $input) = @_;
5491     my $flag = $aggregate . "_YFLAGS";
5492     if ((variable_defined ($flag)
5493          && &variable_value ($flag) =~ /$DASH_D_PATTERN/o)
5494         || (variable_defined ('YFLAGS')
5495             && &variable_value ('YFLAGS') =~ /$DASH_D_PATTERN/o))
5496     {
5497         (my $output_base = $output) =~ s/$KNOWN_EXTENSIONS_PATTERN$//;
5498         my $header = $output_base . '.h';
5500         # Found a `-d' that applies to the compilation of this file.
5501         # Add a dependency for the generated header file, and arrange
5502         # for that file to be included in the distribution.
5503         # FIXME: this fails for `nodist_*_SOURCES'.
5504         $output_rules .= ("${header}: $output\n"
5505                           # Recover from removal of $header
5506                           . "\t\@if test ! -f \$@; then \\\n"
5507                           . "\t  rm -f $output; \\\n"
5508                           . "\t  \$(MAKE) $output; \\\n"
5509                           . "\telse :; fi\n");
5510         &push_dist_common ($header);
5511         # If the files are built in the build directory, then we want
5512         # to remove them with `make clean'.  If they are in srcdir
5513         # they shouldn't be touched.  However, we can't determine this
5514         # statically, and the GNU rules say that yacc/lex output files
5515         # should be removed by maintainer-clean.  So that's what we
5516         # do.
5517         push (@maintainer_clean_files, $header);
5518     }
5519     # Erase $OUTPUT on `make maintainer-clean' (by GNU standards).
5520     # See the comment above for $HEADER.
5521     push (@maintainer_clean_files, $output);
5524 # This is a lex helper which is called whenever we have decided to
5525 # compile a lex file.
5526 sub lang_lex_target_hook
5528     my ($self, $aggregate, $output, $input) = @_;
5529     # If the files are built in the build directory, then we want to
5530     # remove them with `make clean'.  If they are in srcdir they
5531     # shouldn't be touched.  However, we can't determine this
5532     # statically, and the GNU rules say that yacc/lex output files
5533     # should be removed by maintainer-clean.  So that's what we do.
5534     push (@maintainer_clean_files, $output);
5537 # This is a helper for both lex and yacc.
5538 sub yacc_lex_finish_helper
5540     return if defined $language_scratch{'lex-yacc-done'};
5541     $language_scratch{'lex-yacc-done'} = 1;
5543     # If there is more than one distinct yacc (resp lex) source file
5544     # in a given directory, then the `ylwrap' program is required to
5545     # allow parallel builds to work correctly.  FIXME: for now, no
5546     # line number.
5547     require_conf_file ($configure_ac, FOREIGN, 'ylwrap');
5548     if ($config_aux_dir_set_in_configure_in)
5549     {
5550         &define_variable ('YLWRAP', $config_aux_dir . "/ylwrap");
5551     }
5552     else
5553     {
5554         &define_variable ('YLWRAP', '$(top_srcdir)/ylwrap');
5555     }
5558 sub lang_yacc_finish
5560     return if defined $language_scratch{'yacc-done'};
5561     $language_scratch{'yacc-done'} = 1;
5563     macro_error ('YACCFLAGS',
5564                  "`YACCFLAGS' obsolete; use `YFLAGS' instead")
5565       if variable_defined ('YACCFLAGS');
5567     if (count_files_for_language ('yacc') > 1)
5568     {
5569         &yacc_lex_finish_helper;
5570     }
5574 sub lang_lex_finish
5576     return if defined $language_scratch{'lex-done'};
5577     $language_scratch{'lex-done'} = 1;
5579     am_error ("lex source seen but `AM_PROG_LEX' not in `$configure_ac'")
5580       unless $seen_prog_lex;
5582     if (count_files_for_language ('lex') > 1)
5583     {
5584         &yacc_lex_finish_helper;
5585     }
5589 # Given a hash table of linker names, pick the name that has the most
5590 # precedence.  This is lame, but something has to have global
5591 # knowledge in order to eliminate the conflict.  Add more linkers as
5592 # required.
5593 sub resolve_linker
5595     my (%linkers) = @_;
5597     foreach my $l (qw(GCJLINK CXXLINK F77LINK OBJCLINK))
5598     {
5599         return $l if defined $linkers{$l};
5600     }
5601     return 'LINK';
5604 # Called to indicate that an extension was used.
5605 sub saw_extension
5607     my ($ext) = @_;
5608     if (! defined $extension_seen{$ext})
5609     {
5610         $extension_seen{$ext} = 1;
5611     }
5612     else
5613     {
5614         ++$extension_seen{$ext};
5615     }
5618 # Return the number of files seen for a given language.  Knows about
5619 # special cases we care about.  FIXME: this is hideous.  We need
5620 # something that involves real language objects.  For instance yacc
5621 # and yaccxx could both derive from a common yacc class which would
5622 # know about the strange ylwrap requirement.  (Or better yet we could
5623 # just not support legacy yacc!)
5624 sub count_files_for_language
5626     my ($name) = @_;
5628     my @names;
5629     if ($name eq 'yacc' || $name eq 'yaccxx')
5630     {
5631         @names = ('yacc', 'yaccxx');
5632     }
5633     elsif ($name eq 'lex' || $name eq 'lexxx')
5634     {
5635         @names = ('lex', 'lexxx');
5636     }
5637     else
5638     {
5639         @names = ($name);
5640     }
5642     my $r = 0;
5643     foreach $name (@names)
5644     {
5645         my $lang = $languages{$name};
5646         foreach my $ext (@{$lang->extensions})
5647         {
5648             $r += $extension_seen{$ext}
5649                 if defined $extension_seen{$ext};
5650         }
5651     }
5653     return $r
5656 # Called to ask whether source files have been seen . If HEADERS is 1,
5657 # headers can be included.
5658 sub saw_sources_p
5660     my ($headers) = @_;
5662     # count all the sources
5663     my $count = 0;
5664     foreach my $val (values %extension_seen)
5665     {
5666         $count += $val;
5667     }
5669     if (!$headers)
5670     {
5671         $count -= count_files_for_language ('header');
5672     }
5674     return $count > 0;
5678 # register_language (%ATTRIBUTE)
5679 # ------------------------------
5680 # Register a single language.
5681 # Each %ATTRIBUTE is of the form ATTRIBUTE => VALUE.
5682 sub register_language (%)
5684     my (%option) = @_;
5686     # Set the defaults.
5687     $option{'ansi'} = 0
5688       unless defined $option{'ansi'};
5689     $option{'autodep'} = 'no'
5690       unless defined $option{'autodep'};
5691     $option{'linker'} = ''
5692       unless defined $option{'linker'};
5693     $option{'define_flag'} = 1
5694       unless defined $option{'define_flag'};
5696     my $lang = new Language (%option);
5698     # Fill indexes.
5699     grep ($extension_map{$_} = $lang->name, @{$lang->extensions});
5700     $languages{$lang->name} = $lang;
5702     # Update the pattern of known extensions.
5703     accept_extensions (@{$lang->extensions});
5706 # derive_suffix ($EXT, $OBJ)
5707 # --------------------------
5708 # This function is used to find a path from a user-specified suffix $EXT
5709 # to $OBJ or to some other suffix we recognize internally, eg `cc'.
5710 sub derive_suffix ($$)
5712     my ($source_ext, $obj) = @_;
5714     while (! $extension_map{$source_ext}
5715            && $source_ext ne $obj
5716            && defined $suffix_rules{$source_ext})
5717     {
5718         $source_ext = $suffix_rules{$source_ext};
5719     }
5721     return $source_ext;
5725 ################################################################
5727 # Pretty-print something.  HEAD is what should be printed at the
5728 # beginning of the first line, FILL is what should be printed at the
5729 # beginning of every subsequent line.
5730 sub pretty_print_internal
5732     my ($head, $fill, @values) = @_;
5734     my $column = length ($head);
5735     my $result = $head;
5737     # Fill length is number of characters.  However, each Tab
5738     # character counts for eight.  So we count the number of Tabs and
5739     # multiply by 7.
5740     my $fill_length = length ($fill);
5741     $fill_length += 7 * ($fill =~ tr/\t/\t/d);
5743     foreach (@values)
5744     {
5745         # "71" because we also print a space.
5746         if ($column + length ($_) > 71)
5747         {
5748             $result .= " \\\n" . $fill;
5749             $column = $fill_length;
5750         }
5751         $result .= ' ' if $result =~ /\S\z/;
5752         $result .= $_;
5753         $column += length ($_) + 1;
5754     }
5756     $result .= "\n";
5757     return $result;
5760 # Pretty-print something and append to output_vars.
5761 sub pretty_print
5763     $output_vars .= &pretty_print_internal (@_);
5766 # Pretty-print something and append to output_rules.
5767 sub pretty_print_rule
5769     $output_rules .= &pretty_print_internal (@_);
5773 ################################################################
5776 # $STRING
5777 # &conditional_string(@COND-STACK)
5778 # --------------------------------
5779 # Build a string which denotes the conditional in @COND-STACK.  Some
5780 # simplifications are done: `TRUE' entries are elided, and any `FALSE'
5781 # entry results in a return of `FALSE'.
5782 sub conditional_string
5784   my (@stack) = @_;
5786   if (grep (/^FALSE$/, @stack))
5787     {
5788       return 'FALSE';
5789     }
5790   else
5791     {
5792       return join (' ', uniq sort grep (!/^TRUE$/, @stack));
5793     }
5797 # $BOOLEAN
5798 # &conditional_true_when ($COND, $WHEN)
5799 # -------------------------------------
5800 # See if a conditional is true.  Both arguments are conditional
5801 # strings.  This returns true if the first conditional is true when
5802 # the second conditional is true.
5803 # For instance with $COND = `BAR FOO', and $WHEN = `BAR BAZ FOO',
5804 # obviously return 1, and 0 when, for instance, $WHEN = `FOO'.
5805 sub conditional_true_when ($$)
5807     my ($cond, $when) = @_;
5809     # Make a hash holding all the values from $WHEN.
5810     my %cond_vals = map { $_ => 1 } split (' ', $when);
5812     # Check each component of $cond, which looks `COND1 COND2'.
5813     foreach my $comp (split (' ', $cond))
5814     {
5815         # TRUE is always true.
5816         next if $comp eq 'TRUE';
5817         return 0 if ! defined $cond_vals{$comp};
5818     }
5820     return 1;
5824 # $BOOLEAN
5825 # &conditional_is_redundant ($COND, @WHENS)
5826 # ----------------------------------------
5827 # Determine whether $COND is redundant with respect to @WHENS.
5829 # Returns true if $COND is true for any of the conditions in @WHENS.
5831 # If there are no @WHENS, then behave as if @WHENS contained a single empty
5832 # condition.
5833 sub conditional_is_redundant ($@)
5835     my ($cond, @whens) = @_;
5837     if (@whens == 0)
5838     {
5839         return 1 if conditional_true_when ($cond, "");
5840     }
5841     else
5842     {
5843         foreach my $when (@whens)
5844         {
5845             return 1 if conditional_true_when ($cond, $when);
5846         }
5847     }
5849     return 0;
5853 # $NEGATION
5854 # condition_negate ($COND)
5855 # ------------------------
5856 sub condition_negate ($)
5858     my ($cond) = @_;
5860     $cond =~ s/TRUE$/TRUEO/;
5861     $cond =~ s/FALSE$/TRUE/;
5862     $cond =~ s/TRUEO$/FALSE/;
5864     return $cond;
5868 # Compare condition names.
5869 # Issue them in alphabetical order, foo_TRUE before foo_FALSE.
5870 sub by_condition
5872     # Be careful we might be comparing `' or `#'.
5873     $a =~ /^(.*)_(TRUE|FALSE)$/;
5874     my ($aname, $abool) = ($1 || '', $2 || '');
5875     $b =~ /^(.*)_(TRUE|FALSE)$/;
5876     my ($bname, $bbool) = ($1 || '', $2 || '');
5877     return ($aname cmp $bname
5878             # Don't bother with IFs, given that TRUE is after FALSE
5879             # just cmp in the reverse order.
5880             || $bbool cmp $abool
5881             # Just in case...
5882             || $a cmp $b);
5886 # &make_condition (@CONDITIONS)
5887 # -----------------------------
5888 # Transform a list of conditions (themselves can be an internal list
5889 # of conditions, e.g., @CONDITIONS = ('cond1 cond2', 'cond3')) into a
5890 # Make conditional (a pattern for AC_SUBST).
5891 # Correctly returns the empty string when there are no conditions.
5892 sub make_condition
5894     my $res = conditional_string (@_);
5896     # There are no conditions.
5897     if ($res eq '')
5898       {
5899         # Nothing to do.
5900       }
5901     # It's impossible.
5902     elsif ($res eq 'FALSE')
5903       {
5904         $res = '#';
5905       }
5906     # Build it.
5907     else
5908       {
5909         $res = '@' . $res . '@';
5910         $res =~ s/ /@@/g;
5911       }
5913     return $res;
5918 ## ------------------------------ ##
5919 ## Handling the condition stack.  ##
5920 ## ------------------------------ ##
5923 # $COND_STRING
5924 # cond_stack_if ($NEGATE, $COND, $WHERE)
5925 # --------------------------------------
5926 sub cond_stack_if ($$$)
5928   my ($negate, $cond, $where) = @_;
5930   file_error ($where, "$cond does not appear in AM_CONDITIONAL")
5931     if ! $configure_cond{$cond} && $cond !~ /^TRUE|FALSE$/;
5933   $cond = "${cond}_TRUE"
5934     unless $cond =~ /^TRUE|FALSE$/;
5935   $cond = condition_negate ($cond)
5936     if $negate;
5938   push (@cond_stack, $cond);
5940   return conditional_string (@cond_stack);
5944 # $COND_STRING
5945 # cond_stack_else ($NEGATE, $COND, $WHERE)
5946 # ----------------------------------------
5947 sub cond_stack_else ($$$)
5949   my ($negate, $cond, $where) = @_;
5951   if (! @cond_stack)
5952     {
5953       file_error ($where, "else without if");
5954       return;
5955     }
5957   $cond_stack[$#cond_stack] = condition_negate ($cond_stack[$#cond_stack]);
5959   # If $COND is given, check against it.
5960   if (defined $cond)
5961     {
5962       $cond = "${cond}_TRUE"
5963         unless $cond =~ /^TRUE|FALSE$/;
5964       $cond = condition_negate ($cond)
5965         if $negate;
5967       file_error ($where,
5968                   "else reminder ($negate$cond) incompatible with "
5969                   . "current conditional: $cond_stack[$#cond_stack]")
5970         if $cond_stack[$#cond_stack] ne $cond;
5971     }
5973   return conditional_string (@cond_stack);
5977 # $COND_STRING
5978 # cond_stack_endif ($NEGATE, $COND, $WHERE)
5979 # -----------------------------------------
5980 sub cond_stack_endif ($$$)
5982   my ($negate, $cond, $where) = @_;
5983   my $old_cond;
5985   if (! @cond_stack)
5986     {
5987       file_error ($where, "endif without if: $negate$cond");
5988       return;
5989     }
5992   # If $COND is given, check against it.
5993   if (defined $cond)
5994     {
5995       $cond = "${cond}_TRUE"
5996         unless $cond =~ /^TRUE|FALSE$/;
5997       $cond = condition_negate ($cond)
5998         if $negate;
6000       file_error ($where,
6001                   "endif reminder ($negate$cond) incompatible with "
6002                   . "current conditional: $cond_stack[$#cond_stack]")
6003         if $cond_stack[$#cond_stack] ne $cond;
6004     }
6006   pop @cond_stack;
6008   return conditional_string (@cond_stack);
6015 ## ------------------------ ##
6016 ## Handling the variables.  ##
6017 ## ------------------------ ##
6020 # check_ambiguous_conditional ($VAR, $COND)
6021 # -----------------------------------------
6022 # Check for an ambiguous conditional.  This is called when a variable
6023 # is being defined conditionally.  If we already know about a
6024 # definition that is true under the same conditions, then we have an
6025 # ambiguity.
6026 sub check_ambiguous_conditional ($$)
6028     my ($var, $cond) = @_;
6029     my $message = conditional_ambiguous_p ($var, $cond);
6030     if ($message ne '')
6031     {
6032         macro_error ($var, $message);
6033         macro_dump ($var);
6034     }
6037 # $STRING
6038 # conditional_ambiguous_p ($VAR, $COND)
6039 # -------------------------------------
6040 # Check for an ambiguous conditional.  Return an error message if we
6041 # have one, the empty string otherwise.
6042 sub conditional_ambiguous_p ($$)
6044     my ($var, $cond) = @_;
6045     foreach my $vcond (keys %{$var_value{$var}})
6046     {
6047        my $message;
6048        if ($vcond eq $cond)
6049        {
6050            return "$var multiply defined in condition $cond";
6051        }
6052        elsif (&conditional_true_when ($vcond, $cond))
6053        {
6054          return ("$var was already defined in condition $vcond, "
6055                  . "which implies condition $cond");
6056        }
6057        elsif (&conditional_true_when ($cond, $vcond))
6058        {
6059            return ("$var was already defined in condition $vcond, "
6060                    . "which is implied by condition $cond");
6061        }
6062    }
6064     return '';
6068 # &macro_define($VAR, $VAR_IS_AM, $TYPE, $COND, $VALUE, $WHERE)
6069 # -------------------------------------------------------------
6070 # The $VAR can go from Automake to user, but not the converse.
6071 sub macro_define ($$$$$$)
6073   my ($var, $var_is_am, $type, $cond, $value, $where) = @_;
6075   file_error ($where, "bad macro name `$var'")
6076     if $var !~ /$MACRO_PATTERN/o;
6078   $cond ||= 'TRUE';
6080   # An Automake variable must be consistently defined with the same
6081   # sign by Automake.  A user variable must be set by either `=' or
6082   # `:=', and later promoted to `+='.
6083   if ($var_is_am)
6084     {
6085       if (defined $var_type{$var} && $var_type{$var} ne $type)
6086         {
6087           file_error ($where,
6088                       ("$var was set with `$var_type{$var}=' "
6089                        . "and is now set with `$type='"));
6090         }
6091     }
6092   else
6093     {
6094       if (!defined $var_type{$var} && $type eq '+')
6095         {
6096           file_error ($where, "$var must be set with `=' before using `+='");
6097         }
6098     }
6099   $var_type{$var} = $type;
6101   # When adding, since we rewrite, don't try to preserve the
6102   # Automake continuation backslashes.
6103   $value =~ s/\\$//mg
6104     if $type eq '+' && $var_is_am;
6106   # Differentiate the first assignment (including with `+=').
6107   if ($type eq '+' && defined $var_value{$var}{$cond})
6108     {
6109       if (chomp $var_value{$var}{$cond})
6110         {
6111           # Insert a backslash before a trailing newline.
6112           $var_value{$var}{$cond} .= "\\\n";
6113         }
6114       elsif ($var_value{$var}{$cond})
6115         {
6116           # Insert a separator.
6117           $var_value{$var}{$cond} .= ' ';
6118         }
6119        $var_value{$var}{$cond} .= $value;
6120     }
6121   else
6122     {
6123       # The first assignment to a macro sets its location.  Ideally I
6124       # suppose we would associate line numbers with random bits of text.
6125       # FIXME: We sometimes redefine some variables, but we want to keep
6126       # the original location.  More subs are needed to handle
6127       # properly variables.  Once this done, remove this hack.
6128       $var_location{$var} = $where
6129         unless defined $var_location{$var};
6131       # If Automake tries to override a value specified by the user,
6132       # just don't let it do.
6133       if (defined $var_value{$var}{$cond} && !$var_is_am{$var} && $var_is_am)
6134         {
6135           if ($verbose)
6136             {
6137               print STDERR "$me: refusing to override the user definition of:\n";
6138               macro_dump ($var);
6139               print STDERR "$me: with `$cond' => `$value'\n";
6140             }
6141         }
6142       else
6143         {
6144           # There must be no previous value unless the user is redefining
6145           # an Automake variable or an AC_SUBST variable for an existing
6146           # condition.
6147           check_ambiguous_conditional ($var, $cond)
6148             unless (($var_is_am{$var} && !$var_is_am
6149                      || exists $configure_vars{$var})
6150                     && exists $var_value{$var}{$cond});
6152           $var_value{$var}{$cond} = $value;
6153         }
6154     }
6156   # An Automake variable can be given to the user, but not the converse.
6157   if (! defined $var_is_am{$var} || !$var_is_am)
6158     {
6159       $var_is_am{$var} = $var_is_am;
6160     }
6162   # Call var_VAR_trigger if it's defined.
6163   # This hook helps to update some internal state *while*
6164   # parsing the file.  For instance the handling of SUFFIXES
6165   # requires this (see var_SUFFIXES_trigger).
6166   my $var_trigger = "var_${var}_trigger";
6167   &$var_trigger($type, $value) if defined &$var_trigger;
6171 # &macro_delete ($VAR, [@CONDS])
6172 # ------------------------------
6173 # Forget about $VAR under the conditions @CONDS, or completely if
6174 # @CONDS is empty.
6175 sub macro_delete ($@)
6177   my ($var, @conds) = @_;
6179   if (!@conds)
6180     {
6181       delete $var_value{$var};
6182       delete $var_location{$var};
6183       delete $var_is_am{$var};
6184       delete $var_comment{$var};
6185       delete $var_type{$var};
6186     }
6187   else
6188     {
6189       foreach my $cond (@conds)
6190         {
6191           delete $var_value{$var}{$cond};
6192         }
6193     }
6197 # &macro_dump ($VAR)
6198 # ------------------
6199 sub macro_dump ($)
6201   my ($var) = @_;
6203   if (!exists $var_value{$var})
6204     {
6205       print STDERR "  $var does not exist\n";
6206     }
6207   else
6208     {
6209       my $var_is_am = $var_is_am{$var} ? "Automake" : "User";
6210       my $where = (defined $var_location{$var}
6211                    ? $var_location{$var} : "undefined");
6212       print STDERR "$var_comment{$var}"
6213         if defined $var_comment{$var};
6214       print STDERR "  $var ($var_is_am, where = $where) $var_type{$var}=\n";
6215       print STDERR "  {\n";
6216       foreach my $vcond (sort by_condition keys %{$var_value{$var}})
6217         {
6218           print STDERR "    $vcond => $var_value{$var}{$vcond}\n";
6219         }
6220       print STDERR "  }\n";
6221     }
6225 # &macros_dump ()
6226 # ---------------
6227 sub macros_dump ()
6229   my ($var) = @_;
6231   print STDERR "%var_value =\n";
6232   print STDERR "{\n";
6233   foreach my $var (sort (keys %var_value))
6234     {
6235       macro_dump ($var);
6236     }
6237   print STDERR "}\n";
6241 # $BOOLEAN
6242 # variable_defined ($VAR, [$COND])
6243 # ---------------------------------
6244 # See if a variable exists.  $VAR is the variable name, and $COND is
6245 # the condition which we should check.  If no condition is given, we
6246 # currently return true if the variable is defined under any
6247 # condition.
6248 sub variable_defined ($;$)
6250     my ($var, $cond) = @_;
6252     # Unfortunately we can't just check for $var_value{VAR}{COND}
6253     # as this would make perl create $condition{VAR}, which we
6254     # don't want.
6255     if (!exists $var_value{$var})
6256       {
6257         macro_error ($var, "`$var' is a target; expected a variable")
6258           if defined $targets{$var};
6259         # The variable is not defined
6260         return 0;
6261       }
6263     # The variable is not defined for the given condition.
6264     return 0
6265       if $cond && !exists $var_value{$var}{$cond};
6267     # Even a var_value examination is good enough for us.  FIXME:
6268     # really should maintain examined status on a per-condition basis.
6269     $content_seen{$var} = 1;
6270     return 1;
6274 # $BOOLEAN
6275 # variable_assert ($VAR, $WHERE)
6276 # ------------------------------
6277 # Make sure a variable exists.  $VAR is the variable name, and $WHERE
6278 # is the name of a macro which refers to $VAR.
6279 sub variable_assert ($$)
6281   my ($var, $where) = @_;
6283   return 1
6284     if variable_defined $var;
6286   macro_error ($where, "variable `$var' not defined");
6288   return 0;
6292 # Mark a variable as examined.
6293 sub examine_variable
6295     my ($var) = @_;
6296     variable_defined ($var);
6300 # &variable_conditions_recursive ($VAR)
6301 # -------------------------------------
6302 # Return the set of conditions for which a variable is defined.
6304 # If the variable is not defined conditionally, and is not defined in
6305 # terms of any variables which are defined conditionally, then this
6306 # returns the empty list.
6308 # If the variable is defined conditionally, but is not defined in
6309 # terms of any variables which are defined conditionally, then this
6310 # returns the list of conditions for which the variable is defined.
6312 # If the variable is defined in terms of any variables which are
6313 # defined conditionally, then this returns a full set of permutations
6314 # of the subvariable conditions.  For example, if the variable is
6315 # defined in terms of a variable which is defined for COND_TRUE,
6316 # then this returns both COND_TRUE and COND_FALSE.  This is
6317 # because we will need to define the variable under both conditions.
6318 sub variable_conditions_recursive ($)
6320     my ($var) = @_;
6322     %vars_scanned = ();
6324     my @new_conds = variable_conditions_recursive_sub ($var, '');
6325     # Now we want to return all permutations of the subvariable
6326     # conditions.
6327     my %allconds = ();
6328     foreach my $item (@new_conds)
6329     {
6330         foreach (split (' ', $item))
6331         {
6332             s/^(.*)_(TRUE|FALSE)$/$1_TRUE/;
6333             $allconds{$_} = 1;
6334         }
6335     }
6336     @new_conds = variable_conditions_permutations (sort keys %allconds);
6338     my %uniqify;
6339     foreach my $cond (@new_conds)
6340     {
6341         my $reduce = variable_conditions_reduce (split (' ', $cond));
6342         next
6343             if $reduce eq 'FALSE';
6344         $uniqify{$cond} = 1;
6345     }
6347     # Note we cannot just do `return sort keys %uniqify', because this
6348     # function is sometimes used in a scalar context.
6349     my @uniq_list = sort by_condition keys %uniqify;
6350     return @uniq_list;
6354 # @CONDS
6355 # variable_conditions ($VAR)
6356 # --------------------------
6357 # Get the list of conditions that a variable is defined with, without
6358 # recursing through the conditions of any subvariables.
6359 # Argument is $VAR: the variable to get the conditions of.
6360 # Returns the list of conditions.
6361 sub variable_conditions ($)
6363     my ($var) = @_;
6364     my @conds = keys %{$var_value{$var}};
6365     return sort by_condition @conds;
6369 # $BOOLEAN
6370 # &variable_conditionally_defined ($VAR)
6371 # --------------------------------------
6372 sub variable_conditionally_defined ($)
6374     my ($var) = @_;
6375     foreach my $cond (variable_conditions_recursive ($var))
6376       {
6377         return 1
6378           unless $cond =~ /^TRUE|FALSE$/;
6379       }
6380     return 0;
6385 # &variable_conditions_recursive_sub ($VAR, $PARENT)
6386 # -------------------------------------------------------
6387 # A subroutine of variable_conditions_recursive.  This returns all the
6388 # conditions of $VAR, including those of any sub-variables.
6389 sub variable_conditions_recursive_sub
6391     my ($var, $parent) = @_;
6392     my @new_conds = ();
6394     if (defined $vars_scanned{$var})
6395     {
6396         macro_error ($parent, "variable `$var' recursively defined");
6397         return ();
6398     }
6399     $vars_scanned{$var} = 1;
6401     my @this_conds = ();
6402     # Examine every condition under which $VAR is defined.
6403     foreach my $vcond (keys %{$var_value{$var}})
6404     {
6405         push (@this_conds, $vcond);
6407         # If $VAR references some other variable, then compute the
6408         # conditions for that subvariable.
6409         my @subvar_conds = ();
6410         foreach (split (' ', $var_value{$var}{$vcond}))
6411         {
6412             # If a comment seen, just leave.
6413             last if /^#/;
6415             # Handle variable substitutions.
6416             if (/^\$\{(.*)\}$/ || /^\$\((.*)\)$/)
6417             {
6418                 my $varname = $1;
6419                 if ($varname =~ /$SUBST_REF_PATTERN/o)
6420                 {
6421                     $varname = $1;
6422                 }
6425                 # Here we compute all the conditions under which the
6426                 # subvariable is defined.  Then we go through and add
6427                 # $VCOND to each.
6428                 my @svc = variable_conditions_recursive_sub ($varname, $var);
6429                 foreach my $item (@svc)
6430                 {
6431                     my $val = conditional_string ($vcond, split (' ', $item));
6432                     $val ||= 'TRUE';
6433                     push (@subvar_conds, $val);
6434                 }
6435             }
6436         }
6438         # If there are no conditional subvariables, then we want to
6439         # return this condition.  Otherwise, we want to return the
6440         # permutations of the subvariables, taking into account the
6441         # conditions of $VAR.
6442         if (! @subvar_conds)
6443         {
6444             push (@new_conds, $vcond);
6445         }
6446         else
6447         {
6448             push (@new_conds, variable_conditions_reduce (@subvar_conds));
6449         }
6450     }
6452     # Unset our entry in vars_scanned.  We only care about recursive
6453     # definitions.
6454     delete $vars_scanned{$var};
6456     # If we are being called on behalf of another variable, we need to
6457     # return all possible permutations of the conditions.  We have
6458     # already handled everything in @this_conds along with their
6459     # subvariables.  We now need to add any permutations that are not
6460     # in @this_conds.
6461     foreach my $this_cond (@this_conds)
6462     {
6463         my @perms =
6464             variable_conditions_permutations (split (' ', $this_cond));
6465         foreach my $perm (@perms)
6466         {
6467             my $ok = 1;
6468             foreach my $scan (@this_conds)
6469             {
6470                 if (&conditional_true_when ($perm, $scan)
6471                     || &conditional_true_when ($scan, $perm))
6472                 {
6473                     $ok = 0;
6474                     last;
6475                 }
6476             }
6477             next if ! $ok;
6479             # This permutation was not already handled, and is valid
6480             # for the parents.
6481             push (@new_conds, $perm);
6482         }
6483     }
6485     return @new_conds;
6489 # Filter a list of conditionals so that only the exclusive ones are
6490 # retained.  For example, if both `COND1_TRUE COND2_TRUE' and
6491 # `COND1_TRUE' are in the list, discard the latter.
6492 # If the list is empty, return TRUE
6493 sub variable_conditions_reduce
6495     my (@conds) = @_;
6496     my @ret = ();
6497     my $cond;
6498     while(@conds > 0)
6499     {
6500         $cond = shift(@conds);
6502         # FALSE is absorbent.
6503         return 'FALSE'
6504           if $cond eq 'FALSE';
6506         if (!conditional_is_redundant ($cond, @ret, @conds))
6507           {
6508             push (@ret, $cond);
6509           }
6510     }
6512     return "TRUE" if @ret == 0;
6513     return @ret;
6516 # @CONDS
6517 # invert_conditions (@CONDS)
6518 # --------------------------
6519 # Invert a list of conditionals.  Returns a set of conditionals which
6520 # are never true for any of the input conditionals, and when taken
6521 # together with the input conditionals cover all possible cases.
6523 # For example: invert_conditions("A_TRUE B_TRUE", "A_FALSE B_FALSE") will
6524 # return ("A_FALSE B_TRUE", "A_TRUE B_FALSE")
6525 sub invert_conditions
6527     my (@conds) = @_;
6529     my @notconds = ();
6530     foreach my $cond (@conds)
6531     {
6532         foreach my $perm (variable_conditions_permutations (split(' ', $cond)))
6533         {
6534             push @notconds, $perm
6535                     if ! conditional_is_redundant ($perm, @conds);
6536         }
6537     }
6538     return variable_conditions_reduce (@notconds);
6541 # Return a list of permutations of a conditional string.
6542 sub variable_conditions_permutations
6544     my (@comps) = @_;
6545     return ()
6546         if ! @comps;
6547     my $comp = shift (@comps);
6548     return variable_conditions_permutations (@comps)
6549         if $comp eq '';
6550     my $neg = condition_negate ($comp);
6552     my @ret;
6553     foreach my $sub (variable_conditions_permutations (@comps))
6554     {
6555         push (@ret, "$comp $sub");
6556         push (@ret, "$neg $sub");
6557     }
6558     if (! @ret)
6559     {
6560         push (@ret, $comp);
6561         push (@ret, $neg);
6562     }
6563     return @ret;
6567 # $BOOL
6568 # &check_variable_defined_unconditionally($VAR, $PARENT)
6569 # ------------------------------------------------------
6570 # Warn if a variable is conditionally defined.  This is called if we
6571 # are using the value of a variable.
6572 sub check_variable_defined_unconditionally ($$)
6574     my ($var, $parent) = @_;
6575     foreach my $cond (keys %{$var_value{$var}})
6576     {
6577         next
6578           if $cond =~ /^TRUE|FALSE$/;
6580         if ($parent)
6581         {
6582             macro_error ($parent,
6583                          "warning: automake does not support conditional definition of $var in $parent");
6584         }
6585         else
6586         {
6587             macro_error ($parent,
6588                          "warning: automake does not support $var being defined conditionally");
6589         }
6590     }
6594 # Get the TRUE value of a variable, warn if the variable is
6595 # conditionally defined.
6596 sub variable_value
6598     my ($var) = @_;
6599     &check_variable_defined_unconditionally ($var);
6600     return $var_value{$var}{'TRUE'};
6604 # @VALUES
6605 # &value_to_list ($VAR, $VAL, $COND)
6606 # ----------------------------------
6607 # Convert a variable value to a list, split as whitespace.  This will
6608 # recursively follow $(...) and ${...} inclusions.  It preserves @...@
6609 # substitutions.
6611 # If COND is 'all', then all values under all conditions should be
6612 # returned; if COND is a particular condition (all conditions are
6613 # surrounded by @...@) then only the value for that condition should
6614 # be returned; otherwise, warn if VAR is conditionally defined.
6615 # SCANNED is a global hash listing whose keys are all the variables
6616 # already scanned; it is an error to rescan a variable.
6617 sub value_to_list ($$$)
6619     my ($var, $val, $cond) = @_;
6620     my @result;
6622     # Strip backslashes
6623     $val =~ s/\\(\n|$)/ /g;
6625     foreach (split (' ', $val))
6626     {
6627         # If a comment seen, just leave.
6628         last if /^#/;
6630         # Handle variable substitutions.
6631         if (/^\$\{([^}]*)\}$/ || /^\$\(([^)]*)\)$/)
6632         {
6633             my $varname = $1;
6635             # If the user uses a losing variable name, just ignore it.
6636             # This isn't ideal, but people have requested it.
6637             next if ($varname =~ /\@.*\@/);
6639             my ($from, $to);
6640             my @temp_list;
6641             if ($varname =~ /$SUBST_REF_PATTERN/o)
6642             {
6643                 $varname = $1;
6644                 $to = $3;
6645                 $from = quotemeta $2;
6646             }
6648             # Find the value.
6649             @temp_list =
6650               variable_value_as_list_recursive_worker ($1, $cond, $var);
6652             # Now rewrite the value if appropriate.
6653             if (defined $from)
6654             {
6655                 grep (s/$from$/$to/, @temp_list);
6656             }
6658             push (@result, @temp_list);
6659         }
6660         else
6661         {
6662             push (@result, $_);
6663         }
6664     }
6666     return @result;
6670 # @VALUES
6671 # variable_value_as_list ($VAR, $COND, $PARENT)
6672 # ---------------------------------------------
6673 # Get the value of a variable given a specified condition. without
6674 # recursing through any subvariables.
6675 # Arguments are:
6676 #   $VAR    is the variable
6677 #   $COND   is the condition.  If this is not given, the value for the
6678 #           "TRUE" condition will be returned.
6679 #   $PARENT is the variable in which the variable is used: this is used
6680 #           only for error messages.
6681 # Returns the list of conditions.
6682 # For example, if A is defined as "foo $(B) bar", and B is defined as
6683 # "baz", this will return ("foo", "$(B)", "bar")
6684 sub variable_value_as_list
6686     my ($var, $cond, $parent) = @_;
6687     my @result;
6689     # Check defined
6690     return
6691       unless variable_assert $var, $parent;
6693     # Get value for given condition
6694     $cond ||= 'TRUE';
6695     my $onceflag;
6696     foreach my $vcond (keys %{$var_value{$var}})
6697     {
6698         my $val = $var_value{$var}{$vcond};
6700         if (&conditional_true_when ($vcond, $cond))
6701         {
6702             # Unless variable is not defined conditionally, there should only
6703             # be one value of $vcond true when $cond.
6704             &check_variable_defined_unconditionally ($var, $parent)
6705                     if $onceflag;
6706             $onceflag = 1;
6708             # Strip backslashes
6709             $val =~ s/\\(\n|$)/ /g;
6711             foreach (split (' ', $val))
6712             {
6713                 # If a comment seen, just leave.
6714                 last if /^#/;
6716                 push (@result, $_);
6717             }
6718         }
6719     }
6721     return @result;
6725 # @VALUE
6726 # &variable_value_as_list_recursive_worker ($VAR, $COND, $PARENT)
6727 # ---------------------------------------------------------------
6728 # Return contents of VAR as a list, split on whitespace.  This will
6729 # recursively follow $(...) and ${...} inclusions.  It preserves @...@
6730 # substitutions.  If COND is 'all', then all values under all
6731 # conditions should be returned; if COND is a particular condition
6732 # (all conditions are surrounded by @...@) then only the value for
6733 # that condition should be returned; otherwise, warn if VAR is
6734 # conditionally defined.  If PARENT is specified, it is the name of
6735 # the including variable; this is only used for error reports.
6736 sub variable_value_as_list_recursive_worker ($$$)
6738     my ($var, $cond, $parent) = @_;
6739     my @result = ();
6741     return
6742       unless variable_assert $var, $parent;
6744     if (defined $vars_scanned{$var})
6745     {
6746         # `vars_scanned' is a global we use to keep track of which
6747         # variables we've already examined.
6748         macro_error ($parent, "variable `$var' recursively defined");
6749     }
6750     elsif ($cond eq 'all')
6751     {
6752         $vars_scanned{$var} = 1;
6753         foreach my $vcond (keys %{$var_value{$var}})
6754         {
6755             my $val = $var_value{$var}{$vcond};
6756             push (@result, &value_to_list ($var, $val, $cond));
6757         }
6758     }
6759     else
6760     {
6761         $cond ||= 'TRUE';
6762         $vars_scanned{$var} = 1;
6763         my $onceflag;
6764         foreach my $vcond (keys %{$var_value{$var}})
6765         {
6766             my $val = $var_value{$var}{$vcond};
6767             if (&conditional_true_when ($vcond, $cond))
6768             {
6769                 # Warn if we have an ambiguity.  It's hard to know how
6770                 # to handle this case correctly.
6771                 &check_variable_defined_unconditionally ($var, $parent)
6772                     if $onceflag;
6773                 $onceflag = 1;
6774                 push (@result, &value_to_list ($var, $val, $cond));
6775             }
6776         }
6777     }
6779     # Unset our entry in vars_scanned.  We only care about recursive
6780     # definitions.
6781     delete $vars_scanned{$var};
6783     return @result;
6787 # &variable_output ($VAR, [@CONDS])
6788 # ---------------------------------
6789 # Output all the values of $VAR is @COND is not specified, else only
6790 # that corresponding to @COND.
6791 sub variable_output ($@)
6793   my ($var, @conds) = @_;
6795   @conds = keys %{$var_value{$var}}
6796     unless @conds;
6798   $output_vars .= $var_comment{$var}
6799     if defined $var_comment{$var};
6801   foreach my $cond (sort by_condition @conds)
6802     {
6803       my $val = $var_value{$var}{$cond};
6804       my $equals = $var_type{$var} eq ':' ? ':=' : '=';
6805       my $output_var = "$var $equals $val";
6806       $output_var =~ s/^/make_condition ($cond)/meg;
6807       $output_vars .= $output_var . "\n";
6808     }
6812 # &variable_pretty_output ($VAR, [@CONDS])
6813 # ----------------------------------------
6814 # Likewise, but pretty, i.e., we *split* the values at spaces.   Use only
6815 # with variables holding filenames.
6816 sub variable_pretty_output ($@)
6818   my ($var, @conds) = @_;
6820   @conds = keys %{$var_value{$var}}
6821     unless @conds;
6823   $output_vars .= $var_comment{$var}
6824     if defined $var_comment{$var};
6826   foreach my $cond (sort by_condition @conds)
6827     {
6828       my $val = $var_value{$var}{$cond};
6829       my $equals = $var_type{$var} eq ':' ? ':=' : '=';
6830       my $make_condition = make_condition ($cond);
6831       $output_vars .= pretty_print_internal ("$make_condition$var $equals",
6832                                              "$make_condition\t",
6833                                              split (' ' , $val));
6834     }
6838 # &variable_value_as_list_recursive ($VAR, $COND, $PARENT)
6839 # --------------------------------------------------------
6840 # This is just a wrapper for variable_value_as_list_recursive_worker that
6841 # initializes the global hash `vars_scanned'.  This hash is used to
6842 # avoid infinite recursion.
6843 sub variable_value_as_list_recursive ($$@)
6845     my ($var, $cond, $parent) = @_;
6846     %vars_scanned = ();
6847     return &variable_value_as_list_recursive_worker ($var, $cond, $parent);
6851 # &define_pretty_variable ($VAR, $COND, @VALUE)
6852 # ---------------------------------------------
6853 # Like define_variable, but the value is a list, and the variable may
6854 # be defined conditionally.  The second argument is the conditional
6855 # under which the value should be defined; this should be the empty
6856 # string to define the variable unconditionally.  The third argument
6857 # is a list holding the values to use for the variable.  The value is
6858 # pretty printed in the output file.
6859 sub define_pretty_variable ($$@)
6861     my ($var, $cond, @value) = @_;
6863     # Beware that an empty $cond has a different semantics for
6864     # macro_define and variable_pretty_output.
6865     $cond ||= 'TRUE';
6867     if (! variable_defined ($var, $cond))
6868     {
6869         macro_define ($var, 1, '', $cond, "@value", undef);
6870         variable_pretty_output ($var, $cond || 'TRUE');
6871         $content_seen{$var} = 1;
6872     }
6876 # define_variable ($VAR, $VALUE)
6877 # ------------------------------
6878 # Define a new user variable VAR to VALUE, but only if not already defined.
6879 sub define_variable ($$)
6881     my ($var, $value) = @_;
6882     define_pretty_variable ($var, 'TRUE', $value);
6886 # Like define_variable, but define a variable to be the configure
6887 # substitution by the same name.
6888 sub define_configure_variable ($)
6890     my ($var) = @_;
6891     if (! variable_defined ($var, 'TRUE'))
6892     {
6893         # A macro defined via configure is a `user' macro -- we should not
6894         # override it.
6895         macro_define ($var, 0, '', 'TRUE', subst $var, $configure_vars{$var});
6896         variable_pretty_output ($var, 'TRUE');
6897     }
6901 # define_compiler_variable ($LANG)
6902 # --------------------------------
6903 # Define a compiler variable.  We also handle defining the `LT'
6904 # version of the command when using libtool.
6905 sub define_compiler_variable ($)
6907     my ($lang) = @_;
6909     my ($var, $value) = ($lang->compiler, $lang->compile);
6910     &define_variable ($var, $value);
6911     &define_variable ("LT$var", "\$(LIBTOOL) --mode=compile $value")
6912       if $seen_libtool;
6916 # define_linker_variable ($LANG)
6917 # ------------------------------
6918 # Define linker variables.
6919 sub define_linker_variable ($)
6921     my ($lang) = @_;
6923     my ($var, $value) = ($lang->lder, $lang->ld);
6924     # CCLD = $(CC).
6925     &define_variable ($lang->lder, $lang->ld);
6926     # CCLINK = $(CCLD) blah blah...
6927     &define_variable ($lang->linker,
6928                       (($seen_libtool ? '$(LIBTOOL) --mode=link ' : '')
6929                        . $lang->link));
6932 ################################################################
6934 ## ---------------- ##
6935 ## Handling rules.  ##
6936 ## ---------------- ##
6938 # $BOOL
6939 # rule_define ($TARGET, $IS_AM, $COND, $WHERE)
6940 # --------------------------------------------
6941 # Define a new rule.  $TARGET is the rule name.  $IS_AM is a boolean
6942 # which is true if the new rule is defined by the user.  $COND is the
6943 # condition under which the rule is defined.  $WHERE is where the rule
6944 # is defined (file name or line number).  Returns true if it is ok to
6945 # define the rule, false otherwise.
6946 sub rule_define ($$$$)
6948   my ($target, $rule_is_am, $cond, $where) = @_;
6950   # For now `foo:' will override `foo$(EXEEXT):'.  This is temporary,
6951   # though, so we emit a warning.
6952   (my $noexe = $target) =~ s,\$\(EXEEXT\)$,,;
6953   if ($noexe ne $target && defined $targets{$noexe})
6954   {
6955       # The no-exeext option enables this feature.
6956       if (! defined $options{'no-exeext'})
6957       {
6958           macro_error ($noexe,
6959                        "deprecated feature: `$noexe' overrides `$noexe\$(EXEEXT)'\nchange your target to read `$noexe\$(EXEEXT)'");
6960       }
6961       # Don't define.
6962       return 0;
6963   }
6965   if (defined $targets{$target}
6966       && ($cond
6967           ? ! defined $target_conditional{$target}
6968           : defined $target_conditional{$target}))
6969   {
6970       target_error ($target,
6971                     "$target defined both conditionally and unconditionally");
6972   }
6974   # Value here doesn't matter; for targets we only note existence.
6975   $targets{$target} = $where;
6976   if ($cond)
6977   {
6978       if ($target_conditional{$target})
6979       {
6980           &check_ambiguous_conditional ($target, $cond);
6981       }
6982       $target_conditional{$target}{$cond} = $where;
6983   }
6985   # Check the rule for being a suffix rule. If so, store in a hash.
6986   # Either it's a rule for two known extensions...
6987   if ($target =~ /^($KNOWN_EXTENSIONS_PATTERN)($KNOWN_EXTENSIONS_PATTERN)$/
6988   # ...or it's a rule with unknown extensions (.i.e, the rule looks like
6989   # `.foo.bar:' but `.foo' or `.bar' are not declared in SUFFIXES
6990   # and are not known language extensions).
6991   # Automake will complete SUFFIXES from @suffixes automatically
6992   # (see handle_footer).
6993       || ($target =~ /$SUFFIX_RULE_PATTERN/o && accept_extensions($1)))
6994   {
6995       my $internal_ext = $2;
6997       # When tranforming sources to objects, Automake uses the
6998       # %suffix_rules to move from each source extension to
6999       # `.$(OBJEXT)', not to `.o' or `.obj'.  However some people
7000       # define suffix rules for `.o' or `.obj', so internally we will
7001       # consider these extensions equivalent to `.$(OBJEXT)'.  We
7002       # CANNOT rewrite the target (i.e., automagically replace `.o'
7003       # and `.obj' by `.$(OBJEXT)' in the output), or warn the user
7004       # that (s)he'd better use `.$(OBJEXT)', because Automake itself
7005       # output suffix rules for `.o' or `.obj'...
7006       $internal_ext = '.$(OBJEXT)' if ($2 eq '.o' || $2 eq '.obj');
7008       $suffix_rules{$1} = $internal_ext;
7009       verbose "Sources ending in $1 become $2";
7010       push @suffixes, $1, $2;
7011   }
7013   return 1;
7017 # See if a target exists.
7018 sub target_defined
7020     my ($target) = @_;
7021     return defined $targets{$target};
7025 ################################################################
7027 # &append_comments ($VARIABLE, $SPACING, $COMMENT)
7028 # ------------------------------------------------
7029 # Apped $COMMENT to the other comments for $VARIABLE, using
7030 # $SPACING as separator.
7031 sub append_comments ($$$)
7033     my ($var, $spacing, $comment) = @_;
7034     $var_comment{$var} .= $spacing
7035         if (!defined $var_comment{$var} || $var_comment{$var} !~ /\n$/o);
7036     $var_comment{$var} .= $comment;
7040 # &read_am_file ($AMFILE)
7041 # -----------------------
7042 # Read Makefile.am and set up %contents.  Simultaneously copy lines
7043 # from Makefile.am into $output_trailer or $output_vars as
7044 # appropriate.  NOTE we put rules in the trailer section.  We want
7045 # user rules to come after our generated stuff.
7046 sub read_am_file ($)
7048     my ($amfile) = @_;
7050     my $am_file = new Automake::XFile ("< $amfile");
7051     verbose "reading $amfile";
7053     my $spacing = '';
7054     my $comment = '';
7055     my $blank = 0;
7056     my $saw_bk = 0;
7058     use constant IN_VAR_DEF => 0;
7059     use constant IN_RULE_DEF => 1;
7060     use constant IN_COMMENT => 2;
7061     my $prev_state = IN_RULE_DEF;
7063     while ($_ = $am_file->getline)
7064     {
7065         if (/$IGNORE_PATTERN/o)
7066         {
7067             # Merely delete comments beginning with two hashes.
7068         }
7069         elsif (/$WHITE_PATTERN/o)
7070         {
7071             file_error ("$amfile:$.",
7072                         "blank line following trailing backslash")
7073                 if $saw_bk;
7074             # Stick a single white line before the incoming macro or rule.
7075             $spacing = "\n";
7076             $blank = 1;
7077             # Flush all comments seen so far.
7078             if ($comment ne '')
7079             {
7080                 $output_vars .= $comment;
7081                 $comment = '';
7082             }
7083         }
7084         elsif (/$COMMENT_PATTERN/o)
7085         {
7086             # Stick comments before the incoming macro or rule.  Make
7087             # sure a blank line preceeds first block of comments.
7088             $spacing = "\n" unless $blank;
7089             $blank = 1;
7090             $comment .= $spacing . $_;
7091             $spacing = '';
7092             $prev_state = IN_COMMENT;
7093         }
7094         else
7095         {
7096             last;
7097         }
7098         $saw_bk = /\\$/ && ! /$IGNORE_PATTERN/o;
7099     }
7101     # We save the conditional stack on entry, and then check to make
7102     # sure it is the same on exit.  This lets us conditonally include
7103     # other files.
7104     my @saved_cond_stack = @cond_stack;
7105     my $cond = conditional_string (@cond_stack);
7107     my $last_var_name = '';
7108     my $last_var_type = '';
7109     my $last_var_value = '';
7110     # FIXME: shouldn't use $_ in this loop; it is too big.
7111     while ($_)
7112     {
7113         my $here = "$amfile:$.";
7115         # Make sure the line is \n-terminated.
7116         chomp;
7117         $_ .= "\n";
7119         # Don't look at MAINTAINER_MODE_TRUE here.  That shouldn't be
7120         # used by users.  @MAINT@ is an anachronism now.
7121         $_ =~ s/\@MAINT\@//g
7122             unless $seen_maint_mode;
7124         my $new_saw_bk = /\\$/ && ! /$IGNORE_PATTERN/o;
7126         if (/$IGNORE_PATTERN/o)
7127         {
7128             # Merely delete comments beginning with two hashes.
7129         }
7130         elsif (/$WHITE_PATTERN/o)
7131         {
7132             # Stick a single white line before the incoming macro or rule.
7133             $spacing = "\n";
7134             file_error ($here, "blank line following trailing backslash")
7135                 if $saw_bk;
7136         }
7137         elsif (/$COMMENT_PATTERN/o)
7138         {
7139             # Stick comments before the incoming macro or rule.
7140             $comment .= $spacing . $_;
7141             $spacing = '';
7142             file_error ($here, "comment following trailing backslash")
7143                 if $saw_bk && $comment eq '';
7144             $prev_state = IN_COMMENT;
7145         }
7146         elsif ($saw_bk)
7147         {
7148             if ($prev_state == IN_RULE_DEF)
7149             {
7150                 $output_trailer .= &make_condition (@cond_stack);
7151                 $output_trailer .= $_;
7152             }
7153             elsif ($prev_state == IN_COMMENT)
7154             {
7155                 # If the line doesn't start with a `#', add it.
7156                 # We do this because a continuated comment like
7157                 #   # A = foo \
7158                 #         bar \
7159                 #         baz
7160                 # is not portable.  BSD make doesn't honor
7161                 # escaped newlines in comments.
7162                 s/^#?/#/;
7163                 $comment .= $spacing . $_;
7164             }
7165             else # $prev_state == IN_VAR_DEF
7166             {
7167               $last_var_value .= ' '
7168                 unless $last_var_value =~ /\s$/;
7169               $last_var_value .= $_;
7171               if (!/\\$/)
7172                 {
7173                   append_comments $last_var_name, $spacing, $comment;
7174                   $comment = $spacing = '';
7175                   macro_define ($last_var_name, 0,
7176                                 $last_var_type, $cond,
7177                                 $last_var_value, $here)
7178                     if $cond ne 'FALSE';
7179                   push (@var_list, $last_var_name);
7180                 }
7181             }
7182         }
7184         elsif (/$IF_PATTERN/o)
7185           {
7186             $cond = cond_stack_if ($1, $2, $here);
7187           }
7188         elsif (/$ELSE_PATTERN/o)
7189           {
7190             $cond = cond_stack_else ($1, $2, $here);
7191           }
7192         elsif (/$ENDIF_PATTERN/o)
7193           {
7194             $cond = cond_stack_endif ($1, $2, $here);
7195           }
7197         elsif (/$RULE_PATTERN/o)
7198         {
7199             # Found a rule.
7200             $prev_state = IN_RULE_DEF;
7202             rule_define ($1, 0, $cond, $here);
7204             $output_trailer .= $comment . $spacing;
7205             $output_trailer .= &make_condition (@cond_stack);
7206             $output_trailer .= $_;
7207             $comment = $spacing = '';
7208         }
7209         elsif (/$ASSIGNMENT_PATTERN/o)
7210         {
7211             # Found a macro definition.
7212             $prev_state = IN_VAR_DEF;
7213             $last_var_name = $1;
7214             $last_var_type = $2;
7215             $last_var_value = $3;
7216             if ($3 ne '' && substr ($3, -1) eq "\\")
7217             {
7218                 # We preserve the `\' because otherwise the long lines
7219                 # that are generated will be truncated by broken
7220                 # `sed's.
7221                 $last_var_value = $3 . "\n";
7222             }
7224             if (!/\\$/)
7225               {
7226                 # FIXME: this doesn't always work correctly; it will
7227                 # group all comments for a given variable, no matter
7228                 # where defined.
7229                 # Accumulating variables must not be output.
7230                 append_comments $last_var_name, $spacing, $comment;
7231                 $comment = $spacing = '';
7233                 macro_define ($last_var_name, 0,
7234                               $last_var_type, $cond,
7235                               $last_var_value, $here)
7236                   if $cond ne 'FALSE';
7237                 push (@var_list, $last_var_name);
7238               }
7239         }
7240         elsif (/$INCLUDE_PATTERN/o)
7241         {
7242             my $path = $1;
7244             if ($path =~ s/^\$\(top_srcdir\)\///)
7245             {
7246                 push (@include_stack, "\$\(top_srcdir\)/$path");
7247             }
7248             else
7249             {
7250                 $path =~ s/\$\(srcdir\)\///;
7251                 push (@include_stack, "\$\(srcdir\)/$path");
7252                 $path = $relative_dir . "/" . $path;
7253             }
7254             &read_am_file ($path);
7255         }
7256         else
7257         {
7258             # This isn't an error; it is probably a continued rule.
7259             # In fact, this is what we assume.
7260             $prev_state = IN_RULE_DEF;
7261             $output_trailer .= $comment . $spacing;
7262             $output_trailer .= &make_condition  (@cond_stack);
7263             $output_trailer .= $_;
7264             $comment = $spacing = '';
7265             file_error ($here, "`#' comment at start of rule is unportable")
7266                 if $_ =~ /^\t\s*\#/;
7267         }
7269         $saw_bk = $new_saw_bk;
7270         $_ = $am_file->getline;
7271     }
7273     $output_trailer .= $comment;
7275     if ("@saved_cond_stack" ne "@cond_stack")
7276     {
7277         if (@cond_stack)
7278         {
7279             &am_error ("unterminated conditionals: @cond_stack");
7280         }
7281         else
7282         {
7283             # FIXME: better error message here.
7284             &am_error ("conditionals not nested in include file");
7285         }
7286     }
7290 # define_standard_variables ()
7291 # ----------------------------
7292 # A helper for read_main_am_file which initializes configure variables
7293 # and variables from header-vars.am.  This is a subr so we can call it
7294 # twice.
7295 sub define_standard_variables
7297     my $saved_output_vars = $output_vars;
7298     my ($comments, undef, $rules) =
7299       file_contents_internal (1, "$libdir/am/header-vars.am");
7301     # This will output the definitions in $output_vars, which we don't
7302     # want...
7303     foreach my $var (sort keys %configure_vars)
7304     {
7305         &define_configure_variable ($var);
7306         push (@var_list, $var);
7307     }
7309     # ... hence, we restore $output_vars.
7310     $output_vars = $saved_output_vars . $comments . $rules;
7313 # Read main am file.
7314 sub read_main_am_file
7316     my ($amfile) = @_;
7318     # This supports the strange variable tricks we are about to play.
7319     if (scalar keys %var_value > 0)
7320       {
7321         macros_dump ();
7322         prog_error ("variable defined before read_main_am_file");
7323       }
7325     # Generate copyright header for generated Makefile.in.
7326     # We do discard the output of predefined variables, handled below.
7327     $output_vars = ("# $in_file_name generated by automake "
7328                    . $VERSION . " from $am_file_name.\n");
7329     $output_vars .= '# ' . subst ('configure_input') . "\n";
7330     $output_vars .= $gen_copyright;
7332     # We want to predefine as many variables as possible.  This lets
7333     # the user set them with `+=' in Makefile.am.  However, we don't
7334     # want these initial definitions to end up in the output quite
7335     # yet.  So we just load them, but output them later.
7336     &define_standard_variables;
7338     # Read user file, which might override some of our values.
7339     &read_am_file ($amfile);
7341     # Output all the Automake variables.  If the user changed one,
7342     # then it is now marked as owned by the user.
7343     foreach my $var (uniq @var_list)
7344     {
7345         # Don't process user variables.
7346         variable_output ($var)
7347           unless !$var_is_am{$var};
7348     }
7350     # Now dump the user variables that were defined.  We do it in the same
7351     # order in which they were defined (skipping duplicates).
7352     foreach my $var (uniq @var_list)
7353     {
7354         # Don't process Automake variables.
7355         variable_output ($var)
7356           unless $var_is_am{$var};
7357     }
7360 ################################################################
7362 # $FLATTENED
7363 # &flatten ($STRING)
7364 # ------------------
7365 # Flatten the $STRING and return the result.
7366 sub flatten
7368   $_ = shift;
7370   s/\\\n//somg;
7371   s/\s+/ /g;
7372   s/^ //;
7373   s/ $//;
7375   return $_;
7379 # @PARAGRAPHS
7380 # &make_paragraphs ($MAKEFILE, [%TRANSFORM])
7381 # ------------------------------------------
7382 # Load a $MAKEFILE, apply the %TRANSFORM, and return it as a list of
7383 # paragraphs.
7384 sub make_paragraphs ($%)
7386     my ($file, %transform) = @_;
7388     # Complete %transform with global options and make it a Perl
7389     # $command.
7390     my $command =
7391       "s/$IGNORE_PATTERN//gm;"
7392         . transform (%transform,
7394                      'CYGNUS'          => $cygnus_mode,
7395                      'MAINTAINER-MODE'
7396                      => $seen_maint_mode ? subst ('MAINTAINER_MODE_TRUE') : '',
7398                      'SHAR'        => $options{'dist-shar'} || 0,
7399                      'BZIP2'       => $options{'dist-bzip2'} || 0,
7400                      'ZIP'         => $options{'dist-zip'} || 0,
7401                      'COMPRESS'    => $options{'dist-tarZ'} || 0,
7403                      'INSTALL-INFO' => !$options{'no-installinfo'},
7404                      'INSTALL-MAN'  => !$options{'no-installman'},
7405                      'CK-NEWS'      => $options{'check-news'} || 0,
7407                      'SUBDIRS'      => variable_defined ('SUBDIRS'),
7408                      'TOPDIR'       => backname ($relative_dir),
7409                      'TOPDIR_P'     => $relative_dir eq '.',
7410                      'CONFIGURE-AC' => $configure_ac,
7412                      'BUILD'    => $seen_canonical == AC_CANONICAL_SYSTEM,
7413                      'HOST'     => $seen_canonical,
7414                      'TARGET'   => $seen_canonical == AC_CANONICAL_SYSTEM,
7416                      'LIBTOOL'      => defined $configure_vars{'LIBTOOL'})
7417           # We don't need more than two consecutive new-lines.
7418           . 's/\n{3,}/\n\n/g';
7420     # Swallow the file and apply the COMMAND.
7421     my $fc_file = new Automake::XFile "< $file";
7422     # Looks stupid?
7423     verbose "reading $file";
7424     my $saved_dollar_slash = $/;
7425     undef $/;
7426     $_ = $fc_file->getline;
7427     $/ = $saved_dollar_slash;
7428     eval $command;
7429     $fc_file->close;
7430     my $content = $_;
7432     # Split at unescaped new lines.
7433     my @lines = split (/(?<!\\)\n/, $content);
7434     my @res;
7436     while (defined ($_ = shift @lines))
7437       {
7438         my $paragraph = "$_";
7439         # If we are a rule, eat as long as we start with a tab.
7440         if (/$RULE_PATTERN/smo)
7441           {
7442             while (defined ($_ = shift @lines) && $_ =~ /^\t/)
7443               {
7444                 $paragraph .= "\n$_";
7445               }
7446             unshift (@lines, $_);
7447           }
7449         # If we are a comments, eat as much comments as you can.
7450         elsif (/$COMMENT_PATTERN/smo)
7451           {
7452             while (defined ($_ = shift @lines)
7453                    && $_ =~ /$COMMENT_PATTERN/smo)
7454               {
7455                 $paragraph .= "\n$_";
7456               }
7457             unshift (@lines, $_);
7458           }
7460         push @res, $paragraph;
7461         $paragraph = '';
7462       }
7464     return @res;
7469 # ($COMMENT, $VARIABLES, $RULES)
7470 # &file_contents_internal ($IS_AM, $FILE, [%TRANSFORM])
7471 # -----------------------------------------------------
7472 # Return contents of a file from $libdir/am, automatically skipping
7473 # macros or rules which are already known. $IS_AM iff the caller is
7474 # reading an Automake file (as opposed to the user's Makefile.am).
7475 sub file_contents_internal ($$%)
7477     my ($is_am, $file, %transform) = @_;
7479     my $result_vars = '';
7480     my $result_rules = '';
7481     my $comment = '';
7482     my $spacing = '';
7484     # The following flags are used to track rules spanning across
7485     # multiple paragraphs.
7486     my $is_rule = 0;            # 1 if we are processing a rule.
7487     my $discard_rule = 0;       # 1 if the current rule should not be output.
7489     # We save the conditional stack on entry, and then check to make
7490     # sure it is the same on exit.  This lets us conditonally include
7491     # other files.
7492     my @saved_cond_stack = @cond_stack;
7493     my $cond = conditional_string (@cond_stack);
7495     foreach (make_paragraphs ($file, %transform))
7496     {
7497         # Sanity checks.
7498         file_error ($file, "blank line following trailing backslash:\n$_")
7499           if /\\$/;
7500         file_error ($file, "comment following trailing backslash:\n$_")
7501           if /\\#/;
7503         if (/^$/)
7504         {
7505             $is_rule = 0;
7506             # Stick empty line before the incoming macro or rule.
7507             $spacing = "\n";
7508         }
7509         elsif (/$COMMENT_PATTERN/mso)
7510         {
7511             $is_rule = 0;
7512             # Stick comments before the incoming macro or rule.
7513             $comment = "$_\n";
7514         }
7516         # Handle inclusion of other files.
7517         elsif (/$INCLUDE_PATTERN/o)
7518         {
7519             if ($cond ne 'FALSE')
7520               {
7521                 my $file = ($is_am ? "$libdir/am/" : '') . $1;
7522                 # N-ary `.=' fails.
7523                 my ($com, $vars, $rules)
7524                   = file_contents_internal ($is_am, $file, %transform);
7525                 $comment .= $com;
7526                 $result_vars .= $vars;
7527                 $result_rules .= $rules;
7528               }
7529         }
7531         # Handling the conditionals.
7532         elsif (/$IF_PATTERN/o)
7533           {
7534             $cond = cond_stack_if ($1, $2, $file);
7535           }
7536         elsif (/$ELSE_PATTERN/o)
7537           {
7538             $cond = cond_stack_else ($1, $2, $file);
7539           }
7540         elsif (/$ENDIF_PATTERN/o)
7541           {
7542             $cond = cond_stack_endif ($1, $2, $file);
7543           }
7545         # Handling rules.
7546         elsif (/$RULE_PATTERN/mso)
7547         {
7548           $is_rule = 1;
7549           $discard_rule = 0;
7550           # Separate relationship from optional actions: the first
7551           # `new-line tab" not preceded by backslash (continuation
7552           # line).
7553           # I'm quite shoked!  It seems that (\\\n|[^\n]) is not the
7554           # same as `([^\n]|\\\n)!!!  Don't swap it, it breaks.
7555           my $paragraph = $_;
7556           /^((?:\\\n|[^\n])*)(?:\n(\t.*))?$/som;
7557           my ($relationship, $actions) = ($1, $2 || '');
7559           # Separate targets from dependencies: the first colon.
7560           $relationship =~ /^([^:]+\S+) *: *(.*)$/som;
7561           my ($targets, $dependencies) = ($1, $2);
7562           # Remove the escaped new lines.
7563           # I don't know why, but I have to use a tmp $flat_deps.
7564           my $flat_deps = &flatten ($dependencies);
7565           my @deps = split (' ', $flat_deps);
7567           foreach (split (' ' , $targets))
7568             {
7569               # FIXME: We are not robust to people defining several targets
7570               # at once, only some of them being in %dependencies.  The
7571               # actions from the targets in %dependencies are usually generated
7572               # from the content of %actions, but if some targets in $targets
7573               # are not in %dependencies the ELSE branch will output
7574               # a rule for all $targets (i.e. the targets which are both
7575               # in %dependencies and $targets will have two rules).
7577               # FIXME: The logic here is not able to output a
7578               # multi-paragraph rule several time (e.g. for each conditional
7579               # it is defined for) because it only knows the first paragraph.
7581               # Output only if not in FALSE.
7582               if (defined $dependencies{$_}
7583                   && $cond ne 'FALSE')
7584                 {
7585                   &depend ($_, @deps);
7586                   $actions{$_} .= $actions;
7587                 }
7588               else
7589                 {
7590                   # Free-lance dependency.  Output the rule for all the
7591                   # targets instead of one by one.
7593                   # Work out all the conditions for which the target hasn't
7594                   # been defined
7595                   my @undefined_conds;
7596                   if (defined $target_conditional{$targets})
7597                     {
7598                       my @defined_conds = keys %{$target_conditional{$targets}};
7599                       @undefined_conds = invert_conditions(@defined_conds);
7600                     }
7601                   else
7602                     {
7603                       if (defined $targets{$targets})
7604                         {
7605                           # No conditions for which target hasn't been defined
7606                           @undefined_conds = ();
7607                         }
7608                       else
7609                         {
7610                           # Target hasn't been defined for any conditions
7611                           @undefined_conds = ("");
7612                         }
7613                     }
7615                   if ($cond ne 'FALSE')
7616                     {
7617                       for my $undefined_cond (@undefined_conds)
7618                       {
7619                           my $condparagraph = $paragraph;
7620                           $condparagraph =~ s/^/make_condition (@cond_stack, $undefined_cond)/gme;
7621                           if (rule_define ($targets, $is_am,
7622                                           "$cond $undefined_cond", $file))
7623                           {
7624                               $result_rules .=
7625                                   "$spacing$comment$condparagraph\n"
7626                           }
7627                           else
7628                           {
7629                               # Remember to discard next paragraphs
7630                               # if they belong to this rule.
7631                               $discard_rule = 1;
7632                           }
7633                       }
7634                       if ($#undefined_conds == -1)
7635                       {
7636                           # This target has already been defined, the rule
7637                           # has not been defined. Remember to discard next
7638                           # paragraphs if they belong to this rule.
7639                           $discard_rule = 1;
7640                       }
7641                     }
7642                   $comment = $spacing = '';
7643                   last;
7644                 }
7645             }
7646         }
7648         elsif (/$ASSIGNMENT_PATTERN/mso)
7649         {
7650             my ($var, $type, $val) = ($1, $2, $3);
7651             file_error ($file, "macro `$var' with trailing backslash")
7652               if /\\$/;
7654             $is_rule = 0;
7656             # Accumulating variables must not be output.
7657             append_comments $var, $spacing, $comment;
7658             macro_define ($var, $is_am, $type, $cond, $val, $file)
7659               if $cond ne 'FALSE';
7660             push (@var_list, $var);
7662             # If the user has set some variables we were in charge
7663             # of (which is detected by the first reading of
7664             # `header-vars.am'), we must not output them.
7665             $result_vars .= "$spacing$comment$_\n"
7666               if $type ne '+' && $var_is_am{$var} && $cond ne 'FALSE';
7668             $comment = $spacing = '';
7669         }
7670         else
7671         {
7672             # This isn't an error; it is probably some tokens which
7673             # configure is supposed to replace, such as `@SET-MAKE@',
7674             # or some part of a rule cut by an if/endif.
7675             if ($cond ne 'FALSE' && ! ($is_rule && $discard_rule))
7676               {
7677                 s/^/make_condition (@cond_stack)/gme;
7678                 $result_rules .= "$spacing$comment$_\n";
7679               }
7680             $comment = $spacing = '';
7681         }
7682     }
7684     if ("@saved_cond_stack" ne "@cond_stack")
7685     {
7686         if (@cond_stack)
7687         {
7688             &am_error ("unterminated conditionals: @cond_stack");
7689         }
7690         else
7691         {
7692             # FIXME: better error message here.
7693             &am_error ("conditionals not nested in include file");
7694         }
7695     }
7697     return ($comment, $result_vars, $result_rules);
7701 # $CONTENTS
7702 # &file_contents ($BASENAME, [%TRANSFORM])
7703 # ----------------------------------------
7704 # Return contents of a file from $libdir/am, automatically skipping
7705 # macros or rules which are already known.
7706 sub file_contents ($%)
7708     my ($basename, %transform) = @_;
7709     my ($comments, $variables, $rules) =
7710       file_contents_internal (1, "$libdir/am/$basename.am", %transform);
7711     return "$comments$variables$rules";
7715 # $REGEXP
7716 # &transform (%PAIRS)
7717 # -------------------
7718 # Foreach ($TOKEN, $VAL) in %PAIRS produce a replacement expression suitable
7719 # for file_contents which:
7720 #   - replaces %$TOKEN% with $VAL,
7721 #   - enables/disables ?$TOKEN? and ?!$TOKEN?,
7722 #   - replaces %?$TOKEN% with TRUE or FALSE.
7723 sub transform (%)
7725     my (%pairs) = @_;
7726     my $result = '';
7728     while (my ($token, $val) = each %pairs)
7729     {
7730         $result .= "s/\Q%$token%\E/\Q$val\E/gm;";
7731         if ($val)
7732         {
7733             $result .= "s/\Q?$token?\E//gm;s/^.*\Q?!$token?\E.*\\n//gm;";
7734             $result .= "s/\Q%?$token%\E/TRUE/gm;";
7735         }
7736         else
7737         {
7738             $result .= "s/\Q?!$token?\E//gm;s/^.*\Q?$token?\E.*\\n//gm;";
7739             $result .= "s/\Q%?$token%\E/FALSE/gm;";
7740         }
7741     }
7743     return $result;
7747 # &append_exeext ($MACRO)
7748 # -----------------------
7749 # Macro is an Automake magic macro which primary is PROGRAMS, e.g.
7750 # bin_PROGRAMS.  Make sure these programs have $(EXEEXT) appended.
7751 sub append_exeext ($)
7753   my ($macro) = @_;
7755   prog_error "append_exeext ($macro)"
7756     unless $macro =~ /_PROGRAMS$/;
7758   my @conds = variable_conditions_recursive ($macro);
7760   my @condvals;
7761   foreach my $cond (@conds)
7762     {
7763       my @one_binlist = ();
7764       my @condval = variable_value_as_list_recursive ($macro, $cond);
7765       foreach my $rcurs (@condval)
7766         {
7767           # Skip autoconf substs.  Also skip if the user
7768           # already applied $(EXEEXT).
7769           if ($rcurs =~ /^\@.*\@$/ || $rcurs =~ /\$\(EXEEXT\)$/)
7770             {
7771               push (@one_binlist, $rcurs);
7772             }
7773           else
7774             {
7775               push (@one_binlist, $rcurs . '$(EXEEXT)');
7776             }
7777         }
7779       push (@condvals, $cond);
7780       push (@condvals, "@one_binlist");
7781     }
7783   macro_delete ($macro);
7784   while (@condvals)
7785     {
7786       my $cond = shift (@condvals);
7787       my @val = split (' ', shift (@condvals));
7788       define_pretty_variable ($macro, $cond, @val);
7789     }
7793 # @PREFIX
7794 # &am_primary_prefixes ($PRIMARY, $CAN_DIST, @PREFIXES)
7795 # -----------------------------------------------------
7796 # Find all variable prefixes that are used for install directories.  A
7797 # prefix `zar' qualifies iff:
7799 # * `zardir' is a variable.
7800 # * `zar_PRIMARY' is a variable.
7802 # As a side effect, it looks for misspellings.  It is an error to have
7803 # a variable ending in a "reserved" suffix whose prefix is unknown, eg
7804 # "bni_PROGRAMS".  However, unusual prefixes are allowed if a variable
7805 # of the same name (with "dir" appended) exists.  For instance, if the
7806 # variable "zardir" is defined, then "zar_PROGRAMS" becomes valid.
7807 # This is to provide a little extra flexibility in those cases which
7808 # need it.
7809 sub am_primary_prefixes ($$@)
7811     my ($primary, $can_dist, @prefixes) = @_;
7813     local $_;
7814     my %valid = map { $_ => 0 } @prefixes;
7815     $valid{'EXTRA'} = 0;
7816     foreach my $varname (keys %var_value)
7817     {
7818         # Automake is allowed to define variables that look like they
7819         # are magic variables, such as INSTALL_DATA.
7820         next
7821           if $var_is_am{$varname};
7823         if ($varname =~ /^(nobase_)?(dist_|nodist_)?(.*)_$primary$/)
7824         {
7825             my ($base, $dist, $X) = ($1 || '', $2 || '', $3 || '');
7826             if ($dist ne '' && ! $can_dist)
7827             {
7828                 # Note that a configure variable is always legitimate.
7829                 # It is natural to name such variables after the
7830                 # primary, so we explicitly allow it.
7831                 macro_error ($varname,
7832                             "invalid variable `$varname': `dist' is forbidden")
7833                   if ! exists $configure_vars{$varname};
7834             }
7835             # A not-explicitely-allowed prefix X is allowed if Xdir
7836             # has been defined and X is not a standard prefix.
7837             elsif (! defined $valid{$X} && (! variable_defined ("${X}dir")
7838                                             || exists $standard_prefix{$X}))
7839             {
7840                 # Note that a configure variable is always legitimate.
7841                 # It is natural to name such variables after the
7842                 # primary, so we explicitly allow it.
7843                 macro_error ($varname, "invalid variable `$varname'")
7844                   if ! exists $configure_vars{$varname};
7845             }
7846             else
7847             {
7848                 # Ensure all extended prefixes are actually used.
7849                 $valid{"$base$dist$X"} = 1;
7850             }
7851         }
7852     }
7854     # Return only those which are actually defined.
7855     return sort grep { variable_defined ($_ . '_' . $primary) } keys %valid;
7859 # Handle `where_HOW' variable magic.  Does all lookups, generates
7860 # install code, and possibly generates code to define the primary
7861 # variable.  The first argument is the name of the .am file to munge,
7862 # the second argument is the primary variable (eg HEADERS), and all
7863 # subsequent arguments are possible installation locations.  Returns
7864 # list of all values of all _HOW targets.
7866 # FIXME: this should be rewritten to be cleaner.  It should be broken
7867 # up into multiple functions.
7869 # Usage is: am_install_var (OPTION..., file, HOW, where...)
7870 sub am_install_var
7872     my (@args) = @_;
7874     my $do_require = 1;
7875     my $can_dist = 0;
7876     my $default_dist = 0;
7877     while (@args)
7878     {
7879         if ($args[0] eq '-noextra')
7880         {
7881             $do_require = 0;
7882         }
7883         elsif ($args[0] eq '-candist')
7884         {
7885             $can_dist = 1;
7886         }
7887         elsif ($args[0] eq '-defaultdist')
7888         {
7889             $default_dist = 1;
7890             $can_dist = 1;
7891         }
7892         elsif ($args[0] !~ /^-/)
7893         {
7894             last;
7895         }
7896         shift (@args);
7897     }
7899     my ($file, $primary, @prefix) = @args;
7901     # Now that configure substitutions are allowed in where_HOW
7902     # variables, it is an error to actually define the primary.  We
7903     # allow `JAVA', as it is customarily used to mean the Java
7904     # interpreter.  This is but one of several Java hacks.  Similarly,
7905     # `PYTHON' is customarily used to mean the Python interpreter.
7906     macro_error ($primary, "`$primary' is an anachronism")
7907         if variable_defined ($primary)
7908             && ($primary ne 'JAVA' && $primary ne 'PYTHON');
7911     # Get the prefixes which are valid and actually used.
7912     @prefix = am_primary_prefixes ($primary, $can_dist, @prefix);
7914     # If a primary includes a configure substitution, then the EXTRA_
7915     # form is required.  Otherwise we can't properly do our job.
7916     my $require_extra;
7917     my $warned_about_extra = 0;
7919     my @used = ();
7920     my @result = ();
7922     # True if the iteration is the first one.  Used for instance to
7923     # output parts of the associated file only once.
7924     my $first = 1;
7925     foreach my $X (@prefix)
7926     {
7927         my $nodir_name = $X;
7928         my $one_name = $X . '_' . $primary;
7930         my $strip_subdir = 1;
7931         # If subdir prefix should be preserved, do so.
7932         if ($nodir_name =~ /^nobase_/)
7933           {
7934             $strip_subdir = 0;
7935             $nodir_name =~ s/^nobase_//;
7936           }
7938         # If files should be distributed, do so.
7939         my $dist_p = 0;
7940         if ($can_dist)
7941           {
7942             $dist_p = (($default_dist && $nodir_name !~ /^nodist_/)
7943                        || (! $default_dist && $nodir_name =~ /^dist_/));
7944             $nodir_name =~ s/^(dist|nodist)_//;
7945           }
7947         # Append actual contents of where_PRIMARY variable to
7948         # result.
7949         foreach my $rcurs (&variable_value_as_list_recursive ($one_name, 'all'))
7950           {
7951             # Skip configure substitutions.  Possibly bogus.
7952             if ($rcurs =~ /^\@.*\@$/)
7953               {
7954                 if ($nodir_name eq 'EXTRA')
7955                   {
7956                     if (! $warned_about_extra)
7957                       {
7958                         $warned_about_extra = 1;
7959                         macro_error ($one_name,
7960                                      "`$one_name' contains configure substitution, but shouldn't");
7961                       }
7962                   }
7963                 # Check here to make sure variables defined in
7964                 # configure.ac do not imply that EXTRA_PRIMARY
7965                 # must be defined.
7966                 elsif (! defined $configure_vars{$one_name})
7967                   {
7968                     $require_extra = $one_name
7969                       if $do_require;
7970                   }
7972                 next;
7973               }
7975             push (@result, $rcurs);
7976           }
7978         # A blatant hack: we rewrite each _PROGRAMS primary to include
7979         # EXEEXT.
7980         append_exeext ($one_name)
7981           if $primary eq 'PROGRAMS';
7983         # "EXTRA" shouldn't be used when generating clean targets,
7984         # all, or install targets.  We used to warn if EXTRA_FOO was
7985         # defined uselessly, but this was annoying.
7986         next
7987           if $nodir_name eq 'EXTRA';
7989         if ($nodir_name eq 'check')
7990           {
7991             push (@check, '$(' . $one_name . ')');
7992           }
7993         else
7994           {
7995             push (@used, '$(' . $one_name . ')');
7996           }
7998         # Is this to be installed?
7999         my $install_p = $nodir_name ne 'noinst' && $nodir_name ne 'check';
8001         # If so, with install-exec? (or install-data?).
8002         my $exec_p = ($nodir_name =~ /$EXEC_DIR_PATTERN/o);
8004         # Singular form of $PRIMARY.
8005         (my $one_primary = $primary) =~ s/S$//;
8006         $output_rules .= &file_contents ($file,
8007                                          ('FIRST' => $first,
8009                                           'PRIMARY'     => $primary,
8010                                           'ONE_PRIMARY' => $one_primary,
8011                                           'DIR'         => $X,
8012                                           'NDIR'        => $nodir_name,
8013                                           'BASE'        => $strip_subdir,
8015                                           'EXEC'    => $exec_p,
8016                                           'INSTALL' => $install_p,
8017                                           'DIST'    => $dist_p));
8019         $first = 0;
8020     }
8022     # The JAVA variable is used as the name of the Java interpreter.
8023     # The PYTHON variable is used as the name of the Python interpreter.
8024     if (@used && $primary ne 'JAVA' && $primary ne 'PYTHON')
8025     {
8026         # Define it.
8027         define_pretty_variable ($primary, '', @used);
8028         $output_vars .= "\n";
8029     }
8031     if ($require_extra && ! variable_defined ('EXTRA_' . $primary))
8032     {
8033         macro_error ($require_extra,
8034                      "`$require_extra' contains configure substitution, but `EXTRA_$primary' not defined");
8035     }
8037     # Push here because PRIMARY might be configure time determined.
8038     push (@all, '$(' . $primary . ')')
8039         if @used && $primary ne 'JAVA' && $primary ne 'PYTHON';
8041     # Make the result unique.  This lets the user use conditionals in
8042     # a natural way, but still lets us program lazily -- we don't have
8043     # to worry about handling a particular object more than once.
8044     return uniq (sort @result);
8048 ################################################################
8050 # Each key in this hash is the name of a directory holding a
8051 # Makefile.in.  These variables are local to `is_make_dir'.
8052 my %make_dirs = ();
8053 my $make_dirs_set = 0;
8055 sub is_make_dir
8057     my ($dir) = @_;
8058     if (! $make_dirs_set)
8059     {
8060         foreach my $iter (@configure_input_files)
8061         {
8062             $make_dirs{dirname ($iter)} = 1;
8063         }
8064         # We also want to notice Makefile.in's.
8065         foreach my $iter (@other_input_files)
8066         {
8067             if ($iter =~ /Makefile\.in$/)
8068             {
8069                 $make_dirs{dirname ($iter)} = 1;
8070             }
8071         }
8072         $make_dirs_set = 1;
8073     }
8074     return defined $make_dirs{$dir};
8077 ################################################################
8079 # This variable is local to the "require file" set of functions.
8080 my @require_file_paths = ();
8083 # &maybe_push_required_file ($DIR, $FILE, $FULLFILE)
8084 # --------------------------------------------------
8085 # See if we want to push this file onto dist_common.  This function
8086 # encodes the rules for deciding when to do so.
8087 sub maybe_push_required_file
8089     my ($dir, $file, $fullfile) = @_;
8091     if ($dir eq $relative_dir)
8092     {
8093         push_dist_common ($file);
8094         return 1;
8095     }
8096     elsif ($relative_dir eq '.' && ! &is_make_dir ($dir))
8097     {
8098         # If we are doing the topmost directory, and the file is in a
8099         # subdir which does not have a Makefile, then we distribute it
8100         # here.
8101         push_dist_common ($fullfile);
8102         return 1;
8103     }
8104     return 0;
8108 # &require_file_internal ($WHERE, $MYSTRICT, @FILES)
8109 # --------------------------------------------------
8110 # Verify that the file must exist in the current directory.
8111 # $MYSTRICT is the strictness level at which this file becomes required.
8113 # Must set require_file_paths before calling this function.
8114 # require_file_paths is set to hold a single directory (the one in
8115 # which the first file was found) before return.
8116 sub require_file_internal ($$@)
8118     my ($where, $mystrict, @files) = @_;
8120     foreach my $file (@files)
8121     {
8122         my $fullfile;
8123         my $errdir;
8124         my $errfile;
8125         my $save_dir;
8127         my $found_it = 0;
8128         my $dangling_sym = 0;
8129         foreach my $dir (@require_file_paths)
8130         {
8131             $fullfile = $dir . "/" . $file;
8132             $errdir = $dir unless $errdir;
8134             # Use different name for "error filename".  Otherwise on
8135             # an error the bad file will be reported as eg
8136             # `../../install-sh' when using the default
8137             # config_aux_path.
8138             $errfile = $errdir . '/' . $file;
8140             if (-l $fullfile && ! -f $fullfile)
8141             {
8142                 $dangling_sym = 1;
8143                 last;
8144             }
8145             elsif (-f $fullfile)
8146             {
8147                 $found_it = 1;
8148                 maybe_push_required_file ($dir, $file, $fullfile);
8149                 $save_dir = $dir;
8150                 last;
8151             }
8152         }
8154         # `--force-missing' only has an effect if `--add-missing' is
8155         # specified.
8156         if ($found_it && (! $add_missing || ! $force_missing))
8157         {
8158             # Prune the path list.
8159             @require_file_paths = $save_dir;
8160         }
8161         else
8162         {
8163             # If we've already looked for it, we're done.  You might
8164             # wonder why we don't do this before searching for the
8165             # file.  If we do that, then something like
8166             # AC_OUTPUT(subdir/foo foo) will fail to put foo.in into
8167             # DIST_COMMON.
8168             if (! $found_it)
8169             {
8170                 next if defined $require_file_found{$fullfile};
8171                 $require_file_found{$fullfile} = 1;
8172             }
8174             if ($strictness >= $mystrict)
8175             {
8176                 if ($dangling_sym && $add_missing)
8177                 {
8178                     unlink ($fullfile);
8179                 }
8181                 my $trailer = '';
8182                 my $suppress = 0;
8184                 # Only install missing files according to our desired
8185                 # strictness level.
8186                 my $message = "required file `$errfile' not found";
8187                 if ($add_missing)
8188                 {
8189                     $suppress = 1;
8191                     if (-f ("$libdir/$file"))
8192                     {
8193                         # Install the missing file.  Symlink if we
8194                         # can, copy if we must.  Note: delete the file
8195                         # first, in case it is a dangling symlink.
8196                         $message = "installing `$errfile'";
8197                         # Windows Perl will hang if we try to delete a
8198                         # file that doesn't exist.
8199                         unlink ($errfile) if -f $errfile;
8200                         if ($symlink_exists && ! $copy_missing)
8201                         {
8202                             if (! symlink ("$libdir/$file", $errfile))
8203                             {
8204                                 $suppress = 0;
8205                                 $trailer = "; error while making link: $!";
8206                             }
8207                         }
8208                         elsif (system ('cp', "$libdir/$file", $errfile))
8209                         {
8210                             $suppress = 0;
8211                             $trailer = "\n    error while copying";
8212                         }
8213                     }
8215                     if (! maybe_push_required_file (dirname ($errfile),
8216                                                     $file, $errfile))
8217                     {
8218                         if (! $found_it)
8219                         {
8220                             # We have added the file but could not push it
8221                             # into DIST_COMMON (probably because this is
8222                             # an auxiliary file and we are not processing
8223                             # the top level Makefile). This is unfortunate,
8224                             # since it means we are using a file which is not
8225                             # distributed!
8227                             # Get Automake to be run again: on the second
8228                             # run the file will be found, and pushed into
8229                             # the toplevel DIST_COMMON automatically.
8230                             $automake_needs_to_reprocess_all_files = 1;
8231                         }
8232                     }
8234                     # Prune the path list.
8235                     @require_file_paths = &dirname ($errfile);
8236                 }
8238                 # If --force-missing was specified, and we have
8239                 # actually found the file, then do nothing.
8240                 next
8241                     if $found_it && $force_missing;
8243                 if ($suppress)
8244                 {
8245                   file_warning ($where, "$message$trailer");
8246                 }
8247                 else
8248                 {
8249                   file_error ($where, "$message$trailer");
8250                 }
8251             }
8252         }
8253     }
8256 # &require_file ($WHERE, $MYSTRICT, @FILES)
8257 # -----------------------------------------
8258 sub require_file ($$@)
8260     my ($where, $mystrict, @files) = @_;
8261     @require_file_paths = $relative_dir;
8262     require_file_internal ($where, $mystrict, @files);
8265 # &require_file_with_macro ($MACRO, $MYSTRICT, @FILES)
8266 # ----------------------------------------------------
8267 sub require_file_with_macro ($$@)
8269     my ($macro, $mystrict, @files) = @_;
8270     require_file ($var_location{$macro}, $mystrict, @files);
8274 # &require_conf_file ($WHERE, $MYSTRICT, @FILES)
8275 # ----------------------------------------------
8276 # Looks in configuration path, as specified by AC_CONFIG_AUX_DIR.
8277 sub require_conf_file ($$@)
8279     my ($where, $mystrict, @files) = @_;
8280     @require_file_paths = @config_aux_path;
8281     require_file_internal ($where, $mystrict, @files);
8282     my $dir = $require_file_paths[0];
8283     @config_aux_path = @require_file_paths;
8284      # Avoid unsightly '/.'s.
8285     $config_aux_dir = '$(top_srcdir)' . ($dir eq '.' ? "" : "/$dir");
8289 # &require_conf_file_with_macro ($MACRO, $MYSTRICT, @FILES)
8290 # ---------------------------------------------------------
8291 sub require_conf_file_with_macro ($$@)
8293     my ($macro, $mystrict, @files) = @_;
8294     require_conf_file ($var_location{$macro}, $mystrict, @files);
8297 ################################################################
8299 # &require_build_directory ($DIRECTORY)
8300 # ------------------------------------
8301 # Emit rules to create $DIRECTORY if needed, and return
8302 # the file that any target requiring this directory should be made
8303 # dependent upon.
8304 sub require_build_directory ($)
8306     my $directory = shift;
8307     my $dirstamp = "$directory/.dirstamp";
8309     # Don't emit the rule twice.
8310     if (! defined $directory_map{$directory})
8311     {
8312         $directory_map{$directory} = 1;
8314         # Directory must be removed by `make distclean'.
8315         $compile_clean_files{$dirstamp} = DIST_CLEAN;
8317         $output_rules .= ("$dirstamp:\n"
8318                           . "\t\@\$(mkinstalldirs) $directory\n"
8319                           . "\t\@: > $dirstamp\n");
8320     }
8322     return $dirstamp;
8325 # &require_build_directory_maybe ($FILE)
8326 # --------------------------------------
8327 # If $FILE lies in a subdirectory, emit a rule to create this
8328 # directory and return the file that $FILE should be made
8329 # dependent upon.  Otherwise, just return the empty string.
8330 sub require_build_directory_maybe ($)
8332     my $file = shift;
8333     my $directory = dirname ($file);
8335     if ($directory ne '.')
8336     {
8337         return require_build_directory ($directory);
8338     }
8339     else
8340     {
8341         return '';
8342     }
8345 ################################################################
8347 # Push a list of files onto dist_common.
8348 sub push_dist_common
8350     prog_error ("push_dist_common run after handle_dist")
8351         if $handle_dist_run;
8352     macro_define ('DIST_COMMON', 1, '+', '', "@_", '');
8356 # Set strictness.
8357 sub set_strictness
8359     $strictness_name = $_[0];
8360     if ($strictness_name eq 'gnu')
8361     {
8362         $strictness = GNU;
8363     }
8364     elsif ($strictness_name eq 'gnits')
8365     {
8366         $strictness = GNITS;
8367     }
8368     elsif ($strictness_name eq 'foreign')
8369     {
8370         $strictness = FOREIGN;
8371     }
8372     else
8373     {
8374         die "$me: level `$strictness_name' not recognized\n";
8375     }
8379 ################################################################
8381 # Glob something.  Do this to avoid indentation screwups everywhere we
8382 # want to glob.  Gross!
8383 sub my_glob
8385     my ($pat) = @_;
8386     return <${pat}>;
8389 # Remove one level of brackets and strip leading spaces,
8390 # as does m4 to function arguments.
8391 sub unquote_m4_arg
8393     $_ = shift;
8394     s/^\s*//;
8396     my @letters = split //;
8397     my @result = ();
8398     my $depth = 0;
8400     foreach (@letters)
8401     {
8402         if ($_ eq '[')
8403         {
8404             ++$depth;
8405             next if $depth == 1;
8406         }
8407         elsif ($_ eq ']')
8408         {
8409             --$depth;
8410             next if $depth == 0;
8411             # don't count orphan right brackets
8412             $depth = 0 if $depth < 0;
8413         }
8414         push @result, $_;
8415     }
8416     return join '', @result;
8419 ################################################################
8421 # print_error ($LEADER, @ARGS)
8422 # ----------------------------
8423 # Do the work of printing the error message.  Join @ARGS with spaces,
8424 # then split at newlines and add $LEADER to each line.  Uses `warn' to
8425 # print message.  Set exit status.
8426 sub print_error
8428     my ($leader, @args) = @_;
8429     my $text = "@args";
8430     @args = split ("\n", $text);
8431     $text = $leader . join ("\n" . $leader, @args) . "\n";
8432     warn $text;
8433     $exit_status = 1;
8437 # Print an error message and set exit status.
8438 sub am_error (@)
8440     print_error ("$me: ${am_file}.am: ", @_);
8444 # &file_error ($FILE, @ARGS)
8445 # --------------------------
8446 sub file_error ($@)
8448     my ($file, @args) = @_;
8449     print_error ("$file: ", @args);
8453 # &macro_error ($MACRO, @ARGS)
8454 # ----------------------------
8455 # Report an error, @ARGS, about $MACRO.
8456 sub macro_error ($@)
8458     my ($macro, @args) = @_;
8459     file_error ($var_location{$macro}, @args);
8463 # &target_error ($TARGET, @ARGS)
8464 # ------------------------------
8465 # Report an error, @ARGS, about the rule $TARGET.
8466 sub target_error ($@)
8468     my ($target, @args) = @_;
8469     file_error ($targets{$target}, @args);
8473 # Like am_error, but while scanning configure.ac.
8474 sub conf_error
8476     # FIXME: can run in subdirs.
8477     print_error ("$me: $configure_ac: ", @_);
8480 # &file_warning ($FILE, @ARGS)
8481 # ----------------------------
8482 # Warning message with line number referring to configure.ac.
8483 # Does not affect exit_status
8484 sub file_warning ($@)
8486     my ($file, @args) = @_;
8488     my $saved_exit_status = $exit_status;
8489     my $sig = $SIG{'__WARN__'};
8490     $SIG{'__WARN__'} = 'DEFAULT';
8491     file_error ($file, @args);
8492     $exit_status = $saved_exit_status;
8493     $SIG{'__WARN__'} = $sig;
8496 # Tell user where our aclocal.m4 is, but only once.
8497 sub keyed_aclocal_warning ($)
8499     my ($key) = @_;
8500     warn "$me: macro `$key' can be generated by `aclocal'\n";
8503 # Print usage information.
8504 sub usage ()
8506     print <<EOF;
8507 Usage: $0 [OPTION] ... [Makefile]...
8509 Generate Makefile.in for configure from Makefile.am.
8511 Operation modes:
8512       --help             print this help, then exit
8513       --version          print version number, then exit
8514   -v, --verbose          verbosely list files processed
8515       --no-force         only update Makefile.in's that are out of date
8517 Dependency tracking:
8518   -i, --ignore-deps      disable dependency tracking code
8519       --include-deps     enable dependency tracking code
8521 Flavors:
8522       --cygnus           assume program is part of Cygnus-style tree
8523       --foreign          set strictness to foreign
8524       --gnits            set strictness to gnits
8525       --gnu              set strictness to gnu
8527 Library files:
8528   -a, --add-missing      add missing standard files to package
8529       --libdir=DIR       directory storing library files
8530   -c, --copy             with -a, copy missing files (default is symlink)
8531   -f, --force-missing    force update of standard files
8534     my ($last, @lcomm);
8535     $last = '';
8536     foreach my $iter (sort ((@common_files, @common_sometimes)))
8537     {
8538         push (@lcomm, $iter) unless $iter eq $last;
8539         $last = $iter;
8540     }
8542     my @four;
8543     print "\nFiles which are automatically distributed, if found:\n";
8544     format USAGE_FORMAT =
8545   @<<<<<<<<<<<<<<<<   @<<<<<<<<<<<<<<<<   @<<<<<<<<<<<<<<<<   @<<<<<<<<<<<<<<<<
8546   $four[0],           $four[1],           $four[2],           $four[3]
8548     $~ = "USAGE_FORMAT";
8550     my $cols = 4;
8551     my $rows = int(@lcomm / $cols);
8552     my $rest = @lcomm % $cols;
8554     if ($rest)
8555     {
8556         $rows++;
8557     }
8558     else
8559     {
8560         $rest = $cols;
8561     }
8563     for (my $y = 0; $y < $rows; $y++)
8564     {
8565         @four = ("", "", "", "");
8566         for (my $x = 0; $x < $cols; $x++)
8567         {
8568             last if $y + 1 == $rows && $x == $rest;
8570             my $idx = (($x > $rest)
8571                        ?  ($rows * $rest + ($rows - 1) * ($x - $rest))
8572                        : ($rows * $x));
8574             $idx += $y;
8575             $four[$x] = $lcomm[$idx];
8576         }
8577         write;
8578     }
8580     print "\nReport bugs to <bug-automake\@gnu.org>.\n";
8582     exit 0;
8586 # &version ()
8587 # -----------
8588 # Print version information
8589 sub version ()
8591   print <<EOF;
8592 automake (GNU $PACKAGE) $VERSION
8593 Written by Tom Tromey <tromey\@redhat.com>.
8595 Copyright 2002 Free Software Foundation, Inc.
8596 This is free software; see the source for copying conditions.  There is NO
8597 warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
8599   exit 0;