*** empty log message ***
[automake.git] / automake.in
blob54e0eadac35bdc1971f41de9d5afd7e96f749ab2
1 #!@PERL@ -w
2 # -*- perl -*-
3 # @configure_input@
5 eval 'exec @PERL@ -S $0 ${1+"$@"}'
6     if 0;
8 # automake - create Makefile.in from Makefile.am
9 # Copyright 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 # Copyright on generated Makefile.ins.
219 my $gen_copyright = "\
220 # Copyright 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002
221 # Free Software Foundation, Inc.
222 # This Makefile.in is free software; the Free Software Foundation
223 # gives unlimited permission to copy and/or distribute it,
224 # with or without modifications, as long as this notice is preserved.
226 # This program is distributed in the hope that it will be useful,
227 # but WITHOUT ANY WARRANTY, to the extent permitted by law; without
228 # even the implied warranty of MERCHANTABILITY or FITNESS FOR A
229 # PARTICULAR PURPOSE.
232 # These constants are returned by lang_*_rewrite functions.
233 # LANG_SUBDIR means that the resulting object file should be in a
234 # subdir if the source file is.  In this case the file name cannot
235 # have `..' components.
236 my $LANG_IGNORE = 0;
237 my $LANG_PROCESS = 1;
238 my $LANG_SUBDIR = 2;
240 # These are used when keeping track of whether an object can be built
241 # by two different paths.
242 my $COMPILE_LIBTOOL = 1;
243 my $COMPILE_ORDINARY = 2;
245 # Map from obsolete macros to hints for new macros.
246 # If you change this, change the corresponding list in aclocal.in.
247 # FIXME: should just put this into a single file.
248 my %obsolete_macros =
249     (
250      'AC_FEATURE_CTYPE'         => "use `AC_HEADER_STDC'",
251      'AC_FEATURE_ERRNO'         => "add `strerror' to `AC_REPLACE_FUNCS(...)'",
252      'AC_FEATURE_EXIT'          => '',
253      'AC_SYSTEM_HEADER'         => '',
255      # Note that we do not handle this one, because it is still run
256      # from AM_CONFIG_HEADER.  So we deal with it specially in
257      # &scan_autoconf_files.
258      # 'AC_CONFIG_HEADER'       => "use `AM_CONFIG_HEADER'",
260      'fp_C_PROTOTYPES'          => "use `AM_C_PROTOTYPES'",
261      'fp_PROG_CC_STDC'          => "use `AM_PROG_CC_STDC'",
262      'fp_PROG_INSTALL'          => "use `AC_PROG_INSTALL'",
263      'fp_WITH_DMALLOC'          => "use `AM_WITH_DMALLOC'",
264      'fp_WITH_REGEX'            => "use `AM_WITH_REGEX'",
265      'gm_PROG_LIBTOOL'          => "use `AM_PROG_LIBTOOL'",
266      'jm_MAINTAINER_MODE'       => "use `AM_MAINTAINER_MODE'",
267      'md_TYPE_PTRDIFF_T'        => "add `ptrdiff_t' to `AC_CHECK_TYPES(...)'",
268      'ud_PATH_LISPDIR'          => "use `AM_PATH_LISPDIR'",
269      'ud_GNU_GETTEXT'           => "use `AM_GNU_GETTEXT'",
271      # Now part of autoconf proper, under a different name.
272      'fp_FUNC_FNMATCH'          => "use `AC_FUNC_FNMATCH'",
273      'AM_SANITY_CHECK_CC'       => "automatically done by `AC_PROG_CC'",
274      'AM_PROG_INSTALL'          => "use `AC_PROG_INSTALL'",
275      'AM_EXEEXT'                => "automatically done by `AC_PROG_(CC|CXX|F77)'",
276      'AM_CYGWIN32'              => "use `AC_CYGWIN'",
277      'AM_MINGW32'               => "use `AC_MINGW32'",
278      'AM_FUNC_MKTIME'           => "use `AC_FUNC_MKTIME'",
279      );
281 # Regexp to match the above macros.
282 my $obsolete_rx = '\b(' . join ('|', keys %obsolete_macros) . ')\b';
286 ## ---------------------------------- ##
287 ## Variables related to the options.  ##
288 ## ---------------------------------- ##
290 # TRUE if we should always generate Makefile.in.
291 my $force_generation = 1;
293 # Strictness level as set on command line.
294 my $default_strictness = GNU;
296 # Name of strictness level, as set on command line.
297 my $default_strictness_name = 'gnu';
299 # This is TRUE if automatic dependency generation code should be
300 # included in generated Makefile.in.
301 my $cmdline_use_dependencies = 1;
303 # This holds our (eventual) exit status.  We don't actually exit until
304 # we have processed all input files.
305 my $exit_status = 0;
307 # From the Perl manual.
308 my $symlink_exists = (eval 'symlink ("", "");', $@ eq '');
310 # TRUE if missing standard files should be installed.
311 my $add_missing = 0;
313 # TRUE if we should copy missing files; otherwise symlink if possible.
314 my $copy_missing = 0;
316 # TRUE if we should always update files that we know about.
317 my $force_missing = 0;
320 ## ---------------------------------------- ##
321 ## Variables filled during files scanning.  ##
322 ## ---------------------------------------- ##
324 # Name of the top autoconf input: `configure.ac' or `configure.in'.
325 my $configure_ac = '';
327 # Files found by scanning configure.ac for LIBOBJS.
328 my %libsources = ();
330 # True if AM_C_PROTOTYPES appears in configure.ac.
331 my $am_c_prototypes = 0;
333 # Names used in AC_CONFIG_HEADER call.
334 my @config_headers = ();
335 # Where AC_CONFIG_HEADER appears.
336 my $config_header_location;
338 # Directory where output files go.  Actually, output files are
339 # relative to this directory.
340 my $output_directory = '.';
342 # List of Makefile.am's to process, and their corresponding outputs.
343 my @input_files = ();
344 my %output_files = ();
346 # Complete list of Makefile.am's that exist.
347 my @configure_input_files = ();
349 # List of files in AC_CONFIG_FILES/AC_OUTPUT without Makefile.am's,
350 # and their outputs.
351 my @other_input_files = ();
352 # Where the last AC_CONFIG_FILES/AC_OUTPUT appears.
353 my $ac_config_files_location;
355 # List of directories to search for configure-required files.  This
356 # can be set by AC_CONFIG_AUX_DIR.
357 my @config_aux_path = qw(. .. ../..);
358 my $config_aux_dir = '';
359 my $config_aux_dir_set_in_configure_in = 0;
361 # Whether AM_GNU_GETTEXT has been seen in configure.ac.
362 my $seen_gettext = 0;
363 # Where AM_GNU_GETTEXT appears.
364 my $ac_gettext_location;
366 # TRUE if AC_PROG_LEX or AM_PROG_LEX were seen.
367 my $seen_prog_lex = 0;
369 # TRUE if we've seen AC_CANONICAL_(HOST|SYSTEM).
370 my $seen_canonical = 0;
371 my $canonical_location;
373 # Where AC_PROG_LIBTOOL appears.
374 my $seen_libtool;
376 # Where AM_MAINTAINER_MODE appears.
377 my $seen_maint_mode;
379 # Actual version we've seen.
380 my $package_version = '';
382 # Where version is defined.
383 my $package_version_location;
385 # Where AM_PATH_LISPDIR appears.
386 my $am_lispdir_location;
388 # Where AM_PATH_PYTHON appears.
389 my $pythondir_location;
391 # TRUE if we've seen AC_ENABLE_MULTILIB.
392 my $seen_multilib = 0;
394 # TRUE if we've seen AM_PROG_CC_C_O
395 my $seen_cc_c_o = 0;
397 # Where AM_INIT_AUTOMAKE is called;
398 my $seen_init_automake = 0;
400 # TRUE if we've seen AM_AUTOMAKE_VERSION.
401 my $seen_automake_version = 0;
403 # Hash table of discovered configure substitutions.  Keys are names,
404 # values are `FILE:LINE' strings which are used by error message
405 # generation.
406 my %configure_vars = ();
408 # This is used to keep track of which variable definitions we are
409 # scanning.  It is only used in certain limited ways, but it has to be
410 # global.  It is declared just for documentation purposes.
411 my %vars_scanned = ();
413 # TRUE if --cygnus seen.
414 my $cygnus_mode = 0;
416 # Hash table of AM_CONDITIONAL variables seen in configure.
417 my %configure_cond = ();
419 # This maps extensions onto language names.
420 my %extension_map = ();
422 # List of the DIST_COMMON files we discovered while reading
423 # configure.in
424 my $configure_dist_common = '';
426 # This maps languages names onto objects.
427 my %languages = ();
429 # List of targets we must always output.
430 # FIXME: Complete, and remove falsely required targets.
431 my %required_targets =
432   (
433    'all'          => 1,
434    'dvi'          => 1,
435    'info'         => 1,
436    'install-info' => 1,
437    'install'      => 1,
438    'install-data' => 1,
439    'install-exec' => 1,
440    'uninstall'    => 1,
442    # FIXME: Not required, temporary hacks.
443    # Well, actually they are sort of required: the -recursive
444    # targets will run them anyway...
445    'dvi-am'          => 1,
446    'info-am'         => 1,
447    'install-data-am' => 1,
448    'install-exec-am' => 1,
449    'installcheck-am' => 1,
450    'uninstall-am' => 1,
452    'install-man' => 1,
453   );
455 # This is set to 1 when Automake needs to be run again.
456 # (For instance, this happens when an auxiliary file such as
457 # depcomp is added after the toplevel Makefile.in -- which
458 # should distribute depcomp -- has been generated.)
459 my $automake_needs_to_reprocess_all_files = 0;
461 # Options set via AM_INIT_AUTOMAKE.
462 my $global_options = '';
466 ################################################################
468 ## ------------------------------------------ ##
469 ## Variables reset by &initialize_per_input.  ##
470 ## ------------------------------------------ ##
472 # Basename and relative dir of the input file.
473 my $am_file_name;
474 my $am_relative_dir;
476 # Same but wrt Makefile.in.
477 my $in_file_name;
478 my $relative_dir;
480 # These two variables are used when generating each Makefile.in.
481 # They hold the Makefile.in until it is ready to be printed.
482 my $output_rules;
483 my $output_vars;
484 my $output_trailer;
485 my $output_all;
486 my $output_header;
488 # Suffixes found during a run.
489 my @suffixes;
491 # Handling the variables.
493 # For a $VAR:
494 # - $var_value{$VAR}{$COND} is its value associated to $COND,
495 # - $var_location{$VAR} is where it was defined,
496 # - $var_comment{$VAR} are the comments associated to it.
497 # - $var_type{$VAR} is how it has been defined (`', `+', or `:'),
498 # - $var_is_am{$VAR} is true if the variable is owned by Automake.
499 my %var_value;
500 my %var_location;
501 my %var_comment;
502 my %var_type;
503 my %var_is_am;
505 # This holds a 1 if a particular variable was examined.
506 my %content_seen;
508 # This holds the names which are targets.  These also appear in
509 # %contents.
510 my %targets;
512 # Same as %VAR_VALUE, but for targets.
513 my %target_conditional;
515 # This is the conditional stack.
516 my @cond_stack;
518 # This holds the set of included files.
519 my @include_stack;
521 # This holds a list of directories which we must create at `dist'
522 # time.  This is used in some strange scenarios involving weird
523 # AC_OUTPUT commands.
524 my %dist_dirs;
526 # List of dependencies for the obvious targets.
527 my @all;
528 my @check;
529 my @check_tests;
531 # Holds the dependencies of targets which dependencies are factored.
532 # Typically, `.PHONY' will appear in plenty of *.am files, but must
533 # be output once.  Arguably all pure dependencies could be subject
534 # to this factorization, but it is not unpleasant to have paragraphs
535 # in Makefile: keeping related stuff altogether.
536 my %dependencies;
538 # Holds the factored actions.  Tied to %DEPENDENCIES, i.e., filled
539 # only when keys exists in %DEPENDENCIES.
540 my %actions;
542 # A list of files deleted by `maintainer-clean'.
543 my @maintainer_clean_files;
545 # Keys in this hash table are object files or other files in
546 # subdirectories which need to be removed.  This only holds files
547 # which are created by compilations.  The value in the hash indicates
548 # when the file should be removed.
549 my %compile_clean_files;
551 # Value of `$(SOURCES)', used by tags.am.
552 my @sources;
553 # Sources which go in the distribution.
554 my @dist_sources;
556 # This hash maps object file names onto their corresponding source
557 # file names.  This is used to ensure that each object is created
558 # by a single source file.
559 my %object_map;
561 # This hash maps object file names onto an integer value representing
562 # whether this object has been built via ordinary compilation or
563 # libtool compilation (the COMPILE_* constants).
564 my %object_compilation_map;
567 # This keeps track of the directories for which we've already
568 # created `.dirstamp' code.
569 my %directory_map;
571 # All .P files.
572 my %dep_files;
574 # Strictness levels.
575 my $strictness;
576 my $strictness_name;
578 # Options from AUTOMAKE_OPTIONS.
579 my %options;
581 # Whether or not dependencies are handled.  Can be further changed
582 # in handle_options.
583 my $use_dependencies;
585 # This is a list of all targets to run during "make dist".
586 my @dist_targets;
588 # Keys in this hash are the basenames of files which must depend on
589 # ansi2knr.  Values are either the empty string, or the directory in
590 # which the ANSI source file appears; the directory must have a
591 # trailing `/'.
592 my %de_ansi_files;
594 # This maps the source extension of a suffix rule to its
595 # corresponding output extension.
596 # FIXME: because this hash maps one input extension to one output
597 # extension, Automake cannot handle two suffix rules with the same
598 # input extension.
599 my %suffix_rules;
601 # This is the name of the redirect `all' target to use.
602 my $all_target;
604 # This keeps track of which extensions we've seen (that we care
605 # about).
606 my %extension_seen;
608 # This is random scratch space for the language finish functions.
609 # Don't randomly overwrite it; examine other uses of keys first.
610 my %language_scratch;
612 # We keep track of which objects need special (per-executable)
613 # handling on a per-language basis.
614 my %lang_specific_files;
616 # This is set when `handle_dist' has finished.  Once this happens,
617 # we should no longer push on dist_common.
618 my $handle_dist_run;
620 # Used to store a set of linkers needed to generate the sources currently
621 # under consideration.
622 my %linkers_used;
624 # True if we need `LINK' defined.  This is a hack.
625 my $need_link;
627 # This is the list of such variables to output.
628 # FIXME: Might be useless actually.
629 my @var_list;
631 # Was get_object_extension run?
632 # FIXME: This is a hack. a better switch should be found.
633 my $get_object_extension_was_run;
635 # Contains a stack of `from' parts of variable substitutions currently in
636 # force.
637 my @substfroms;
639 # Contains a stack of `to' parts of variable substitutions currently in
640 # force.
641 my @substtos;
643 # Associates a variable name, together with a list of substitutions to be
644 # performed on it, with a number.  Used to provide unique names for generated
645 # variables.
646 my %substnums = ();
648 ## --------------------------------- ##
649 ## Forward subroutine declarations.  ##
650 ## --------------------------------- ##
651 sub register_language (%);
652 sub file_contents_internal ($$%);
653 sub define_objects_from_sources ($$$$$$$);
656 # &initialize_per_input ()
657 # ------------------------
658 # (Re)-Initialize per-Makefile.am variables.
659 sub initialize_per_input ()
661     $am_file_name = '';
662     $am_relative_dir = '';
664     $in_file_name = '';
665     $relative_dir = '';
667     $output_rules = '';
668     $output_vars = '';
669     $output_trailer = '';
670     $output_all = '';
671     $output_header = '';
673     @suffixes = ();
675     %var_value = ();
676     %var_location = ();
677     %var_comment = ();
678     %var_type = ();
679     %var_is_am = ();
681     %content_seen = ();
683     %targets = ();
685     %target_conditional = ();
687     @cond_stack = ();
689     @include_stack = ();
691     %dist_dirs = ();
693     @all = ();
694     @check = ();
695     @check_tests = ();
697     %dependencies =
698       (
699        # Texinfoing.
700        'dvi'      => [],
701        'dvi-am'   => [],
702        'info'     => [],
703        'info-am'  => [],
705        # Installing/uninstalling.
706        'install-data-am'      => [],
707        'install-exec-am'      => [],
708        'uninstall-am'         => [],
710        'install-man'          => [],
711        'uninstall-man'        => [],
713        'install-info'         => [],
714        'install-info-am'      => [],
715        'uninstall-info'       => [],
717        'installcheck-am'      => [],
719        # Cleaning.
720        'clean-am'             => [],
721        'mostlyclean-am'       => [],
722        'maintainer-clean-am'  => [],
723        'distclean-am'         => [],
724        'clean'                => [],
725        'mostlyclean'          => [],
726        'maintainer-clean'     => [],
727        'distclean'            => [],
729        # Tarballing.
730        'dist-all'             => [],
732        # Phoning.
733        '.PHONY'               => []
734       );
735     %actions = ();
737     @maintainer_clean_files = ();
739     @sources = ();
740     @dist_sources = ();
742     %object_map = ();
743     %object_compilation_map = ();
745     %directory_map = ();
747     %dep_files = ();
749     $strictness = $default_strictness;
750     $strictness_name = $default_strictness_name;
752     %options = ();
754     $use_dependencies = $cmdline_use_dependencies;
756     @dist_targets = ();
758     %de_ansi_files = ();
760     %suffix_rules = ();
762     $all_target = '';
764     %extension_seen = ();
766     %language_scratch = ();
768     %lang_specific_files = ();
770     $handle_dist_run = 0;
772     $need_link = 0;
774     @var_list = ();
776     $get_object_extension_was_run = 0;
778     %compile_clean_files = ();
782 ################################################################
784 # Initialize our list of languages that are internally supported.
786 # C.
787 register_language ('name' => 'c',
788                    'Name' => 'C',
789                    'config_vars' => ['CC'],
790                    'ansi' => 1,
791                    'autodep' => '',
792                    'flags' => 'CFLAGS',
793                    'compiler' => 'COMPILE',
794                    'compile' => '$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS)',
795                    'lder' => 'CCLD',
796                    'ld' => '$(CC)',
797                    'linker' => 'LINK',
798                    'link' => '$(CCLD) $(AM_CFLAGS) $(CFLAGS) $(AM_LDFLAGS) $(LDFLAGS) -o $@',
799                    'compile_flag' => '-c',
800                    'extensions' => ['.c'],
801                    '_finish' => \&lang_c_finish);
803 # C++.
804 register_language ('name' => 'cxx',
805                    'Name' => 'C++',
806                    'config_vars' => ['CXX'],
807                    'linker' => 'CXXLINK',
808                    'link' => '$(CXXLD) $(AM_CXXFLAGS) $(CXXFLAGS) $(AM_LDFLAGS) $(LDFLAGS) -o $@',
809                    'autodep' => 'CXX',
810                    'flags' => 'CXXFLAGS',
811                    'compile' => '$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS)',
812                    'compiler' => 'CXXCOMPILE',
813                    'compile_flag' => '-c',
814                    'output_flag' => '-o',
815                    'lder' => 'CXXLD',
816                    'ld' => '$(CXX)',
817                    'pure' => 1,
818                    'extensions' => ['.c++', '.cc', '.cpp', '.cxx', '.C']);
820 # Objective C.
821 register_language ('name' => 'objc',
822                    'Name' => 'Objective C',
823                    'config_vars' => ['OBJC'],
824                    'linker' => 'OBJCLINK',,
825                    'link' => '$(OBJCLD) $(AM_OBJCFLAGS) $(OBJCFLAGS) $(AM_LDFLAGS) $(LDFLAGS) -o $@',
826                    'autodep' => 'OBJC',
827                    'flags' => 'OBJCFLAGS',
828                    'compile' => '$(OBJC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_OBJCFLAGS) $(OBJCFLAGS)',
829                    'compiler' => 'OBJCCOMPILE',
830                    'compile_flag' => '-c',
831                    'output_flag' => '-o',
832                    'lder' => 'OBJCLD',
833                    'ld' => '$(OBJC)',
834                    'pure' => 1,
835                    'extensions' => ['.m']);
837 # Headers.
838 register_language ('name' => 'header',
839                    'Name' => 'Header',
840                    'extensions' => ['.h', '.H', '.hxx', '.h++', '.hh',
841                                     '.hpp', '.inc'],
842                    # Nothing to do.
843                    '_finish' => sub { });
845 # Yacc (C & C++).
846 register_language ('name' => 'yacc',
847                    'Name' => 'Yacc',
848                    'config_vars' => ['YACC'],
849                    'flags' => 'YFLAGS',
850                    'define_flag' => 0,
851                    'compile' => '$(YACC) $(YFLAGS) $(AM_YFLAGS)',
852                    'compiler' => 'YACCCOMPILE',
853                    'extensions' => ['.y'],
854                    'rule_file' => 'yacc',
855                    '_finish' => \&lang_yacc_finish,
856                    '_target_hook' => \&lang_yacc_target_hook);
857 register_language ('name' => 'yaccxx',
858                    'Name' => 'Yacc (C++)',
859                    'config_vars' => ['YACC'],
860                    'rule_file' => 'yacc',
861                    'flags' => 'YFLAGS',
862                    'define_flag' => 0,
863                    'compiler' => 'YACCCOMPILE',
864                    'compile' => '$(YACC) $(YFLAGS) $(AM_YFLAGS)',
865                    'extensions' => ['.y++', '.yy', '.yxx', '.ypp'],
866                    '_finish' => \&lang_yacc_finish,
867                    '_target_hook' => \&lang_yacc_target_hook);
869 # Lex (C & C++).
870 register_language ('name' => 'lex',
871                    'Name' => 'Lex',
872                    'config_vars' => ['LEX'],
873                    'rule_file' => 'lex',
874                    'flags' => 'LFLAGS',
875                    'define_flag' => 0,
876                    'compile' => '$(LEX) $(LFLAGS) $(AM_LFLAGS)',
877                    'compiler' => 'LEXCOMPILE',
878                    'extensions' => ['.l'],
879                    '_finish' => \&lang_lex_finish);
880 register_language ('name' => 'lexxx',
881                    'Name' => 'Lex (C++)',
882                    'config_vars' => ['LEX'],
883                    'rule_file' => 'lex',
884                    'flags' => 'LFLAGS',
885                    'define_flag' => 0,
886                    'compile' => '$(LEX) $(LFLAGS) $(AM_LFLAGS)',
887                    'compiler' => 'LEXCOMPILE',
888                    'extensions' => ['.l++', '.ll', '.lxx', '.lpp'],
889                    '_finish' => \&lang_lex_finish);
891 # Assembler.
892 register_language ('name' => 'asm',
893                    'Name' => 'Assembler',
894                    'config_vars' => ['CCAS', 'CCASFLAGS'],
896                    'flags' => 'CCASFLAGS',
897                    # Users can set AM_ASFLAGS to includes DEFS, INCLUDES,
898                    # or anything else required.  They can also set AS.
899                    'compile' => '$(CCAS) $(AM_CCASFLAGS) $(CCASFLAGS)',
900                    'compiler' => 'CCASCOMPILE',
901                    'compile_flag' => '-c',
902                    'extensions' => ['.s', '.S'],
904                    # With assembly we still use the C linker.
905                    '_finish' => \&lang_c_finish);
907 # Fortran 77
908 register_language ('name' => 'f77',
909                    'Name' => 'Fortran 77',
910                    'linker' => 'F77LINK',
911                    'link' => '$(F77LD) $(AM_FFLAGS) $(FFLAGS) $(AM_LDFLAGS) $(LDFLAGS) -o $@',
912                    'flags' => 'FFLAGS',
913                    'compile' => '$(F77) $(AM_FFLAGS) $(FFLAGS)',
914                    'compiler' => 'F77COMPILE',
915                    'compile_flag' => '-c',
916                    'output_flag' => '-o',
917                    'lder' => 'F77LD',
918                    'ld' => '$(F77)',
919                    'pure' => 1,
920                    'extensions' => ['.f', '.for', '.f90']);
922 # Preprocessed Fortran 77
924 # The current support for preprocessing Fortran 77 just involves
925 # passing `$(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS)
926 # $(CPPFLAGS)' as additional flags to the Fortran 77 compiler, since
927 # this is how GNU Make does it; see the `GNU Make Manual, Edition 0.51
928 # for `make' Version 3.76 Beta' (specifically, from info file
929 # `(make)Catalogue of Rules').
931 # A better approach would be to write an Autoconf test
932 # (i.e. AC_PROG_FPP) for a Fortran 77 preprocessor, because not all
933 # Fortran 77 compilers know how to do preprocessing.  The Autoconf
934 # macro AC_PROG_FPP should test the Fortran 77 compiler first for
935 # preprocessing capabilities, and then fall back on cpp (if cpp were
936 # available).
937 register_language ('name' => 'ppf77',
938                    'Name' => 'Preprocessed Fortran 77',
939                    'config_vars' => ['F77'],
940                    'linker' => 'F77LINK',
941                    'link' => '$(F77LD) $(AM_FFLAGS) $(FFLAGS) $(AM_LDFLAGS) $(LDFLAGS) -o $@',
942                    'lder' => 'F77LD',
943                    'ld' => '$(F77)',
944                    'flags' => 'FFLAGS',
945                    'compiler' => 'PPF77COMPILE',
946                    'compile' => '$(F77) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_FFLAGS) $(FFLAGS)',
947                    'compile_flag' => '-c',
948                    'output_flag' => '-o',
949                    'pure' => 1,
950                    'extensions' => ['.F']);
952 # Ratfor.
953 register_language ('name' => 'ratfor',
954                    'Name' => 'Ratfor',
955                    'config_vars' => ['F77'],
956                    'linker' => 'F77LINK',
957                    'link' => '$(F77LD) $(AM_FFLAGS) $(FFLAGS) $(AM_LDFLAGS) $(LDFLAGS) -o $@',
958                    'lder' => 'F77LD',
959                    'ld' => '$(F77)',
960                    'flags' => 'RFLAGS',
961                    # FIXME also FFLAGS.
962                    'compile' => '$(F77) $(AM_FFLAGS) $(FFLAGS) $(AM_RFLAGS) $(RFLAGS)',
963                    'compiler' => 'RCOMPILE',
964                    'compile_flag' => '-c',
965                    'output_flag' => '-o',
966                    'pure' => 1,
967                    'extensions' => ['.r']);
969 # Java via gcj.
970 register_language ('name' => 'java',
971                    'Name' => 'Java',
972                    'config_vars' => ['GCJ'],
973                    'linker' => 'GCJLINK',
974                    'link' => '$(GCJLD) $(AM_GCJFLAGS) $(GCJFLAGS) $(AM_LDFLAGS) $(LDFLAGS) -o $@',
975                    'autodep' => 'GCJ',
976                    'flags' => 'GCJFLAGS',
977                    'compile' => '$(GCJ) $(AM_GCJFLAGS) $(GCJFLAGS)',
978                    'compiler' => 'GCJCOMPILE',
979                    'compile_flag' => '-c',
980                    'output_flag' => '-o',
981                    'lder' => 'GCJLD',
982                    'ld' => '$(GCJ)',
983                    'pure' => 1,
984                    'extensions' => ['.java', '.class', '.zip', '.jar']);
986 ################################################################
988 # Parse command line.
989 &parse_arguments;
991 # Do configure.ac scan only once.
992 &scan_autoconf_files;
994 die "$me: no `Makefile.am' found or specified\n"
995     if ! @input_files;
997 my $automake_has_run = 0;
1001     if ($automake_has_run)
1002     {
1003         print "$me: processing Makefiles another time to fix them up.\n";
1004         &prog_error ("running more than two times should never be needed.")
1005             if $automake_has_run >= 2;
1006     }
1007     $automake_needs_to_reprocess_all_files = 0;
1009     # Now do all the work on each file.
1010     # This guy must be local otherwise it's private to the loop.
1011     use vars '$am_file';
1012     local $am_file;
1013     foreach $am_file (@input_files)
1014     {
1015         if (! -f ($am_file . '.am'))
1016         {
1017             &am_error ("`" . $am_file . ".am' does not exist");
1018         }
1019         else
1020         {
1021             &generate_makefile ($output_files{$am_file}, $am_file);
1022         }
1023     }
1024     ++$automake_has_run;
1026 while ($automake_needs_to_reprocess_all_files);
1028 exit $exit_status;
1030 # FIXME: This should be `my'ed next to its subs.
1031 use vars '%require_file_found';
1033 ################################################################
1035 # prog_error (@PRINT-ME)
1036 # ----------------------
1037 # Signal a programming error, display PRINT-ME, and exit 1.
1038 sub prog_error (@)
1040     print STDERR "$me: programming error: @_\n";
1041     exit 1;
1045 # subst ($TEXT)
1046 # -------------
1047 # Return a configure-style substitution using the indicated text.
1048 # We do this to avoid having the substitutions directly in automake.in;
1049 # when we do that they are sometimes removed and this causes confusion
1050 # and bugs.
1051 sub subst ($)
1053     my ($text) = @_;
1054     return '@' . $text . '@';
1057 ################################################################
1060 # $BACKPATH
1061 # &backname ($REL-DIR)
1062 # --------------------
1063 # If I `cd $REL-DIR', then to come back, I should `cd $BACKPATH'.
1064 # For instance `src/foo' => `../..'.
1065 # Works with non strictly increasing paths, i.e., `src/../lib' => `..'.
1066 sub backname ($)
1068     my ($file) = @_;
1069     my @res;
1070     foreach (split (/\//, $file))
1071     {
1072         next if $_ eq '.' || $_ eq '';
1073         if ($_ eq '..')
1074         {
1075             pop @res;
1076         }
1077         else
1078         {
1079             push (@res, '..');
1080         }
1081     }
1082     return join ('/', @res) || '.';
1085 ################################################################
1087 # Pattern that matches all know input extensions (i.e. extensions used
1088 # by the languages supported by Automake).  Using this pattern
1089 # (instead of `\..*$') to match extensions allows Automake to support
1090 # dot-less extensions.
1091 my $KNOWN_EXTENSIONS_PATTERN = "";
1092 my @known_extensions_list = ();
1094 # accept_extensions (@EXTS)
1095 # -------------------------
1096 # Update $KNOWN_EXTENSIONS_PATTERN to recognize the extensions
1097 # listed @EXTS.  Extensions should contain a dot if needed.
1098 sub accept_extensions (@)
1100     push @known_extensions_list, @_;
1101     $KNOWN_EXTENSIONS_PATTERN =
1102         '(?:' . join ('|', map (quotemeta, @known_extensions_list)) . ')';
1105 # var_SUFFIXES_trigger ($TYPE, $VALUE)
1106 # ------------------------------------
1107 # This is called automagically by define_macro() when SUFFIXES
1108 # is defined ($TYPE eq '') or appended ($TYPE eq '+').
1109 # The work here needs to be performed as a side-effect of the
1110 # define_macro() call because SUFFIXES definitions impact
1111 # on $KNOWN_EXTENSIONS_PATTERN, and $KNOWN_EXTENSIONS_PATTERN
1112 # are used when parsing the input am file.
1113 sub var_SUFFIXES_trigger ($$)
1115     my ($type, $value) = @_;
1116     accept_extensions (split (' ', $value));
1119 ################################################################
1121 # Parse command line.
1122 sub parse_arguments ()
1124     # Start off as gnu.
1125     &set_strictness ('gnu');
1127     use Getopt::Long;
1128     Getopt::Long::config ("bundling", "pass_through");
1129     Getopt::Long::GetOptions
1130       (
1131        'version'        => \&version,
1132        'help'           => \&usage,
1133        'libdir:s'       => \$libdir,
1134        'gnu'            => sub { &set_strictness ('gnu'); },
1135        'gnits'          => sub { &set_strictness ('gnits'); },
1136        'cygnus'         => \$cygnus_mode,
1137        'foreign'        => sub { &set_strictness ('foreign'); },
1138        'include-deps'   => sub { $cmdline_use_dependencies = 1; },
1139        'i|ignore-deps'  => sub { $cmdline_use_dependencies = 0; },
1140        'no-force'       => sub { $force_generation = 0; },
1141        'f|force-missing'=> \$force_missing,
1142        'o|output-dir:s' => \$output_directory,
1143        'a|add-missing'  => \$add_missing,
1144        'c|copy'         => \$copy_missing,
1145        'v|verbose'      => \$verbose,
1146        'Werror'         => sub { $SIG{"__WARN__"} = sub { die $_[0] } },
1147        'Wno-error'      => sub { $SIG{"__WARN__"} = 'DEFAULT' }
1148       )
1149         or exit 1;
1151     foreach my $arg (@ARGV)
1152     {
1153       if ($arg =~ /^-./)
1154         {
1155           print STDERR "$0: unrecognized option `$arg'\n";
1156           print STDERR "Try `$0 --help' for more information.\n";
1157           exit (1);
1158         }
1160       # Handle $local:$input syntax.  Note that we only examine the
1161       # first ":" file to see if it is automake input; the rest are
1162       # just taken verbatim.  We still keep all the files around for
1163       # dependency checking, however.
1164       my ($local, $input, @rest) = split (/:/, $arg);
1165       if (! $input)
1166         {
1167           $input = $local;
1168         }
1169       else
1170         {
1171           # Strip .in; later on .am is tacked on.  That is how the
1172           # automake input file is found.  Maybe not the best way, but
1173           # it is easy to explain.
1174           $input =~ s/\.in$//
1175             or die "$me: invalid input file name `$arg'\n.";
1176         }
1177       push (@input_files, $input);
1178       $output_files{$input} = join (':', ($local, @rest));
1179     }
1181     # Take global strictness from whatever we currently have set.
1182     $default_strictness = $strictness;
1183     $default_strictness_name = $strictness_name;
1186 ################################################################
1188 # Generate a Makefile.in given the name of the corresponding Makefile and
1189 # the name of the file output by config.status.
1190 sub generate_makefile
1192     my ($output, $makefile) = @_;
1194     # Reset all the Makefile.am related variables.
1195     &initialize_per_input;
1197     # Name of input file ("Makefile.am") and output file
1198     # ("Makefile.in").  These have no directory components.
1199     $am_file_name = basename ($makefile) . '.am';
1200     $in_file_name = basename ($makefile) . '.in';
1202     # $OUTPUT is encoded.  If it contains a ":" then the first element
1203     # is the real output file, and all remaining elements are input
1204     # files.  We don't scan or otherwise deal with these input file,
1205     # other than to mark them as dependencies.  See
1206     # &scan_autoconf_files for details.
1207     my (@secondary_inputs);
1208     ($output, @secondary_inputs) = split (/:/, $output);
1210     $relative_dir = dirname ($output);
1211     $am_relative_dir = dirname ($makefile);
1213     &read_main_am_file ($makefile . '.am');
1214     if (&handle_options)
1215     {
1216         # Fatal error.  Just return, so we can continue with next file.
1217         return;
1218     }
1220     # There are a few install-related variables that you should not define.
1221     foreach my $var ('PRE_INSTALL', 'POST_INSTALL', 'NORMAL_INSTALL')
1222     {
1223         if (variable_defined ($var) && !$var_is_am{$var})
1224         {
1225             macro_error ($var, "`$var' should not be defined");
1226         }
1227     }
1229     &handle_libtool;
1231     # At the toplevel directory, we might need config.guess, config.sub
1232     # or libtool scripts (ltconfig and ltmain.sh).
1233     if ($relative_dir eq '.')
1234     {
1235         # AC_CANONICAL_HOST and AC_CANONICAL_SYSTEM need config.guess and
1236         # config.sub.
1237         require_conf_file ($canonical_location, FOREIGN,
1238                            'config.guess', 'config.sub')
1239           if $seen_canonical;
1240     }
1242     # We still need Makefile.in here, because sometimes the `dist'
1243     # target doesn't re-run automake.
1244     if ($am_relative_dir eq $relative_dir)
1245     {
1246         # Only distribute the files if they are in the same subdir as
1247         # the generated makefile.
1248         &push_dist_common ($in_file_name, $am_file_name);
1249     }
1251     push (@sources, '$(SOURCES)')
1252         if variable_defined ('SOURCES');
1254     # Must do this after reading .am file.  See read_main_am_file to
1255     # understand weird tricks we play there with variables.
1256     &define_variable ('subdir', $relative_dir);
1258     # Check first, because we might modify some state.
1259     &check_cygnus;
1260     &check_gnu_standards;
1261     &check_gnits_standards;
1263     &handle_configure ($output, $makefile, @secondary_inputs);
1264     &handle_gettext;
1265     &handle_libraries;
1266     &handle_ltlibraries;
1267     &handle_programs;
1268     &handle_scripts;
1270     # This must run first so that the ANSI2KNR definition is generated
1271     # before it is used by the _.c rules.  We have to do this because
1272     # a variable which is used in a dependency must be defined before
1273     # the target, or else make won't properly see it.
1274     &handle_compile;
1275     # This must be run after all the sources are scanned.
1276     &handle_languages;
1278     # Re-init SOURCES.  FIXME: other code shouldn't depend on this
1279     # (but currently does).
1280     macro_define ('SOURCES', 1, '', 'TRUE', "@sources", 'internal');
1281     define_pretty_variable ('DIST_SOURCES', '', @dist_sources);
1283     &handle_multilib;
1284     &handle_texinfo;
1285     &handle_emacs_lisp;
1286     &handle_python;
1287     &handle_java;
1288     &handle_man_pages;
1289     &handle_data;
1290     &handle_headers;
1291     &handle_subdirs;
1292     &handle_tags;
1293     &handle_minor_options;
1294     &handle_tests;
1296     # This must come after most other rules.
1297     &handle_dist ($makefile);
1299     &handle_footer;
1300     &do_check_merge_target;
1301     &handle_all ($output);
1303     # FIXME: Gross!
1304     if (variable_defined ('lib_LTLIBRARIES') &&
1305         variable_defined ('bin_PROGRAMS'))
1306     {
1307         $output_rules .= "install-binPROGRAMS: install-libLTLIBRARIES\n\n";
1308     }
1310     &handle_installdirs;
1311     &handle_clean;
1312     &handle_factored_dependencies;
1314     check_typos ();
1316     if (! -d ($output_directory . '/' . $am_relative_dir))
1317     {
1318         mkdir ($output_directory . '/' . $am_relative_dir, 0755);
1319     }
1321     my ($out_file) = $output_directory . '/' . $makefile . ".in";
1322     if (! $force_generation && -e $out_file)
1323     {
1324         my ($am_time) = (stat ($makefile . '.am'))[9];
1325         my ($in_time) = (stat ($out_file))[9];
1326         # FIXME: should cache these times.
1327         my ($conf_time) = (stat ($configure_ac))[9];
1328         # FIXME: how to do unsigned comparison?
1329         if ($am_time < $in_time || $am_time < $conf_time)
1330         {
1331             # No need to update.
1332             return;
1333         }
1334         if (-f 'aclocal.m4')
1335         {
1336             my ($acl_time) = (stat _)[9];
1337             return if ($am_time < $acl_time);
1338         }
1339     }
1341     if (-e "$out_file")
1342     {
1343         unlink ($out_file)
1344             or die "$me: cannot remove $out_file: $!\n";
1345     }
1346     my $gm_file = new Automake::XFile "> $out_file";
1347     verbose "creating ", $makefile, ".in";
1349     print $gm_file $output_vars;
1350     # We make sure that `all:' is the first target.
1351     print $gm_file $output_all;
1352     print $gm_file $output_header;
1353     print $gm_file $output_rules;
1354     print $gm_file $output_trailer;
1357 ################################################################
1359 # A helper which handles the logic of requiring a version number in
1360 # AUTOMAKE_OPTIONS.  Return 1 on error, 0 on success.
1361 sub version_check ($$$$)
1363     my ($rmajor, $rminor, $ralpha, $rfork) = ($1, $2, $3, $4);
1365     prog_error ("version is incorrect: $VERSION")
1366         if $VERSION !~ /(\d+)\.(\d+)([a-z]?)-?([A-Za-z0-9]+)?/;
1368     my ($tmajor, $tminor, $talpha, $tfork) = ($1, $2, $3, $4);
1370     $rfork ||= '';
1371     $tfork ||= '';
1373     my $rminorminor = 0;
1374     my $tminorminor = 0;
1376     # Some versions were labelled like `1.4-p3a'.  This is the same as
1377     # an alpha release labelled `1.4.3a'.  However, a version like
1378     # `1.4g' is the same as `1.4.99g'.  Yes, this sucks.  Moral:
1379     # always listen to the users.
1380     if ($rfork =~ /p([0-9]+)([a-z]?)/)
1381     {
1382         $rminorminor = $1;
1383         # `1.4a-p3b' never existed.  But we'll accept it anyway.
1384         $ralpha = $ralpha || $2 || '';
1385         $rfork = '';
1386     }
1387     if ($tfork =~ /p([0-9]+)([a-z]?)/)
1388     {
1389         $tminorminor = $1;
1390         # `1.4a-p3b' never existed.  But we'll accept it anyway.
1391         $talpha = $talpha || $2 || '';
1392         $tfork = '';
1393     }
1395     $rminorminor = 99 if $ralpha ne '' && $rminorminor == 0;
1396     $tminorminor = 99 if $talpha ne '' && $tminorminor == 0;
1398     # 2.0 is better than 1.0.
1399     # 1.2 is better than 1.1.
1400     # 1.2a is better than 1.2.
1401     # If we require 3.4n-foo then we require something
1402     # >= 3.4n, with the `foo' fork identifier.
1403     # The $r* variables are what the user specified.
1404     # The $t* variables denote automake itself.
1405     if ($rmajor > $tmajor
1406         || ($rmajor == $tmajor && $rminor > $tminor)
1407         || ($rminor == $tminor && $rminor == $tminor
1408             && $rminorminor > $tminorminor)
1409         || ($rminor == $tminor && $rminor == $tminor
1410             && $rminorminor == $tminorminor
1411             && $ralpha gt $talpha)
1412         || ($rfork ne '' && $rfork ne $tfork))
1413     {
1414         macro_error ('AUTOMAKE_OPTIONS',
1415                      "require version $_, but have $VERSION");
1416         return 1;
1417     }
1419     return 0;
1422 # $BOOL
1423 # process_option_list ($CONFIG, @OPTIONS)
1424 # ------------------------------
1425 # Process a list of options.  Return 1 on error, 0 otherwise.
1426 # This is a helper for handle_options.  CONFIG is true if we're
1427 # handling global options.
1428 sub process_option_list
1430     my ($config, @list) = @_;
1431     foreach (@list)
1432     {
1433         $options{$_} = 1;
1434         if ($_ eq 'gnits' || $_ eq 'gnu' || $_ eq 'foreign')
1435         {
1436             &set_strictness ($_);
1437         }
1438         elsif ($_ eq 'cygnus')
1439         {
1440             $cygnus_mode = 1;
1441         }
1442         elsif (/^(.*\/)?ansi2knr$/)
1443         {
1444             # An option like "../lib/ansi2knr" is allowed.  With no
1445             # path prefix, we assume the required programs are in this
1446             # directory.  We save the actual option for later.
1447             $options{'ansi2knr'} = $_;
1448         }
1449         elsif ($_ eq 'no-installman' || $_ eq 'no-installinfo'
1450                || $_ eq 'dist-shar' || $_ eq 'dist-zip'
1451                || $_ eq 'dist-tarZ' || $_ eq 'dist-bzip2'
1452                || $_ eq 'dejagnu' || $_ eq 'no-texinfo.tex'
1453                || $_ eq 'readme-alpha' || $_ eq 'check-news'
1454                || $_ eq 'subdir-objects' || $_ eq 'nostdinc'
1455                || $_ eq 'no-exeext' || $_ eq 'no-define')
1456         {
1457             # Explicitly recognize these.
1458         }
1459         elsif ($_ eq 'no-dependencies')
1460         {
1461             $use_dependencies = 0;
1462         }
1463         elsif (/(\d+)\.(\d+)([a-z]?)(-[A-Za-z0-9]+)?/)
1464         {
1465             # Got a version number.
1466             if (version_check ($1, $2, $3, $4))
1467             {
1468                 return 1;
1469             }
1470         }
1471         else
1472         {
1473             if ($config)
1474             {
1475                 file_error ($seen_init_automake,
1476                             "option `" . $_ . "\' not recognized");
1477             }
1478             else
1479             {
1480                 macro_error ('AUTOMAKE_OPTIONS',
1481                              "option `" . $_ . "\' not recognized");
1482             }
1483             return 1;
1484         }
1485     }
1488 # Handle AUTOMAKE_OPTIONS variable.  Return 1 on error, 0 otherwise.
1489 sub handle_options
1491     # Process global options first so that more specific options can
1492     # override.
1493     if (&process_option_list (1, split (' ', $global_options)))
1494     {
1495         return 1;
1496     }
1498     if (variable_defined ('AUTOMAKE_OPTIONS'))
1499     {
1500         if (&process_option_list (0, &variable_value_as_list_recursive ('AUTOMAKE_OPTIONS', '')))
1501         {
1502             return 1;
1503         }
1504     }
1506     if ($strictness == GNITS)
1507     {
1508         $options{'readme-alpha'} = 1;
1509         $options{'check-news'} = 1;
1510     }
1512     return 0;
1516 # get_object_extension ($OUT)
1517 # ---------------------------
1518 # Return object extension.  Just once, put some code into the output.
1519 # OUT is the name of the output file
1520 sub get_object_extension
1522     my ($out) = @_;
1524     # Maybe require libtool library object files.
1525     my $extension = '.$(OBJEXT)';
1526     $extension = '.lo' if ($out =~ /\.la$/);
1528     # Check for automatic de-ANSI-fication.
1529     $extension = '$U' . $extension
1530       if defined $options{'ansi2knr'};
1532     $get_object_extension_was_run = 1;
1534     return $extension;
1538 # Call finish function for each language that was used.
1539 sub handle_languages
1541     if ($use_dependencies)
1542     {
1543         # Include auto-dep code.  Don't include it if DEP_FILES would
1544         # be empty.
1545         if (&saw_sources_p (0) && keys %dep_files)
1546         {
1547             # Set location of depcomp.
1548             &define_variable ('depcomp', "\$(SHELL) $config_aux_dir/depcomp");
1549             &define_variable ('am__depfiles_maybe', 'depfiles');
1551             require_conf_file ("$am_file.am", FOREIGN, 'depcomp');
1553             my @deplist = sort keys %dep_files;
1555             # We define this as a conditional variable because BSD
1556             # make can't handle backslashes for continuing comments on
1557             # the following line.
1558             define_pretty_variable ('DEP_FILES', 'AMDEP_TRUE', @deplist);
1560             # Generate each `include' individually.  Irix 6 make will
1561             # not properly include several files resulting from a
1562             # variable expansion; generating many separate includes
1563             # seems safest.
1564             $output_rules .= "\n";
1565             foreach my $iter (@deplist)
1566             {
1567                 $output_rules .= (subst ('AMDEP_TRUE')
1568                                   . subst ('am__include')
1569                                   . ' '
1570                                   . subst ('am__quote')
1571                                   . $iter
1572                                   . subst ('am__quote')
1573                                   . "\n");
1574             }
1576             # Compute the set of directories to remove in distclean-depend.
1577             my @depdirs = uniq (map { dirname ($_) } @deplist);
1578             $output_rules .= &file_contents ('depend',
1579                                              DEPDIRS => "@depdirs");
1580         }
1581     }
1582     else
1583     {
1584         &define_variable ('depcomp', '');
1585         &define_variable ('am__depfiles_maybe', '');
1586     }
1588     my %done;
1590     # Is the c linker needed?
1591     my $needs_c = 0;
1592     foreach my $ext (sort keys %extension_seen)
1593     {
1594         next unless $extension_map{$ext};
1596         my $lang = $languages{$extension_map{$ext}};
1598         my $rule_file = $lang->rule_file || 'depend2';
1600         # Get information on $LANG.
1601         my $pfx = $lang->autodep;
1602         my $fpfx = ($pfx eq '') ? 'CC' : $pfx;
1604         my $AMDEP = (($use_dependencies && $lang->autodep ne 'no')
1605                      ? 'AMDEP' : 'FALSE');
1607         my %transform = ('EXT'     => $ext,
1608                          'PFX'     => $pfx,
1609                          'FPFX'    => $fpfx,
1610                          'LIBTOOL' => defined $seen_libtool,
1611                          'AMDEP'   => $AMDEP,
1612                          '-c'      => $lang->compile_flag || '',
1613                          'MORE-THAN-ONE'
1614                                    => (count_files_for_language ($lang->name) > 1));
1616         # Generate the appropriate rules for this extension.
1617         if (($use_dependencies && $lang->autodep ne 'no')
1618             || defined $lang->compile)
1619         {
1620             # Some C compilers don't support -c -o.  Use it only if really
1621             # needed.
1622             my $output_flag = $lang->output_flag || '';
1623             $output_flag = '-o'
1624               if (! $output_flag
1625                   && $lang->flags eq 'CFLAGS'
1626                   && defined $options{'subdir-objects'});
1628             # FIXME: this is a temporary hack to compute a possible
1629             # derived extension.  This is not used by depend2.am.
1630             (my $der_ext = $ext) =~ tr/yl/cc/;
1632             # Another yacc/lex hack.
1633             my $destfile = '$*' . $der_ext;
1635             $output_rules .=
1636               file_contents ($rule_file,
1637                              %transform,
1638                              'GENERIC'   => 1,
1640                              'DERIVED-EXT' => $der_ext,
1642                              # In this situation we know that the
1643                              # object is in this directory, so
1644                              # $(DEPDIR) is the correct location for
1645                              # dependencies.
1646                              'DEPBASE'   => '$(DEPDIR)/$*',
1647                              'BASE'      => '$*',
1648                              'SOURCE'    => '$<',
1649                              'OBJ'       => '$@',
1650                              'OBJOBJ'    => '$@',
1651                              'LTOBJ'     => '$@',
1653                              'COMPILE'   => '$(' . $lang->compiler . ')',
1654                              'LTCOMPILE' => '$(LT' . $lang->compiler . ')',
1655                              '-o'        => $output_flag);
1656         }
1658         # Now include code for each specially handled object with this
1659         # language.
1660         my %seen_files = ();
1661         foreach my $file (@{$lang_specific_files{$lang->name}})
1662         {
1663             my ($derived, $source, $obj, $myext) = split (' ', $file);
1665             # For any specially-generated object, we must respect the
1666             # ansi2knr setting so that we don't inadvertently try to
1667             # use the default rule.
1668             if ($lang->ansi && defined $options{'ansi2knr'})
1669             {
1670                 $myext = '$U' . $myext;
1671             }
1673             # We might see a given object twice, for instance if it is
1674             # used under different conditions.
1675             next if defined $seen_files{$obj};
1676             $seen_files{$obj} = 1;
1678             my $flags = $lang->flags || '';
1679             my $val = "${derived}_${flags}";
1681             prog_error ("found $lang->name in handle_languages, but compiler not defined")
1682                 unless defined $lang->compile;
1684             (my $obj_compile = $lang->compile) =~ s/\(AM_$flags/\($val/;
1685             my $obj_ltcompile = '$(LIBTOOL) --mode=compile ' . $obj_compile;
1687             # We _need_ `-o' for per object rules.
1688             my $output_flag = $lang->output_flag || '-o';
1690             my $depbase = dirname ($obj);
1691             $depbase = ''
1692                 if $depbase eq '.';
1693             $depbase .= '/'
1694                 unless $depbase eq '';
1695             $depbase .= '$(DEPDIR)/' . basename ($obj);
1697             # Generate a transform which will turn suffix targets in
1698             # depend2.am into real targets for the particular objects we
1699             # are building.
1700             $output_rules .=
1701               file_contents ($rule_file,
1702                              (%transform,
1703                               'GENERIC'   => 0,
1705                               'DEPBASE'   => $depbase,
1706                               'BASE'      => $obj,
1707                               'SOURCE'    => $source,
1708                               # Use $myext and not `.o' here, in case
1709                               # we are actually building a new source
1710                               # file -- e.g. via yacc.
1711                               'OBJ'       => "$obj$myext",
1712                               'OBJOBJ'    => "$obj.obj",
1713                               'LTOBJ'     => "$obj.lo",
1715                               'COMPILE'   => $obj_compile,
1716                               'LTCOMPILE' => $obj_ltcompile,
1717                               '-o'        => $output_flag));
1718         }
1720         # The rest of the loop is done once per language.
1721         next if defined $done{$lang};
1722         $done{$lang} = 1;
1724         # Load the language dependent Makefile chunks.
1725         my %lang = map { uc ($_) => 0 } keys %languages;
1726         $lang{uc ($lang->name)} = 1;
1727         $output_rules .= file_contents ('lang-compile', %transform, %lang);
1729         # If the source to a program consists entirely of code from a
1730         # `pure' language, for instance C++ for Fortran 77, then we
1731         # don't need the C compiler code.  However if we run into
1732         # something unusual then we do generate the C code.  There are
1733         # probably corner cases here that do not work properly.
1734         # People linking Java code to Fortran code deserve pain.
1735         $needs_c ||= ! $lang->pure;
1737         define_compiler_variable ($lang)
1738           if ($lang->compile);
1740         define_linker_variable ($lang)
1741           if ($lang->link);
1743         foreach my $var (@{$lang->config_vars})
1744           {
1745             am_error ($lang->Name
1746                       . " source seen but `$var' not defined in"
1747                       . " `$configure_ac'")
1748               if !exists $configure_vars{$var};
1749           }
1751         # The compiler's flag must be a configure variable.
1752         define_configure_variable ($lang->flags)
1753             if defined $lang->flags && $lang->define_flag;
1755         # Call the finisher.
1756         $lang->finish;
1757     }
1759     # If the project is entirely C++ or entirely Fortran 77 (i.e., 1
1760     # suffix rule was learned), don't bother with the C stuff.  But if
1761     # anything else creeps in, then use it.
1762     $needs_c = 1
1763       if $need_link || scalar keys %suffix_rules > 1;
1765     if ($needs_c)
1766       {
1767         if (! defined $done{$languages{'c'}})
1768           {
1769             &define_configure_variable ($languages{'c'}->flags);
1770             &define_compiler_variable ($languages{'c'});
1771           }
1772         define_linker_variable ($languages{'c'});
1773       }
1776 # Check to make sure a source defined in LIBOBJS is not explicitly
1777 # mentioned.  This is a separate function (as opposed to being inlined
1778 # in handle_source_transform) because it isn't always appropriate to
1779 # do this check.
1780 sub check_libobjs_sources
1782     my ($one_file, $unxformed) = @_;
1784     foreach my $prefix ('', 'EXTRA_', 'dist_', 'nodist_',
1785                         'dist_EXTRA_', 'nodist_EXTRA_')
1786     {
1787         my @files;
1788         if (variable_defined ($prefix . $one_file . '_SOURCES'))
1789         {
1790             @files = &variable_value_as_list_recursive (
1791                                 ($prefix . $one_file . '_SOURCES'),
1792                                 'all');
1793         }
1794         elsif ($prefix eq '')
1795         {
1796             @files = ($unxformed . '.c');
1797         }
1798         else
1799         {
1800             next;
1801         }
1803         foreach my $file (@files)
1804         {
1805           macro_error ($prefix . $one_file . '_SOURCES',
1806                        "automatically discovered file `$file' should not be explicitly mentioned")
1807             if defined $libsources{$file};
1808         }
1809     }
1813 # @OBJECTS
1814 # handle_single_transform_list ($VAR, $TOPPARENT, $DERIVED, $OBJ, @FILES)
1815 # -----------------------------------------------------------------------
1816 # Does much of the actual work for handle_source_transform.
1817 # Arguments are:
1818 #   $VAR is the name of the variable that the source filenames come from
1819 #   $TOPPARENT is the name of the _SOURCES variable which is being processed
1820 #   $DERIVED is the name of resulting executable or library
1821 #   $OBJ is the object extension (e.g., `$U.lo')
1822 #   @FILES is the list of source files to transform
1823 # Result is a list of the names of objects
1824 # %linkers_used will be updated with any linkers needed
1825 sub handle_single_transform_list ($$$$@)
1827     my ($var, $topparent, $derived, $obj, @files) = @_;
1828     my @result = ();
1829     my $nonansi_obj = $obj;
1830     $nonansi_obj =~ s/\$U//g;
1832     # Turn sources into objects.  We use a while loop like this
1833     # because we might add to @files in the loop.
1834     while (scalar @files > 0)
1835     {
1836         $_ = shift @files;
1838         # Configure substitutions in _SOURCES variables are errors.
1839         if (/^\@.*\@$/)
1840         {
1841             macro_error ($var,
1842                          "`$var' includes configure substitution `$_', and is referred to from `$topparent': configure substitutions not allowed in _SOURCES variables");
1843             next;
1844         }
1846         # If the source file is in a subdirectory then the `.o' is put
1847         # into the current directory, unless the subdir-objects option
1848         # is in effect.
1850         # Split file name into base and extension.
1851         next if ! /^(?:(.*)\/)?([^\/]*)($KNOWN_EXTENSIONS_PATTERN)$/;
1852         my $full = $_;
1853         my $directory = $1 || '';
1854         my $base = $2;
1855         my $extension = $3;
1857         # We must generate a rule for the object if it requires its own flags.
1858         my $renamed = 0;
1859         my ($linker, $object);
1861         # This records whether we've seen a derived source file (eg,
1862         # yacc output).
1863         my $derived_source = 0;
1865         # This holds the `aggregate context' of the file we are
1866         # currently examining.  If the file is compiled with
1867         # per-object flags, then it will be the name of the object.
1868         # Otherwise it will be `AM'.  This is used by the target hook
1869         # language function.
1870         my $aggregate = 'AM';
1872         $extension = &derive_suffix ($extension, $nonansi_obj);
1873         my $lang;
1874         if ($extension_map{$extension} &&
1875             ($lang = $languages{$extension_map{$extension}}))
1876         {
1877             # Found the language, so see what it says.
1878             &saw_extension ($extension);
1880             # Note: computed subr call.  The language rewrite function
1881             # should return one of the $LANG_* constants.  It could
1882             # also return a list whose first value is such a constant
1883             # and whose second value is a new source extension which
1884             # should be applied.  This means this particular language
1885             # generates another source file which we must then process
1886             # further.
1887             my $subr = 'lang_' . $lang->name . '_rewrite';
1888             my ($r, $source_extension)
1889                 = & $subr ($directory, $base, $extension);
1890             # Skip this entry if we were asked not to process it.
1891             next if $r == $LANG_IGNORE;
1893             # Now extract linker and other info.
1894             $linker = $lang->linker;
1896             my $this_obj_ext;
1897             if (defined $source_extension)
1898             {
1899                 $this_obj_ext = $source_extension;
1900                 $derived_source = 1;
1901             }
1902             elsif ($lang->ansi)
1903             {
1904                 $this_obj_ext = $obj;
1905             }
1906             else
1907             {
1908                 $this_obj_ext = $nonansi_obj;
1909             }
1910             $object = $base . $this_obj_ext;
1912             if (defined $lang->flags
1913                 && variable_defined ($derived . '_' . $lang->flags))
1914             {
1915                 # We have a per-executable flag in effect for this
1916                 # object.  In this case we rewrite the object's
1917                 # name to ensure it is unique.  We also require
1918                 # the `compile' program to deal with compilers
1919                 # where `-c -o' does not work.
1921                 # We choose the name `DERIVED_OBJECT' to ensure
1922                 # (1) uniqueness, and (2) continuity between
1923                 # invocations.  However, this will result in a
1924                 # name that is too long for losing systems, in
1925                 # some situations.  So we provide _SHORTNAME to
1926                 # override.
1928                 my $dname = $derived;
1929                 if (variable_defined ($derived . '_SHORTNAME'))
1930                 {
1931                     # FIXME: should use the same conditional as
1932                     # the _SOURCES variable.  But this is really
1933                     # silly overkill -- nobody should have
1934                     # conditional shortnames.
1935                     $dname = &variable_value ($derived . '_SHORTNAME');
1936                 }
1937                 $object = $dname . '-' . $object;
1939                 require_conf_file ("$am_file.am", FOREIGN, 'compile')
1940                     if $lang->name eq 'c';
1942                 prog_error ("$lang->name flags defined without compiler")
1943                     if ! defined $lang->compile;
1945                 $renamed = 1;
1946             }
1948             # If rewrite said it was ok, put the object into a
1949             # subdir.
1950             if ($r == $LANG_SUBDIR && $directory ne '')
1951             {
1952                 $object = $directory . '/' . $object;
1953             }
1955             # If doing dependency tracking, then we can't print
1956             # the rule.  If we have a subdir object, we need to
1957             # generate an explicit rule.  Actually, in any case
1958             # where the object is not in `.' we need a special
1959             # rule.  The per-object rules in this case are
1960             # generated later, by handle_languages.
1961             if ($renamed || $directory ne '')
1962             {
1963                 my $obj_sans_ext = substr ($object, 0,
1964                                            - length ($this_obj_ext));
1965                 my $val = ("$full $obj_sans_ext "
1966                            # Only use $this_obj_ext in the derived
1967                            # source case because in the other case we
1968                            # *don't* want $(OBJEXT) to appear here.
1969                            . ($derived_source ? $this_obj_ext : '.o'));
1971                 # If we renamed the object then we want to use the
1972                 # per-executable flag name.  But if this is simply a
1973                 # subdir build then we still want to use the AM_ flag
1974                 # name.
1975                 if ($renamed)
1976                 {
1977                     $val = "$derived $val";
1978                     $aggregate = $derived;
1979                 }
1980                 else
1981                 {
1982                     $val = "AM $val";
1983                 }
1985                 # Each item on this list is a string consisting of
1986                 # four space-separated values: the derived flag prefix
1987                 # (eg, for `foo_CFLAGS', it is `foo'), the name of the
1988                 # source file, the base name of the output file, and
1989                 # the extension for the object file.
1990                 push (@{$lang_specific_files{$lang->name}}, $val);
1991             }
1992         }
1993         elsif ($extension eq $nonansi_obj)
1994         {
1995             # This is probably the result of a direct suffix rule.
1996             # In this case we just accept the rewrite.
1997             $object = "$base$extension";
1998             $linker = '';
1999         }
2000         else
2001         {
2002             # No error message here.  Used to have one, but it was
2003             # very unpopular.
2004             # FIXME: we could potentially do more processing here,
2005             # perhaps treating the new extension as though it were a
2006             # new source extension (as above).  This would require
2007             # more restructuring than is appropriate right now.
2008             next;
2009         }
2011         if (defined $object_map{$object})
2012         {
2013             if ($object_map{$object} ne $full)
2014             {
2015                 am_error ("object `$object' created by `$full' and `$object_map{$object}'");
2016             }
2017         }
2019         my $comp_val = (($object =~ /\.lo$/)
2020                         ? $COMPILE_LIBTOOL : $COMPILE_ORDINARY);
2021         (my $comp_obj = $object) =~ s/\.lo$/.\$(OBJEXT)/;
2022         if (defined $object_compilation_map{$comp_obj}
2023             && $object_compilation_map{$comp_obj} != 0
2024             # Only see the error once.
2025             && ($object_compilation_map{$comp_obj}
2026                 != ($COMPILE_LIBTOOL | $COMPILE_ORDINARY))
2027             && $object_compilation_map{$comp_obj} != $comp_val)
2028         {
2029             am_error ("object `$object' created both with libtool and without");
2030         }
2031         $object_compilation_map{$comp_obj} |= $comp_val;
2033         if (defined $lang)
2034         {
2035             # Let the language do some special magic if required.
2036             $lang->target_hook ($aggregate, $object, $full);
2037         }
2039         if ($derived_source)
2040         {
2041             prog_error ("$lang->name has automatic dependency tracking")
2042                 if $lang->autodep ne 'no';
2043             # Make sure this new source file is handled next.  That will
2044             # make it appear to be at the right place in the list.
2045             unshift (@files, $object);
2046             # Distribute derived sources unless the source they are
2047             # derived from is not.
2048             &push_dist_common ($object)
2049                 unless ($topparent =~ /^(:?nobase_)?nodist_/);
2050             next;
2051         }
2053         $linkers_used{$linker} = 1;
2055         push (@result, $object);
2057         if (! defined $object_map{$object})
2058         {
2059             my @dep_list = ();
2060             $object_map{$object} = $full;
2062             # If file is in subdirectory, we need explicit
2063             # dependency.
2064             if ($directory ne '' || $renamed)
2065             {
2066                 push (@dep_list, $full);
2067             }
2069             # If resulting object is in subdir, we need to make
2070             # sure the subdir exists at build time.
2071             if ($object =~ /\//)
2072             {
2073                 # FIXME: check that $DIRECTORY is somewhere in the
2074                 # project
2076                 # For Java, the way we're handling it right now, a
2077                 # `..' component doesn't make sense.
2078                 if ($lang->name eq 'java' && $object =~ /(\/|^)\.\.\//)
2079                 {
2080                     am_error ("`$full' contains `..' component but should not");
2081                 }
2083                 # Make sure object is removed by `make mostlyclean'.
2084                 $compile_clean_files{$object} = MOSTLY_CLEAN;
2086                 push (@dep_list, require_build_directory ($directory));
2088                 # If we're generating dependencies, we also want
2089                 # to make sure that the appropriate subdir of the
2090                 # .deps directory is created.
2091                 push (@dep_list,
2092                       require_build_directory ($directory . '/$(DEPDIR)'))
2093                     if $use_dependencies;
2094             }
2096             &pretty_print_rule ($object . ':', "\t", @dep_list)
2097                 if scalar @dep_list > 0;
2098         }
2100         # Transform .o or $o file into .P file (for automatic
2101         # dependency code).
2102         if ($lang && $lang->autodep ne 'no')
2103         {
2104             my $depfile = $object;
2105             $depfile =~ s/\.([^.]*)$/.P$1/;
2106             $depfile =~ s/\$\(OBJEXT\)$/o/;
2107             $dep_files{dirname ($depfile) . '/$(DEPDIR)/'
2108                            . basename ($depfile)} = 1;
2109         }
2110     }
2112     return @result;
2115 # $BOOL
2116 # define_objects_from_sources ($VAR, $OBJVAR, $NODEFINE, $ONE_FILE,
2117 #                              $OBJ, $PARENT, $TOPPARENT)
2118 # ---------------------------------------------------------------------
2119 # Define an _OBJECTS variable for a _SOURCES variable (or subvariable)
2121 # Arguments are:
2122 #   $VAR is the name of the _SOURCES variable
2123 #   $OBJVAR is the name of the _OBJECTS
2124 #   $NODEFINE is a boolean: if true, $OBJVAR will not be defined (but
2125 #   work done to determine the linker will be).
2126 #   $ONE_FILE is the canonical (transformed) name of object to build
2127 #   $OBJ is the object extension (ie either `.o' or `.lo').
2128 #   $PARENT is the variable in which $VAR is used, or $VAR if not applicable.
2129 #   $TOPPARENT is the _SOURCES variable being processed.
2131 # Result is a boolean, true if a linker is needed to deal with the objects.
2133 # %linkers_used, %vars_scanned, @substfroms and @substtos should be cleared
2134 # before use:
2135 #   %linkers_used variable will be set to contain the linkers desired.
2136 #   %vars_scanned will be used to check for recursive definitions.
2137 #   @substfroms and @substtos will be used to keep a stack of variable
2138 #   substitutions to be applied.
2140 sub define_objects_from_sources ($$$$$$$)
2142     my ($var, $objvar, $nodefine, $one_file, $obj, $parent, $topparent) = @_;
2144     if (defined $vars_scanned{$var})
2145     {
2146         macro_error ($var, "variable `$var' recursively defined");
2147         return "";
2148     }
2149     $vars_scanned{$var} = 1;
2151     my $needlinker = "";
2152     foreach my $cond (variable_conditions ($var))
2153     {
2154         my @result;
2155         foreach my $val (&variable_value_as_list ($var, $cond, $parent))
2156         {
2157             # If $val is a variable (i.e. ${foo} or $(bar), not a filename),
2158             # handle the sub variable recursively.
2159             if ($val =~ /^\$\{([^}]*)\}$/ || $val =~ /^\$\(([^)]*)\)$/)
2160             {
2161                 my $subvar = $1;
2163                 # If the user uses a losing variable name, just ignore it.
2164                 # This isn't ideal, but people have requested it.
2165                 next if ($subvar =~ /\@.*\@/);
2167                 # See if the variable is actually a substitution reference
2168                 my ($from, $to);
2169                 my @temp_list;
2170                 if ($subvar =~ /$SUBST_REF_PATTERN/o)
2171                 {
2172                     $subvar = $1;
2173                     $to = $3;
2174                     $from = quotemeta $2;
2175                 }
2176                 push @substfroms, $from;
2177                 push @substtos, $to;
2179                 my $subobjvar = subobjname ($subvar);
2180                 push (@result, '$('. $subobjvar . ')');
2182                 my $temp = define_objects_from_sources ($subvar, $subobjvar,
2183                                                         $nodefine, $one_file,
2184                                                         $obj, $var, $topparent);
2185                 $needlinker ||= $temp;
2187                 pop @substfroms;
2188                 pop @substtos;
2189             }
2190             else # $var is a filename
2191             {
2192                 my $substnum=$#substfroms;
2193                 while ($substnum >= 0)
2194                 {
2195                     $val =~ s/$substfroms[$substnum]$/$substtos[$substnum]/
2196                         if defined $substfroms[$substnum];
2197                     $substnum -= 1;
2198                 }
2200                 my (@transformed) =
2201                       &handle_single_transform_list ($var, $topparent, $one_file, $obj, $val);
2202                 push (@result, @transformed);
2203                 $needlinker = "true" if @transformed;
2204             }
2205         }
2207         # Define _OBJECTS conditionally.
2208         define_pretty_variable ($objvar, $cond, (@result))
2209                 unless $nodefine;
2210     }
2212     delete $vars_scanned{$var};
2213     return $needlinker;
2217 # $OBJNAME
2218 # subobjname ($VARNAME)
2219 # ---------------------
2220 # Return a name for an object variable.
2222 # Arguments are:
2223 #   $VARNAME is the name of the variable the object variable is being
2224 #   generated from.
2226 # This function also looks at @substfroms and @substtos to determine any
2227 # substitutions to be performed on the object variable.
2229 # The name returned is unique for the combination of $varname and
2230 # substitutions to be performed.
2231 sub subobjname ($)
2233     my ($varname) = @_;
2234     my $key = $varname;
2235     my $substnum=$#substfroms;
2236     while ($substnum >= 0)
2237     {
2238         if (defined $substfroms[$substnum] &&
2239             ($substfroms[$substnum] || $substtos[$substnum]))
2240         {
2241             $key .= ":" . $substfroms[$substnum] . "=" . $substtos[$substnum];
2242         }
2243         $substnum -= 1;
2244     }
2246     my $num = $substnums{$key};
2247     if (! $num)
2248     {
2249         $num = keys(%substnums) + 1;
2250         $substnums{$key} = $num;
2251     }
2253     return "am__objects_$num";
2257 # Handle SOURCE->OBJECT transform for one program or library.
2258 # Arguments are:
2259 #   canonical (transformed) name of object to build
2260 #   actual name of object to build
2261 #   object extension (ie either `.o' or `$o'.
2262 # Return result is name of linker variable that must be used.
2263 # Empty return means just use `LINK'.
2264 sub handle_source_transform
2266     # one_file is canonical name.  unxformed is given name.  obj is
2267     # object extension.
2268     my ($one_file, $unxformed, $obj) = @_;
2270     my ($linker) = '';
2272     if (variable_defined ($one_file . "_OBJECTS"))
2273     {
2274         macro_error ($one_file . '_OBJECTS',
2275                      $one_file . '_OBJECTS', 'should not be defined');
2276         # No point in continuing.
2277         return;
2278     }
2280     my %used_pfx = ();
2281     my $needlinker;
2282     %linkers_used = ();
2283     foreach my $prefix ('', 'EXTRA_', 'dist_', 'nodist_',
2284                         'dist_EXTRA_', 'nodist_EXTRA_')
2285     {
2286         my $var = $prefix . $one_file . "_SOURCES";
2287         next
2288           if !variable_defined ($var);
2290         # We are going to define _OBJECTS variables using the prefix.
2291         # Then we glom them all together.  So we can't use the null
2292         # prefix here as we need it later.
2293         my $xpfx = ($prefix eq '') ? 'am_' : $prefix;
2295         # Keep track of which prefixes we saw.
2296         $used_pfx{$xpfx} = 1
2297           unless $prefix =~ /EXTRA_/;
2299         push @sources, "\$($var)";
2300         push @dist_sources, "\$($var)"
2301           unless $prefix =~ /^nodist_/;
2303         @substfroms = ();
2304         @substtos = ();
2305         %vars_scanned = ();
2306         my $temp = define_objects_from_sources ($var,
2307                                                 $xpfx . $one_file . '_OBJECTS',
2308                                                 $prefix =~ /EXTRA_/,
2309                                                 $one_file, $obj, $var, $var);
2310         $needlinker ||= $temp;
2311     }
2312     if ($needlinker)
2313     {
2314         $linker ||= &resolve_linker (%linkers_used);
2315     }
2317     my @keys = sort keys %used_pfx;
2318     if (scalar @keys == 0)
2319     {
2320         &define_variable ($one_file . "_SOURCES", $unxformed . ".c");
2321         push (@sources, $unxformed . '.c');
2322         push (@dist_sources, $unxformed . '.c');
2324         %linkers_used = ();
2325         my (@result) =
2326           &handle_single_transform_list ($one_file . '_SOURCES',
2327                                          $one_file . '_SOURCES',
2328                                          $one_file, $obj,
2329                                          "$unxformed.c");
2330         $linker ||= &resolve_linker (%linkers_used);
2331         define_pretty_variable ($one_file . "_OBJECTS", '', @result)
2332     }
2333     else
2334     {
2335         grep ($_ = '$(' . $_ . $one_file . '_OBJECTS)', @keys);
2336         define_pretty_variable ($one_file . '_OBJECTS', '', @keys);
2337     }
2339     # If we want to use `LINK' we must make sure it is defined.
2340     if ($linker eq '')
2341     {
2342         $need_link = 1;
2343     }
2345     return $linker;
2349 # handle_lib_objects ($XNAME, $VAR)
2350 # ---------------------------------
2351 # Special-case @ALLOCA@ and @LIBOBJS@ in _LDADD or _LIBADD variables.
2352 # Also, generate _DEPENDENCIES variable if appropriate.
2353 # Arguments are:
2354 #   transformed name of object being built, or empty string if no object
2355 #   name of _LDADD/_LIBADD-type variable to examine
2356 # Returns 1 if LIBOBJS seen, 0 otherwise.
2357 sub handle_lib_objects
2359     my ($xname, $var) = @_;
2361     prog_error ("handle_lib_objects: $var undefined")
2362         if ! variable_defined ($var);
2364     my $ret = 0;
2365     foreach my $cond (variable_conditions_recursive ($var))
2366       {
2367         if (&handle_lib_objects_cond ($xname, $var, $cond))
2368           {
2369             $ret = 1;
2370           }
2371       }
2372     return $ret;
2375 # Subroutine of handle_lib_objects: handle a particular condition.
2376 sub handle_lib_objects_cond
2378     my ($xname, $var, $cond) = @_;
2380     # We recognize certain things that are commonly put in LIBADD or
2381     # LDADD.
2382     my @dep_list = ();
2384     my $seen_libobjs = 0;
2385     my $flagvar = 0;
2387     foreach my $lsearch (&variable_value_as_list_recursive ($var, $cond))
2388     {
2389         # Skip -lfoo and -Ldir; these are explicitly allowed.
2390         next if $lsearch =~ /^-[lL]/;
2391         if (! $flagvar && $lsearch =~ /^-/)
2392         {
2393             if ($var =~ /^(.*)LDADD$/)
2394             {
2395                 # Skip -dlopen and -dlpreopen; these are explicitly allowed.
2396                 next if $lsearch =~ /^-dl(pre)?open$/;
2397                 my $prefix = $1 || 'AM_';
2398                 macro_error ($var,
2399                              "linker flags such as `$lsearch' belong in `${prefix}LDFLAGS");
2400             }
2401             else
2402             {
2403                 $var =~ /^(.*)LIBADD$/;
2404                 # Only get this error once.
2405                 $flagvar = 1;
2406                 macro_error ($var,
2407                              "linker flags such as `$lsearch' belong in `${1}LDFLAGS");
2408             }
2409         }
2411         # Assume we have a file of some sort, and push it onto the
2412         # dependency list.  Autoconf substitutions are not pushed;
2413         # rarely is a new dependency substituted into (eg) foo_LDADD
2414         # -- but "bad things (eg -lX11) are routinely substituted.
2415         # Note that LIBOBJS and ALLOCA are exceptions to this rule,
2416         # and handled specially below.
2417         push (@dep_list, $lsearch)
2418             unless $lsearch =~ /^\@.*\@$/;
2420         # Automatically handle @LIBOBJS@ and @ALLOCA@.  Basically this
2421         # means adding entries to dep_files.
2422         if ($lsearch =~ /^\@(LT)?LIBOBJS\@$/)
2423         {
2424             my $lt = $1 ? $1 : '';
2425             my $myobjext = ($1 ? 'l' : '') . 'o';
2427             push (@dep_list, $lsearch);
2428             $seen_libobjs = 1;
2429             if (! keys %libsources
2430                 && ! variable_defined ($lt . 'LIBOBJS'))
2431             {
2432                 macro_error ($var,
2433                              "\@$lt" . "LIBOBJS\@ seen but never set in `$configure_ac'");
2434             }
2436             foreach my $iter (keys %libsources)
2437             {
2438                 if ($iter =~ /\.[cly]$/)
2439                 {
2440                     &saw_extension ($&);
2441                     &saw_extension ('.c');
2442                 }
2444                 if ($iter =~ /\.h$/)
2445                 {
2446                     require_file_with_macro ($var, FOREIGN, $iter);
2447                 }
2448                 elsif ($iter ne 'alloca.c')
2449                 {
2450                     my $rewrite = $iter;
2451                     $rewrite =~ s/\.c$/.P$myobjext/;
2452                     $dep_files{'$(DEPDIR)/' . $rewrite} = 1;
2453                     $rewrite = "^" . quotemeta ($iter) . "\$";
2454                     # Only require the file if it is not a built source.
2455                     if (! variable_defined ('BUILT_SOURCES')
2456                         || ! grep (/$rewrite/,
2457                                    &variable_value_as_list_recursive (
2458                                         'BUILT_SOURCES', 'all')))
2459                     {
2460                         require_file_with_macro ($var, FOREIGN, $iter);
2461                     }
2462                 }
2463             }
2464         }
2465         elsif ($lsearch =~ /^\@(LT)?ALLOCA\@$/)
2466         {
2467             my $lt = $1 ? $1 : '';
2468             my $myobjext = ($1 ? 'l' : '') . 'o';
2470             push (@dep_list, $lsearch);
2471             macro_error ($var,
2472                          "\@$lt" . "ALLOCA\@ seen but `AC_FUNC_ALLOCA' not in `$configure_ac'")
2473                 if ! defined $libsources{'alloca.c'};
2474             $dep_files{'$(DEPDIR)/alloca.P' . $myobjext} = 1;
2475             require_file_with_macro ($var, FOREIGN, 'alloca.c');
2476             &saw_extension ('c');
2477         }
2478     }
2480     if ($xname ne '')
2481     {
2482         if (conditional_ambiguous_p ($xname . '_DEPENDENCIES', $cond) ne '')
2483         {
2484             # Note that we've examined this.
2485             &examine_variable ($xname . '_DEPENDENCIES');
2486         }
2487         else
2488         {
2489             define_pretty_variable ($xname . '_DEPENDENCIES', $cond,
2490                                     @dep_list);
2491         }
2492     }
2494     return $seen_libobjs;
2497 # Canonicalize the input parameter
2498 sub canonicalize
2500     my ($string) = @_;
2501     $string =~ tr/A-Za-z0-9_\@/_/c;
2502     return $string;
2505 # Canonicalize a name, and check to make sure the non-canonical name
2506 # is never used.  Returns canonical name.  Arguments are name and a
2507 # list of suffixes to check for.
2508 sub check_canonical_spelling
2510     my ($name, @suffixes) = @_;
2512     my $xname = &canonicalize ($name);
2513     if ($xname ne $name)
2514     {
2515         foreach my $xt (@suffixes)
2516         {
2517             macro_error ("$name$xt",
2518                          "invalid variable `$name$xt'; should be `$xname$xt'")
2519                 if variable_defined ("$name$xt");
2520         }
2521     }
2523     return $xname;
2527 # handle_compile ()
2528 # -----------------
2529 # Set up the compile suite.
2530 sub handle_compile ()
2532     return
2533       unless $get_object_extension_was_run;
2535     # Boilerplate.
2536     my $default_includes = '';
2537     if (! defined $options{'nostdinc'})
2538       {
2539         $default_includes = ' -I. -I$(srcdir)';
2541         if (variable_defined ('CONFIG_HEADER'))
2542           {
2543             foreach my $hdr (split (' ', &variable_value ('CONFIG_HEADER')))
2544               {
2545                 $default_includes .= ' -I' . dirname ($hdr);
2546               }
2547           }
2548       }
2550     my (@mostly_rms, @dist_rms);
2551     foreach my $item (sort keys %compile_clean_files)
2552     {
2553         if ($compile_clean_files{$item} == MOSTLY_CLEAN)
2554         {
2555             push (@mostly_rms, "\t-rm -f $item");
2556         }
2557         elsif ($compile_clean_files{$item} == DIST_CLEAN)
2558         {
2559             push (@dist_rms, "\t-rm -f $item");
2560         }
2561         else
2562         {
2563             prog_error ("invalid entry in \%compile_clean_files");
2564         }
2565     }
2567     my ($coms, $vars, $rules) =
2568       &file_contents_internal (1, "$libdir/am/compile.am",
2569                                ('DEFAULT_INCLUDES' => $default_includes,
2570                                 'MOSTLYRMS' => join ("\n", @mostly_rms),
2571                                 'DISTRMS' => join ("\n", @dist_rms)));
2572     $output_vars .= $vars;
2573     $output_rules .= "$coms$rules";
2575     # Check for automatic de-ANSI-fication.
2576     if (defined $options{'ansi2knr'})
2577       {
2578         if (! $am_c_prototypes)
2579           {
2580             macro_error ('AUTOMAKE_OPTIONS',
2581                          "option `ansi2knr' in use but `AM_C_PROTOTYPES' not in `$configure_ac'");
2582             &keyed_aclocal_warning ('AM_C_PROTOTYPES');
2583             # Only give this error once.
2584             $am_c_prototypes = 1;
2585           }
2587         # topdir is where ansi2knr should be.
2588         if ($options{'ansi2knr'} eq 'ansi2knr')
2589           {
2590             # Only require ansi2knr files if they should appear in
2591             # this directory.
2592             require_file_with_macro ('AUTOMAKE_OPTIONS', FOREIGN,
2593                                      'ansi2knr.c', 'ansi2knr.1');
2595             # ansi2knr needs to be built before subdirs, so unshift it.
2596             unshift (@all, '$(ANSI2KNR)');
2597           }
2599         my $ansi2knr_dir = '';
2600         $ansi2knr_dir = dirname ($options{'ansi2knr'})
2601           if $options{'ansi2knr'} ne 'ansi2knr';
2603         $output_rules .= &file_contents ('ansi2knr',
2604                                          ('ANSI2KNR-DIR' => $ansi2knr_dir));
2606     }
2609 # handle_libtool ()
2610 # -----------------
2611 # Handle libtool rules.
2612 sub handle_libtool
2614     return unless $seen_libtool;
2616     # Libtool requires some files, but only at top level.
2617     require_conf_file ($seen_libtool, FOREIGN, @libtool_files)
2618         if $relative_dir eq '.';
2620     # Output the libtool compilation rules.
2621     $output_rules .= &file_contents ('libtool');
2624 # handle_programs ()
2625 # ------------------
2626 # Handle C programs.
2627 sub handle_programs
2629     my @proglist = &am_install_var ('progs', 'PROGRAMS',
2630                                     'bin', 'sbin', 'libexec', 'pkglib',
2631                                     'noinst', 'check');
2632     return if ! @proglist;
2634     my $seen_libobjs = 0;
2635     foreach my $one_file (@proglist)
2636     {
2637         my $obj = &get_object_extension ($one_file);
2639         # Canonicalize names and check for misspellings.
2640         my $xname = &check_canonical_spelling ($one_file, '_LDADD', '_LDFLAGS',
2641                                                '_SOURCES', '_OBJECTS',
2642                                                '_DEPENDENCIES');
2644         my $linker = &handle_source_transform ($xname, $one_file, $obj);
2646         my $xt = '';
2647         if (variable_defined ($xname . "_LDADD"))
2648         {
2649             if (&handle_lib_objects ($xname, $xname . '_LDADD'))
2650             {
2651                 $seen_libobjs = 1;
2652             }
2653             $xt = '_LDADD';
2654         }
2655         else
2656         {
2657             # User didn't define prog_LDADD override.  So do it.
2658             &define_variable ($xname . '_LDADD', '$(LDADD)');
2660             # This does a bit too much work.  But we need it to
2661             # generate _DEPENDENCIES when appropriate.
2662             if (variable_defined ('LDADD'))
2663             {
2664                 if (&handle_lib_objects ($xname, 'LDADD'))
2665                 {
2666                     $seen_libobjs = 1;
2667                 }
2668             }
2669             elsif (! variable_defined ($xname . '_DEPENDENCIES'))
2670             {
2671                 &define_variable ($xname . '_DEPENDENCIES', '');
2672             }
2673             $xt = '_SOURCES'
2674         }
2676         if (variable_defined ($xname . '_LIBADD'))
2677         {
2678             macro_error ($xname . '_LIBADD',
2679                          "use `" . $xname . "_LDADD', not `"
2680                          . $xname . "_LIBADD'");
2681         }
2683         if (! variable_defined ($xname . '_LDFLAGS'))
2684         {
2685             # Define the prog_LDFLAGS variable.
2686             &define_variable ($xname . '_LDFLAGS', '');
2687         }
2689         # Determine program to use for link.
2690         my $xlink;
2691         if (variable_defined ($xname . '_LINK'))
2692         {
2693             $xlink = $xname . '_LINK';
2694         }
2695         else
2696         {
2697             $xlink = $linker ? $linker : 'LINK';
2698         }
2700         # If the resulting program lies into a subdirectory,
2701         # make sure this directory will exist.
2702         my $dirstamp = require_build_directory_maybe ($one_file);
2704         # Don't add $(EXEEXT) if user already did.
2705         my $extension = ($one_file !~ /\$\(EXEEXT\)$/
2706                          ? "\$(EXEEXT)"
2707                          : '');
2709         $output_rules .= &file_contents ('program',
2710                                          ('PROGRAM'  => $one_file,
2711                                           'XPROGRAM' => $xname,
2712                                           'XLINK'    => $xlink,
2713                                           'DIRSTAMP' => $dirstamp,
2714                                           'EXEEXT'   => $extension));
2715     }
2717     if (variable_defined ('LDADD') && &handle_lib_objects ('', 'LDADD'))
2718     {
2719         $seen_libobjs = 1;
2720     }
2722     if ($seen_libobjs)
2723     {
2724         foreach my $one_file (@proglist)
2725         {
2726             my $xname = &canonicalize ($one_file);
2728             if (variable_defined ($xname . '_LDADD'))
2729             {
2730                 &check_libobjs_sources ($xname, $xname . '_LDADD');
2731             }
2732             elsif (variable_defined ('LDADD'))
2733             {
2734                 &check_libobjs_sources ($xname, 'LDADD');
2735             }
2736         }
2737     }
2741 # handle_libraries ()
2742 # -------------------
2743 # Handle libraries.
2744 sub handle_libraries
2746     my @liblist = &am_install_var ('libs', 'LIBRARIES',
2747                                    'lib', 'pkglib', 'noinst', 'check');
2748     return if ! @liblist;
2750     my @prefix = am_primary_prefixes ('LIBRARIES', 0, 'lib', 'pkglib',
2751                                       'noinst', 'check');
2752     if (! defined $configure_vars{'RANLIB'}
2753         && @prefix)
2754       {
2755         macro_error ($prefix[0] . '_LIBRARIES',
2756                      "library used but `RANLIB' not defined in `$configure_ac'");
2757         # Only get this error once.  If this is ever printed, we have
2758         # a bug.
2759         $configure_vars{'RANLIB'} = 'BUG';
2760       }
2762     my $seen_libobjs = 0;
2763     foreach my $onelib (@liblist)
2764     {
2765         # Check that the library fits the standard naming convention.
2766         if (basename ($onelib) !~ /^lib.*\.a/)
2767         {
2768             # FIXME should put line number here.  That means mapping
2769             # from library name back to variable name.
2770             &am_error ("`$onelib' is not a standard library name");
2771         }
2773         my $obj = &get_object_extension ($onelib);
2775         # Canonicalize names and check for misspellings.
2776         my $xlib = &check_canonical_spelling ($onelib, '_LIBADD', '_SOURCES',
2777                                               '_OBJECTS', '_DEPENDENCIES',
2778                                               '_AR');
2780         if (! variable_defined ($xlib . '_AR'))
2781         {
2782             &define_variable ($xlib . '_AR', '$(AR) cru');
2783         }
2785         if (variable_defined ($xlib . '_LIBADD'))
2786         {
2787             if (&handle_lib_objects ($xlib, $xlib . '_LIBADD'))
2788             {
2789                 $seen_libobjs = 1;
2790             }
2791         }
2792         else
2793         {
2794             # Generate support for conditional object inclusion in
2795             # libraries.
2796             &define_variable ($xlib . "_LIBADD", '');
2797         }
2799         if (variable_defined ($xlib . '_LDADD'))
2800         {
2801             macro_error ($xlib . '_LDADD',
2802                          "use `" . $xlib . "_LIBADD', not `"
2803                          . $xlib . "_LDADD'");
2804         }
2806         # Make sure we at look at this.
2807         &examine_variable ($xlib . '_DEPENDENCIES');
2809         &handle_source_transform ($xlib, $onelib, $obj);
2811         # If the resulting library lies into a subdirectory,
2812         # make sure this directory will exist.
2813         my $dirstamp = require_build_directory_maybe ($onelib);
2815         $output_rules .= &file_contents ('library',
2816                                          ('LIBRARY'  => $onelib,
2817                                           'XLIBRARY' => $xlib,
2818                                           'DIRSTAMP' => $dirstamp));
2819     }
2821     if ($seen_libobjs)
2822     {
2823         foreach my $onelib (@liblist)
2824         {
2825             my $xlib = &canonicalize ($onelib);
2826             if (variable_defined ($xlib . '_LIBADD'))
2827             {
2828                 &check_libobjs_sources ($xlib, $xlib . '_LIBADD');
2829             }
2830         }
2831     }
2835 # handle_ltlibraries ()
2836 # ---------------------
2837 # Handle shared libraries.
2838 sub handle_ltlibraries
2840     my @liblist = &am_install_var ('ltlib', 'LTLIBRARIES',
2841                                    'noinst', 'lib', 'pkglib', 'check');
2842     return if ! @liblist;
2844     my %instdirs;
2845     my @prefix = am_primary_prefixes ('LTLIBRARIES', 0, 'lib', 'pkglib',
2846                                       'noinst', 'check');
2848     foreach my $key (@prefix)
2849       {
2850         if (!$seen_libtool)
2851           {
2852             macro_error ($key . '_LTLIBRARIES',
2853                          "library used but `LIBTOOL' not defined in `$configure_ac'");
2854             # Only get this error once.  If this is ever printed,
2855             # we have a bug.
2856             $configure_vars{'LIBTOOL'} = 'BUG';
2857             $seen_libtool = $var_location{$key . '_LTLIBRARIES'};
2858           }
2860         # Get the installation directory of each library.
2861         for (variable_value_as_list_recursive ($key . '_LTLIBRARIES', 'all'))
2862           {
2863             if ($instdirs{$_})
2864               {
2865                 am_error ("`$_' is already going to be installed in `$instdirs{$_}'");
2866               }
2867             else
2868               {
2869                 $instdirs{$_} = $key;
2870               }
2871           }
2872       }
2874     my $seen_libobjs = 0;
2875     foreach my $onelib (@liblist)
2876     {
2877         my $obj = &get_object_extension ($onelib);
2879         # Canonicalize names and check for misspellings.
2880         my $xlib = &check_canonical_spelling ($onelib, '_LIBADD', '_LDFLAGS',
2881                                               '_SOURCES', '_OBJECTS',
2882                                               '_DEPENDENCIES');
2884         if (! variable_defined ($xlib . '_LDFLAGS'))
2885         {
2886             # Define the lib_LDFLAGS variable.
2887             &define_variable ($xlib . '_LDFLAGS', '');
2888         }
2890         # Check that the library fits the standard naming convention.
2891         my $libname_rx = "^lib.*\.la";
2892         if ((variable_defined ($xlib . '_LDFLAGS')
2893              && grep (/-module/, &variable_value_as_list_recursive (
2894                                         $xlib . '_LDFLAGS', 'all')))
2895             || (variable_defined ('LDFLAGS')
2896                 && grep (/-module/, &variable_value_as_list_recursive (
2897                                         'LDFLAGS', 'all'))))
2898         {
2899                 # Relax name checking for libtool modules.
2900                 $libname_rx = "\.la";
2901         }
2902         if (basename ($onelib) !~ /$libname_rx$/)
2903         {
2904             # FIXME this should only be a warning for foreign packages
2905             # FIXME should put line number here.  That means mapping
2906             # from library name back to variable name.
2907             &am_error ("`$onelib' is not a standard libtool library name");
2908         }
2910         if (variable_defined ($xlib . '_LIBADD'))
2911         {
2912             if (&handle_lib_objects ($xlib, $xlib . '_LIBADD'))
2913             {
2914                 $seen_libobjs = 1;
2915             }
2916         }
2917         else
2918         {
2919             # Generate support for conditional object inclusion in
2920             # libraries.
2921             &define_variable ($xlib . "_LIBADD", '');
2922         }
2924         if (variable_defined ($xlib . '_LDADD'))
2925         {
2926             macro_error ($xlib . '_LDADD',
2927                          "use `" . $xlib . "_LIBADD', not `"
2928                          . $xlib . "_LDADD'");
2929         }
2931         # Make sure we at look at this.
2932         &examine_variable ($xlib . '_DEPENDENCIES');
2934         my $linker = &handle_source_transform ($xlib, $onelib, $obj);
2936         # Determine program to use for link.
2937         my $xlink;
2938         if (variable_defined ($xlib . '_LINK'))
2939         {
2940             $xlink = $xlib . '_LINK';
2941         }
2942         else
2943         {
2944             $xlink = $linker ? $linker : 'LINK';
2945         }
2947         my $rpath;
2948         if ($instdirs{$onelib} eq 'EXTRA'
2949             || $instdirs{$onelib} eq 'noinst'
2950             || $instdirs{$onelib} eq 'check')
2951         {
2952             # It's an EXTRA_ library, so we can't specify -rpath,
2953             # because we don't know where the library will end up.
2954             # The user probably knows, but generally speaking automake
2955             # doesn't -- and in fact configure could decide
2956             # dynamically between two different locations.
2957             $rpath = '';
2958         }
2959         else
2960         {
2961             $rpath = ('-rpath $(' . $instdirs{$onelib} . 'dir)');
2962         }
2964         # If the resulting library lies into a subdirectory,
2965         # make sure this directory will exist.
2966         my $dirstamp = require_build_directory_maybe ($onelib);
2968         $output_rules .= &file_contents ('ltlibrary',
2969                                          ('LTLIBRARY'  => $onelib,
2970                                           'XLTLIBRARY' => $xlib,
2971                                           'RPATH'      => $rpath,
2972                                           'XLINK'      => $xlink,
2973                                           'DIRSTAMP'   => $dirstamp));
2974     }
2976     if ($seen_libobjs)
2977     {
2978         foreach my $onelib (@liblist)
2979         {
2980             my $xlib = &canonicalize ($onelib);
2981             if (variable_defined ($xlib . '_LIBADD'))
2982             {
2983                 &check_libobjs_sources ($xlib, $xlib . '_LIBADD');
2984             }
2985         }
2986     }
2989 # See if any _SOURCES variable were misspelled.  Also, make sure that
2990 # EXTRA_ variables don't contain configure substitutions.
2991 sub check_typos ()
2993     foreach my $varname (keys %var_value)
2994     {
2995         foreach my $primary ('_SOURCES', '_LIBADD', '_LDADD', '_LDFLAGS',
2996                              '_DEPENDENCIES')
2997         {
2998           macro_error ($varname,
2999                        "invalid unused variable name: `$varname'")
3000             if $varname =~ /$primary$/ && ! $content_seen{$varname};
3001         }
3002     }
3006 # Handle scripts.
3007 sub handle_scripts
3009     # NOTE we no longer automatically clean SCRIPTS, because it is
3010     # useful to sometimes distribute scripts verbatim.  This happens
3011     # eg in Automake itself.
3012     &am_install_var ('-candist', 'scripts', 'SCRIPTS',
3013                      'bin', 'sbin', 'libexec', 'pkgdata',
3014                      'noinst', 'check');
3018 # ($OUTFILE, $VFILE, @CLEAN_FILES)
3019 # &scan_texinfo_file ($FILENAME)
3020 # ------------------------------
3021 # $OUTFILE is the name of the info file produced by $FILENAME.
3022 # $VFILE is the name of the version.texi file used (empty if none).
3023 # @CLEAN_FILES is the list of by products (indexes etc.)
3024 sub scan_texinfo_file
3026     my ($filename) = @_;
3028     # These are always created, no matter whether indexes are used or not.
3029     my @clean_suffixes = qw(aux dvi log ps toc
3030                             cp fn ky vr tp pg); # grep new.*index texinfo.tex
3032     # There are predefined indexes which don't follow the regular rules.
3033     my %predefined_index = qw(c cps
3034                               f fns
3035                               k kys
3036                               v vrs
3037                               t tps
3038                               p pgs);
3040     # There are commands which include a hidden index command.
3041     my %hidden_index = (tp => 'tps');
3042     $hidden_index{$_} = 'fns' foreach qw(fn un typefn typefun max spec
3043                                          op typeop method typemethod);
3044     $hidden_index{$_} = 'vrs' foreach qw(vr var typevr typevar opt cv
3045                                          ivar typeivar);
3047     # Indexes stored into another one.  In this case, the *.??s file
3048     # is not created.
3049     my @syncodeindexes = ();
3051     my $texi = new Automake::XFile "< $filename";
3052     verbose "reading $filename";
3054     my ($outfile, $vfile);
3055     while ($_ = $texi->getline)
3056     {
3057       if (/^\@setfilename +(\S+)/)
3058       {
3059         $outfile = $1;
3060         if ($outfile =~ /\.(.+)$/ && $1 ne 'info')
3061           {
3062             file_error ("$filename:$.",
3063                         "output `$outfile' has unrecognized extension");
3064             return;
3065           }
3066       }
3067       # A "version.texi" file is actually any file whose name
3068       # matches "vers*.texi".
3069       elsif (/^\@include\s+(vers[^.]*\.texi)\s*$/)
3070       {
3071         $vfile = $1;
3072       }
3074       # Try to find what are the indexes which are used.
3076       # Creating a new category of index.
3077       elsif (/^\@def(code)?index (\w+)/)
3078       {
3079         push @clean_suffixes, $2;
3080       }
3082       # Storing in a predefined index.
3083       elsif (/^\@([cfkvtp])index /)
3084       {
3085         push @clean_suffixes, $predefined_index{$1};
3086       }
3087       elsif (/^\@def(\w+) /)
3088       {
3089         push @clean_suffixes, $hidden_index{$1}
3090           if defined $hidden_index{$1};
3091       }
3093       # Merging an index into an another.
3094       elsif (/^\@syn(code)?index (\w+) (\w+)/)
3095       {
3096         push @syncodeindexes, "$2s";
3097         push @clean_suffixes, "$3s";
3098       }
3100     }
3102     if ($outfile eq '')
3103       {
3104         &am_error ("`$filename' missing \@setfilename");
3105         return;
3106       }
3108     my $infobase = basename ($filename);
3109     $infobase =~ s/\.te?xi(nfo)?$//;
3110     my %clean_files = map { +"$infobase.$_" => 1 } @clean_suffixes;
3111     grep { delete $clean_files{"$infobase.$_"} } @syncodeindexes;
3112     return ($outfile, $vfile, (sort keys %clean_files));
3116 # ($DO-SOMETHING, $TEXICLEANS)
3117 # handle_texinfo_helper ()
3118 # ------------------------
3119 # Handle all Texinfo source; helper for handle_texinfo
3120 sub handle_texinfo_helper
3122     macro_error ('TEXINFOS',
3123                  "`TEXINFOS' is an anachronism; use `info_TEXINFOS'")
3124         if variable_defined ('TEXINFOS');
3125     return (0, '') if (! variable_defined ('info_TEXINFOS')
3126                        && ! variable_defined ('html_TEXINFOS'));
3128     if (variable_defined ('html_TEXINFOS'))
3129     {
3130         macro_error ('html_TEXINFOS',
3131                      "HTML generation not yet supported");
3132         return (0, '');
3133     }
3135     my @texis = &variable_value_as_list_recursive ('info_TEXINFOS', 'all');
3137     my (@info_deps_list, @dvis_list, @texi_deps);
3138     my %versions;
3139     my $done = 0;
3140     my @texi_cleans;
3141     my $canonical;
3143     my %texi_suffixes;
3144     foreach my $info_cursor (@texis)
3145     {
3146         my $infobase = $info_cursor;
3147         $infobase =~ s/\.(txi|texinfo|texi)$//;
3149         if ($infobase eq $info_cursor)
3150         {
3151             # FIXME: report line number.
3152             &am_error ("texinfo file `$info_cursor' has unrecognized extension");
3153             next;
3154         }
3155         $texi_suffixes{$1} = 1;
3157         # If 'version.texi' is referenced by input file, then include
3158         # automatic versioning capability.
3159         my ($out_file, $vtexi, @clean_files) =
3160           &scan_texinfo_file ("$relative_dir/$info_cursor")
3161             or next;
3162         push (@texi_cleans, @clean_files);
3164         if ($vtexi)
3165         {
3166             &am_error ("`$vtexi', included in `$info_cursor', also included in `$versions{$vtexi}'")
3167                 if (defined $versions{$vtexi});
3168             $versions{$vtexi} = $info_cursor;
3170             # We number the stamp-vti files.  This is doable since the
3171             # actual names don't matter much.  We only number starting
3172             # with the second one, so that the common case looks nice.
3173             my $vti = ($done ? $done : 'vti');
3174             ++$done;
3176             # This is ugly, but it is our historical practice.
3177             if ($config_aux_dir_set_in_configure_in)
3178             {
3179                 require_conf_file_with_macro ('info_TEXINFOS', FOREIGN,
3180                                               'mdate-sh');
3181             }
3182             else
3183             {
3184                 require_file_with_macro ('info_TEXINFOS', FOREIGN,
3185                                          'mdate-sh');
3186             }
3188             my $conf_dir;
3189             if ($config_aux_dir_set_in_configure_in)
3190             {
3191                 $conf_dir = $config_aux_dir;
3192                 $conf_dir .= '/' unless $conf_dir =~ /\/$/;
3193             }
3194             else
3195             {
3196                 $conf_dir = '$(srcdir)/';
3197             }
3198             $output_rules .= &file_contents ('texi-vers',
3199                                              ('TEXI'  => $info_cursor,
3200                                               'VTI'   => $vti,
3201                                               'VTEXI' => $vtexi,
3202                                               'MDDIR' => $conf_dir));
3203         }
3205         # If user specified file_TEXINFOS, then use that as explicit
3206         # dependency list.
3207         @texi_deps = ();
3208         push (@texi_deps, $info_cursor);
3209         # Prefix with $(srcdir) because some version of make won't
3210         # work if the target has it and the dependency doesn't.
3211         push (@texi_deps, '$(srcdir)/' . $vtexi) if $vtexi;
3213         my $canonical = &canonicalize ($infobase);
3214         if (variable_defined ($canonical . "_TEXINFOS"))
3215         {
3216             push (@texi_deps, '$(' . $canonical . '_TEXINFOS)');
3217             &push_dist_common ('$(' . $canonical . '_TEXINFOS)');
3218         }
3220         $output_rules .= ("\n" . $out_file . ": "
3221                           . "@texi_deps"
3222                           . "\n" . $infobase . ".dvi: "
3223                           . "@texi_deps"
3224                           . "\n");
3226         push (@info_deps_list, $out_file);
3227         push (@dvis_list, $infobase . '.dvi');
3228     }
3230     # Handle location of texinfo.tex.
3231     my $need_texi_file = 0;
3232     my $texinfodir;
3233     if ($cygnus_mode)
3234     {
3235         $texinfodir = '$(top_srcdir)/../texinfo';
3236         &define_variable ('TEXINFO_TEX', "$texinfodir/texinfo.tex");
3237     }
3238     elsif ($config_aux_dir_set_in_configure_in)
3239     {
3240         $texinfodir = $config_aux_dir;
3241         &define_variable ('TEXINFO_TEX', "$texinfodir/texinfo.tex");
3242         $need_texi_file = 2; # so that we require_conf_file later
3243     }
3244     elsif (variable_defined ('TEXINFO_TEX'))
3245     {
3246         # The user defined TEXINFO_TEX so assume he knows what he is
3247         # doing.
3248         $texinfodir = ('$(srcdir)/'
3249                        . dirname (&variable_value ('TEXINFO_TEX')));
3250     }
3251     else
3252     {
3253         $texinfodir = '$(srcdir)';
3254         $need_texi_file = 1;
3255     }
3257     foreach my $txsfx (sort keys %texi_suffixes)
3258     {
3259         $output_rules .= &file_contents ('texibuild',
3260                                          ('TEXINFODIR' => $texinfodir,
3261                                           'SUFFIX'     => $txsfx));
3262     }
3264     # The return value.
3265     my $texiclean = &pretty_print_internal ("", "\t  ", @texi_cleans);
3267     push (@dist_targets, 'dist-info');
3269     if (! defined $options{'no-installinfo'})
3270     {
3271         # Make sure documentation is made and installed first.  Use
3272         # $(INFO_DEPS), not 'info', because otherwise recursive makes
3273         # get run twice during "make all".
3274         unshift (@all, '$(INFO_DEPS)');
3275     }
3277     &define_variable ("INFO_DEPS", "@info_deps_list");
3278     &define_variable ("DVIS", "@dvis_list");
3279     # This next isn't strictly needed now -- the places that look here
3280     # could easily be changed to look in info_TEXINFOS.  But this is
3281     # probably better, in case noinst_TEXINFOS is ever supported.
3282     &define_variable ("TEXINFOS", &variable_value ('info_TEXINFOS'));
3284     # Do some error checking.  Note that this file is not required
3285     # when in Cygnus mode; instead we defined TEXINFO_TEX explicitly
3286     # up above.
3287     if ($need_texi_file && ! defined $options{'no-texinfo.tex'})
3288     {
3289         if ($need_texi_file > 1)
3290         {
3291             require_conf_file_with_macro ('info_TEXINFOS', FOREIGN,
3292                                           'texinfo.tex');
3293         }
3294         else
3295         {
3296             require_file_with_macro ('info_TEXINFOS', FOREIGN, 'texinfo.tex');
3297         }
3298     }
3300     return (1, $texiclean);
3303 # handle_texinfo ()
3304 # -----------------
3305 # Handle all Texinfo source.
3306 sub handle_texinfo
3308     my ($do_something, $texiclean) = handle_texinfo_helper ();
3309     $output_rules .=  &file_contents ('texinfos',
3310                                       ('TEXICLEAN' => $texiclean,
3311                                        'LOCAL-TEXIS' => $do_something));
3314 # Handle any man pages.
3315 sub handle_man_pages
3317     macro_error ('MANS', "`MANS' is an anachronism; use `man_MANS'")
3318         if variable_defined ('MANS');
3320     # Find all the sections in use.  We do this by first looking for
3321     # "standard" sections, and then looking for any additional
3322     # sections used in man_MANS.
3323     my (%sections, %vlist);
3324     # We handle nodist_ for uniformity.  man pages aren't distributed
3325     # by default so it isn't actually very important.
3326     foreach my $pfx ('', 'dist_', 'nodist_')
3327     {
3328         # Add more sections as needed.
3329         foreach my $section ('0'..'9', 'n', 'l')
3330         {
3331             if (variable_defined ($pfx . 'man' . $section . '_MANS'))
3332             {
3333                 $sections{$section} = 1;
3334                 $vlist{'$(' . $pfx . 'man' . $section . '_MANS)'} = 1;
3336                 &push_dist_common ('$(' . $pfx . 'man' . $section . '_MANS)')
3337                     if $pfx eq 'dist_';
3338             }
3339         }
3341         if (variable_defined ($pfx . 'man_MANS'))
3342         {
3343             $vlist{'$(' . $pfx . 'man_MANS)'} = 1;
3344             foreach (&variable_value_as_list_recursive ($pfx . 'man_MANS', 'all'))
3345             {
3346                 # A page like `foo.1c' goes into man1dir.
3347                 if (/\.([0-9a-z])([a-z]*)$/)
3348                 {
3349                     $sections{$1} = 1;
3350                 }
3351             }
3353             &push_dist_common ('$(' . $pfx . 'man_MANS)')
3354                 if $pfx eq 'dist_';
3355         }
3356     }
3358     return unless %sections;
3360     # Now for each section, generate an install and unintall rule.
3361     # Sort sections so output is deterministic.
3362     foreach my $section (sort keys %sections)
3363     {
3364         $output_rules .= &file_contents ('mans', ('SECTION' => $section));
3365     }
3367     my @mans = sort keys %vlist;
3368     $output_vars .= file_contents ('mans-vars',
3369                                    ('MANS' => "@mans"));
3371     if (! defined $options{'no-installman'})
3372     {
3373         push (@all, '$(MANS)');
3374     }
3377 # Handle DATA variables.
3378 sub handle_data
3380     &am_install_var ('-noextra', '-candist', 'data', 'DATA',
3381                      'data', 'sysconf', 'sharedstate', 'localstate',
3382                      'pkgdata', 'noinst', 'check');
3385 # Handle TAGS.
3386 sub handle_tags
3388     my @tag_deps = ();
3389     if (variable_defined ('SUBDIRS'))
3390     {
3391         $output_rules .= ("tags-recursive:\n"
3392                           . "\tlist=\'\$(SUBDIRS)\'; for subdir in \$\$list; do \\\n"
3393                           # Never fail here if a subdir fails; it
3394                           # isn't important.
3395                           . "\t  test \"\$\$subdir\" = . || (cd \$\$subdir"
3396                           . " && \$(MAKE) \$(AM_MAKEFLAGS) tags); \\\n"
3397                           . "\tdone\n");
3398         push (@tag_deps, 'tags-recursive');
3399         &depend ('.PHONY', 'tags-recursive');
3400     }
3402     if (&saw_sources_p (1)
3403         || variable_defined ('ETAGS_ARGS')
3404         || @tag_deps)
3405     {
3406         my @config;
3407         foreach my $spec (@config_headers)
3408         {
3409             my ($out, @ins) = split_config_file_spec ($spec);
3410             foreach my $in (@ins)
3411               {
3412                 # If the config header source is in this directory,
3413                 # require it.
3414                 push @config, basename ($in)
3415                   if $relative_dir eq dirname ($in);
3416               }
3417         }
3418         $output_rules .= &file_contents ('tags',
3419                                          ('CONFIG' => "@config",
3420                                           'DIRS'   => "@tag_deps"));
3421         &examine_variable ('TAGS_DEPENDENCIES');
3422     }
3423     elsif (variable_defined ('TAGS_DEPENDENCIES'))
3424     {
3425         macro_error ('TAGS_DEPENDENCIES',
3426                      "doesn't make sense to define `TAGS_DEPENDENCIES' without sources or `ETAGS_ARGS'");
3427     }
3428     else
3429     {
3430         # Every Makefile must define some sort of TAGS rule.
3431         # Otherwise, it would be possible for a top-level "make TAGS"
3432         # to fail because some subdirectory failed.
3433         $output_rules .= "tags: TAGS\nTAGS:\n\n";
3434     }
3437 # Handle multilib support.
3438 sub handle_multilib
3440     if ($seen_multilib && $relative_dir eq '.')
3441     {
3442         $output_rules .= &file_contents ('multilib');
3443     }
3447 # $BOOLEAN
3448 # &for_dist_common ($A, $B)
3449 # -------------------------
3450 # Subroutine for &handle_dist: sort files to dist.
3452 # We put README first because it then becomes easier to make a
3453 # Usenet-compliant shar file (in these, README must be first).
3455 # FIXME: do more ordering of files here.
3456 sub for_dist_common
3458     return 0
3459         if $a eq $b;
3460     return -1
3461         if $a eq 'README';
3462     return 1
3463         if $b eq 'README';
3464     return $a cmp $b;
3468 # handle_dist ($MAKEFILE)
3469 # -----------------------
3470 # Handle 'dist' target.
3471 sub handle_dist
3473     my ($makefile) = @_;
3475     # `make dist' isn't used in a Cygnus-style tree.
3476     # Omit the rules so that people don't try to use them.
3477     return if $cygnus_mode;
3479     # Look for common files that should be included in distribution.
3480     # If the aux dir is set, and it does not have a Makefile.am, then
3481     # we check for these files there as well.
3482     my $check_aux = 0;
3483     my $auxdir = '';
3484     if ($relative_dir eq '.'
3485         && $config_aux_dir_set_in_configure_in)
3486     {
3487         ($auxdir = $config_aux_dir) =~ s,^\$\(top_srcdir\)/,,;
3488         if (! &is_make_dir ($auxdir))
3489         {
3490             $check_aux = 1;
3491         }
3492     }
3493     foreach my $cfile (@common_files)
3494     {
3495         if (-f ($relative_dir . "/" . $cfile)
3496             # The file might be absent, but if it can be built it's ok.
3497             || exists $targets{$cfile})
3498         {
3499             &push_dist_common ($cfile);
3500         }
3502         # Don't use `elsif' here because a file might meaningfully
3503         # appear in both directories.
3504         if ($check_aux && -f ($auxdir . '/' . $cfile))
3505         {
3506             &push_dist_common ($auxdir . '/' . $cfile);
3507         }
3508     }
3510     # We might copy elements from $configure_dist_common to
3511     # %dist_common if we think we need to.  If the file appears in our
3512     # directory, we would have discovered it already, so we don't
3513     # check that.  But if the file is in a subdir without a Makefile,
3514     # we want to distribute it here if we are doing `.'.  Ugly!
3515     if ($relative_dir eq '.')
3516     {
3517        foreach my $file (split (' ' , $configure_dist_common))
3518        {
3519            push_dist_common ($file)
3520              unless is_make_dir (dirname ($file));
3521        }
3522     }
3526     # Files to distributed.  Don't use &variable_value_as_list_recursive
3527     # as it recursively expands `$(dist_pkgdata_DATA)' etc.
3528     check_variable_defined_unconditionally ('DIST_COMMON');
3529     my @dist_common = split (' ', variable_value ('DIST_COMMON', 'TRUE'));
3530     @dist_common = uniq (sort for_dist_common (@dist_common));
3531     pretty_print ('DIST_COMMON = ', "\t", @dist_common);
3533     # Now that we've processed DIST_COMMON, disallow further attempts
3534     # to set it.
3535     $handle_dist_run = 1;
3537     # Scan EXTRA_DIST to see if we need to distribute anything from a
3538     # subdir.  If so, add it to the list.  I didn't want to do this
3539     # originally, but there were so many requests that I finally
3540     # relented.
3541     if (variable_defined ('EXTRA_DIST'))
3542     {
3543         # FIXME: This should be fixed to work with conditionals.  That
3544         # will require only making the entries in %dist_dirs under the
3545         # appropriate condition.  This is meaningful if the nature of
3546         # the distribution should depend upon the configure options
3547         # used.
3548         foreach (&variable_value_as_list_recursive ('EXTRA_DIST', ''))
3549         {
3550             next if /^\@.*\@$/;
3551             next unless s,/+[^/]+$,,;
3552             $dist_dirs{$_} = 1
3553                 unless $_ eq '.';
3554         }
3555     }
3557     # We have to check DIST_COMMON for extra directories in case the
3558     # user put a source used in AC_OUTPUT into a subdir.
3559     foreach (&variable_value_as_list_recursive ('DIST_COMMON', 'all'))
3560     {
3561         next if /^\@.*\@$/;
3562         next unless s,/+[^/]+$,,;
3563         $dist_dirs{$_} = 1
3564             unless $_ eq '.';
3565     }
3567     # Rule to check whether a distribution is viable.
3568     my %transform = ('DISTCHECK-HOOK' => &target_defined ('distcheck-hook'),
3569                      'GETTEXT'        => $seen_gettext);
3571     # Prepend $(distdir) to each directory given.
3572     my %rewritten = map { '$(distdir)/' . "$_" => 1 } keys %dist_dirs;
3573     $transform{'DISTDIRS'} = join (' ', sort keys %rewritten);
3575     # If we have SUBDIRS, create all dist subdirectories and do
3576     # recursive build.
3577     if (variable_defined ('SUBDIRS'))
3578     {
3579         # If SUBDIRS is conditionally defined, then set DIST_SUBDIRS
3580         # to all possible directories, and use it.  If DIST_SUBDIRS is
3581         # defined, just use it.
3582         my $dist_subdir_name;
3583         # Note that we check DIST_SUBDIRS first on purpose.  At least
3584         # one project uses so many conditional subdirectories that
3585         # calling variable_conditionally_defined on SUBDIRS will cause
3586         # automake to grow to 150Mb.  Sigh.
3587         if (variable_defined ('DIST_SUBDIRS')
3588             || variable_conditionally_defined ('SUBDIRS'))
3589         {
3590             $dist_subdir_name = 'DIST_SUBDIRS';
3591             if (! variable_defined ('DIST_SUBDIRS'))
3592             {
3593                 define_pretty_variable
3594                   ('DIST_SUBDIRS', '',
3595                    uniq (&variable_value_as_list_recursive ('SUBDIRS', 'all')));
3596             }
3597         }
3598         else
3599         {
3600             $dist_subdir_name = 'SUBDIRS';
3601             # We always define this because that is what `distclean'
3602             # wants.
3603             define_pretty_variable ('DIST_SUBDIRS', '', '$(SUBDIRS)');
3604         }
3606         $transform{'DIST_SUBDIR_NAME'} = $dist_subdir_name;
3607     }
3609     # If the target `dist-hook' exists, make sure it is run.  This
3610     # allows users to do random weird things to the distribution
3611     # before it is packaged up.
3612     push (@dist_targets, 'dist-hook')
3613       if &target_defined ('dist-hook');
3614     $transform{'DIST-TARGETS'} = join(' ', @dist_targets);
3616     # Defining $(DISTDIR).
3617     $transform{'DISTDIR'} = !variable_defined('distdir');
3618     $transform{'TOP_DISTDIR'} = backname ($relative_dir);
3620     $output_rules .= &file_contents ('distdir', %transform);
3624 # Handle subdirectories.
3625 sub handle_subdirs
3627     return
3628       unless variable_defined ('SUBDIRS');
3630     # Make sure each directory mentioned in SUBDIRS actually exists.
3631     foreach my $dir (&variable_value_as_list_recursive ('SUBDIRS', 'all'))
3632     {
3633         # Skip directories substituted by configure.
3634         next if $dir =~ /^\@.*\@$/;
3636         if (! -d $am_relative_dir . '/' . $dir)
3637         {
3638             macro_error ('SUBDIRS',
3639                          "required directory $am_relative_dir/$dir does not exist");
3640             next;
3641         }
3643         macro_error ('SUBDIRS', "directory should not contain `/'")
3644             if $dir =~ /\//;
3645     }
3647     $output_rules .= &file_contents ('subdirs');
3648     variable_pretty_output ('RECURSIVE_TARGETS', 'TRUE');
3652 # ($REGEN, @DEPENDENCIES)
3653 # &scan_aclocal_m4
3654 # ----------------
3655 # If aclocal.m4 creation is automated, return the list of its dependencies.
3656 sub scan_aclocal_m4
3658     my $regen_aclocal = 0;
3660     return (0, ())
3661       unless $relative_dir eq '.';
3663     &examine_variable ('CONFIG_STATUS_DEPENDENCIES');
3664     &examine_variable ('CONFIGURE_DEPENDENCIES');
3666     if (-f 'aclocal.m4')
3667     {
3668         &define_variable ("ACLOCAL_M4", '$(top_srcdir)/aclocal.m4');
3669         &push_dist_common ('aclocal.m4');
3671         my $aclocal = new Automake::XFile "< aclocal.m4";
3672         my $line = $aclocal->getline;
3673         $regen_aclocal = $line =~ 'generated automatically by aclocal';
3674     }
3676     my @ac_deps = ();
3678     if (-f 'acinclude.m4')
3679     {
3680         $regen_aclocal = 1;
3681         push @ac_deps, 'acinclude.m4';
3682     }
3684     if (variable_defined ('ACLOCAL_M4_SOURCES'))
3685     {
3686         push (@ac_deps, '$(ACLOCAL_M4_SOURCES)');
3687     }
3688     elsif (variable_defined ('ACLOCAL_AMFLAGS'))
3689     {
3690         # Scan all -I directories for m4 files.  These are our
3691         # dependencies.
3692         my $examine_next = 0;
3693         foreach my $amdir (&variable_value_as_list_recursive ('ACLOCAL_AMFLAGS', ''))
3694         {
3695             if ($examine_next)
3696             {
3697                 $examine_next = 0;
3698                 if ($amdir !~ /^\// && -d $amdir)
3699                 {
3700                     foreach my $ac_dep (&my_glob ($amdir . '/*.m4'))
3701                     {
3702                         $ac_dep =~ s/^\.\/+//;
3703                         push (@ac_deps, $ac_dep)
3704                           unless $ac_dep eq "aclocal.m4"
3705                             || $ac_dep eq "acinclude.m4";
3706                     }
3707                 }
3708             }
3709             elsif ($amdir eq '-I')
3710             {
3711                 $examine_next = 1;
3712             }
3713         }
3714     }
3716     # Note that it might be possible that aclocal.m4 doesn't exist but
3717     # should be auto-generated.  This case probably isn't very
3718     # important.
3720     return ($regen_aclocal, @ac_deps);
3724 # @DEPENDENCY
3725 # &rewrite_inputs_into_dependencies ($ADD_SRCDIR, @INPUTS)
3726 # --------------------------------------------------------
3727 # Rewrite a list of input files into a form suitable to put on a
3728 # dependency list.  The idea is that if an input file has a directory
3729 # part the same as the current directory, then the directory part is
3730 # simply removed.  But if the directory part is different, then
3731 # $(top_srcdir) is prepended.  Among other things, this is used to
3732 # generate the dependency list for the output files generated by
3733 # AC_OUTPUT.  Consider what the dependencies should look like in this
3734 # case:
3735 #   AC_OUTPUT(src/out:src/in1:lib/in2)
3736 # The first argument, ADD_SRCDIR, is 1 if $(top_srcdir) should be added.
3737 # If 0 then files that require this addition will simply be ignored.
3738 sub rewrite_inputs_into_dependencies ($@)
3740     my ($add_srcdir, @inputs) = @_;
3741     my @newinputs;
3743     foreach my $single (@inputs)
3744     {
3745         if (dirname ($single) eq $relative_dir)
3746         {
3747             push (@newinputs, basename ($single));
3748         }
3749         elsif ($add_srcdir)
3750         {
3751             push (@newinputs, '$(top_srcdir)/' . $single);
3752         }
3753     }
3755     return @newinputs;
3758 # Handle remaking and configure stuff.
3759 # We need the name of the input file, to do proper remaking rules.
3760 sub handle_configure
3762     my ($local, $input, @secondary_inputs) = @_;
3764     my $input_base = basename ($input);
3765     my $local_base = basename ($local);
3767     my $amfile = $input_base . '.am';
3768     # We know we can always add '.in' because it really should be an
3769     # error if the .in was missing originally.
3770     my $infile = '$(srcdir)/' . $input_base . '.in';
3771     my $colon_infile = '';
3772     if ($local ne $input || @secondary_inputs)
3773     {
3774         $colon_infile = ':' . $input . '.in';
3775     }
3776     $colon_infile .= ':' . join (':', @secondary_inputs)
3777         if @secondary_inputs;
3779     my @rewritten = rewrite_inputs_into_dependencies (1, @secondary_inputs);
3781     my ($regen_aclocal_m4, @aclocal_m4_deps) = scan_aclocal_m4 ();
3783     $output_rules .=
3784       &file_contents ('configure',
3785                       ('MAKEFILE'
3786                        => $local_base,
3787                        'MAKEFILE-DEPS'
3788                        => "@rewritten",
3789                        'CONFIG-MAKEFILE'
3790                        => ((($relative_dir eq '.') ? '$@' : '$(subdir)/$@')
3791                            . $colon_infile),
3792                        'MAKEFILE-IN'
3793                        => $infile,
3794                        'MAKEFILE-IN-DEPS'
3795                        => "@include_stack",
3796                        'MAKEFILE-AM'
3797                        => $amfile,
3798                        'STRICTNESS'
3799                        => $cygnus_mode ? 'cygnus' : $strictness_name,
3800                        'USE-DEPS'
3801                        => $cmdline_use_dependencies ? '' : ' --ignore-deps',
3802                        'MAKEFILE-AM-SOURCES'
3803                        =>  "$input$colon_infile",
3804                        'REGEN-ACLOCAL-M4'
3805                        => $regen_aclocal_m4,
3806                        'ACLOCAL_M4_DEPS'
3807                        => "@aclocal_m4_deps"));
3809     if ($relative_dir eq '.')
3810     {
3811         &push_dist_common ('acconfig.h')
3812             if -f 'acconfig.h';
3813     }
3815     # If we have a configure header, require it.
3816     my $hdr_index = 0;
3817     my @distclean_config;
3818     foreach my $spec (@config_headers)
3819       {
3820         $hdr_index += 1;
3821         # $CONFIG_H_PATH: config.h from top level.
3822         my ($config_h_path, @ins) = split_config_file_spec ($spec);
3823         my $config_h_dir = dirname ($config_h_path);
3825         # If the header is in the current directory we want to build
3826         # the header here.  Otherwise, if we're at the topmost
3827         # directory and the header's directory doesn't have a
3828         # Makefile, then we also want to build the header.
3829         if ($relative_dir eq $config_h_dir
3830             || ($relative_dir eq '.' && ! &is_make_dir ($config_h_dir)))
3831         {
3832             my ($cn_sans_dir, $stamp_dir);
3833             if ($relative_dir eq $config_h_dir)
3834             {
3835                 $cn_sans_dir = basename ($config_h_path);
3836                 $stamp_dir = '';
3837             }
3838             else
3839             {
3840                 $cn_sans_dir = $config_h_path;
3841                 if ($config_h_dir eq '.')
3842                 {
3843                     $stamp_dir = '';
3844                 }
3845                 else
3846                 {
3847                     $stamp_dir = $config_h_dir . '/';
3848                 }
3849             }
3851             # Compute relative path from directory holding output
3852             # header to directory holding input header.  FIXME:
3853             # doesn't handle case where we have multiple inputs.
3854             my $in0_sans_dir;
3855             if (dirname ($ins[0]) eq $relative_dir)
3856             {
3857                 $in0_sans_dir = basename ($ins[0]);
3858             }
3859             else
3860             {
3861                 $in0_sans_dir = backname ($relative_dir) . '/' . $ins[0];
3862             }
3864             require_file ($config_header_location, FOREIGN, $in0_sans_dir);
3866             # Header defined and in this directory.
3867             my @files;
3868             if (-f $config_h_path . '.top')
3869             {
3870                 push (@files, "$cn_sans_dir.top");
3871             }
3872             if (-f $config_h_path . '.bot')
3873             {
3874                 push (@files, "$cn_sans_dir.bot");
3875             }
3877             push_dist_common (@files);
3879             # For now, acconfig.h can only appear in the top srcdir.
3880             if (-f 'acconfig.h')
3881             {
3882                 push (@files, '$(top_srcdir)/acconfig.h');
3883             }
3885             my $stamp = "${stamp_dir}stamp-h${hdr_index}";
3886             $output_rules .=
3887               file_contents ('remake-hdr',
3888                              ('FILES'         => "@files",
3889                               'CONFIG_H'      => $cn_sans_dir,
3890                               'CONFIG_HIN'    => $in0_sans_dir,
3891                               'CONFIG_H_PATH' => $config_h_path,
3892                               'STAMP'         => "$stamp"));
3894             push @distclean_config, $cn_sans_dir;
3895         }
3896     }
3898     $output_rules .= file_contents ('clean-hdr',
3899                                     ('FILES' => "@distclean_config"))
3900       if @distclean_config;
3902     # Set location of mkinstalldirs.
3903     define_variable ('mkinstalldirs',
3904                      ('$(SHELL) ' . $config_aux_dir . '/mkinstalldirs'));
3906     macro_error ('CONFIG_HEADER',
3907                  "`CONFIG_HEADER' is an anachronism; now determined from `$configure_ac'")
3908         if variable_defined ('CONFIG_HEADER');
3910     my @config_h;
3911     foreach my $spec (@config_headers)
3912       {
3913         my ($out, @ins) = split_config_file_spec ($spec);
3914         # Generate CONFIG_HEADER define.
3915         if ($relative_dir eq dirname ($out))
3916         {
3917             push @config_h, basename ($out);
3918         }
3919         else
3920         {
3921             push @config_h, "\$(top_builddir)/$out";
3922         }
3923     }
3924     define_variable ("CONFIG_HEADER", "@config_h")
3925       if @config_h;
3927     # Now look for other files in this directory which must be remade
3928     # by config.status, and generate rules for them.
3929     my @actual_other_files = ();
3930     foreach my $lfile (@other_input_files)
3931     {
3932         my $file;
3933         my @inputs;
3934         if ($lfile =~ /^([^:]*):(.*)$/)
3935         {
3936             # This is the ":" syntax of AC_OUTPUT.
3937             $file = $1;
3938             @inputs = split (':', $2);
3939         }
3940         else
3941         {
3942             # Normal usage.
3943             $file = $lfile;
3944             @inputs = $file . '.in';
3945         }
3947         # Automake files should not be stored in here, but in %MAKE_LIST.
3948         prog_error ("$lfile in \@other_input_files")
3949           if -f $file . '.am';
3951         my $local = basename ($file);
3953         # Make sure the dist directory for each input file is created.
3954         # We only have to do this at the topmost level though.  This
3955         # is a bit ugly but it easier than spreading out the logic,
3956         # especially in cases like AC_OUTPUT(foo/out:bar/in), where
3957         # there is no Makefile in bar/.
3958         if ($relative_dir eq '.')
3959         {
3960             foreach (@inputs)
3961             {
3962                 $dist_dirs{dirname ($_)} = 1;
3963             }
3964         }
3966         # We skip files that aren't in this directory.  However, if
3967         # the file's directory does not have a Makefile, and we are
3968         # currently doing `.', then we create a rule to rebuild the
3969         # file in the subdir.
3970         my $fd = dirname ($file);
3971         if ($fd ne $relative_dir)
3972         {
3973             if ($relative_dir eq '.' && ! &is_make_dir ($fd))
3974             {
3975                 $local = $file;
3976             }
3977             else
3978             {
3979                 next;
3980             }
3981         }
3983         # Some users have been tempted to put `stamp-h' in the
3984         # AC_OUTPUT line.  This won't do the right thing, so we
3985         # explicitly fail here.
3986         if ($local eq 'stamp-h')
3987         {
3988             # FIXME: allow real filename.
3989             file_error ($ac_config_files_location,
3990                         'stamp-h should not appear in AC_OUTPUT');
3991             next;
3992         }
3994         my @rewritten_inputs = rewrite_inputs_into_dependencies (1, @inputs);
3995         $output_rules .= ($local . ': '
3996                           . '$(top_builddir)/config.status '
3997                           . "@rewritten_inputs\n"
3998                           . "\t"
3999                           . 'cd $(top_builddir) && '
4000                           . '$(SHELL) ./config.status '
4001                           . ($relative_dir eq '.' ? '' : '$(subdir)/')
4002                           . '$@'
4003                           . "\n");
4004         push (@actual_other_files, $local);
4006         # Require all input files.
4007         require_file ($ac_config_files_location, FOREIGN,
4008                       rewrite_inputs_into_dependencies (0, @inputs));
4009     }
4011     # These files get removed by "make clean".
4012     define_pretty_variable ('CONFIG_CLEAN_FILES', '', @actual_other_files);
4015 # Handle C headers.
4016 sub handle_headers
4018     my @r = &am_install_var ('-defaultdist', 'header', 'HEADERS', 'include',
4019                              'oldinclude', 'pkginclude',
4020                              'noinst', 'check');
4021     foreach (@r)
4022     {
4023         next unless /\..*$/;
4024         &saw_extension ($&);
4025     }
4028 sub handle_gettext
4030     return if ! $seen_gettext || $relative_dir ne '.';
4032     if (! variable_defined ('SUBDIRS'))
4033     {
4034         conf_error ("AM_GNU_GETTEXT used but SUBDIRS not defined");
4035         return;
4036     }
4038     my @subdirs = &variable_value_as_list_recursive ('SUBDIRS', 'all');
4039     macro_error ('SUBDIRS',
4040                  "AM_GNU_GETTEXT used but `po' not in SUBDIRS")
4041         if ! grep ('po', @subdirs);
4042     macro_error ('SUBDIRS',
4043                  "AM_GNU_GETTEXT used but `intl' not in SUBDIRS")
4044         if ! grep ('intl', @subdirs);
4046     require_file ($ac_gettext_location, GNU, 'ABOUT-NLS');
4049 # Handle footer elements.
4050 sub handle_footer
4052     # NOTE don't use define_pretty_variable here, because
4053     # $contents{...} is already defined.
4054     $output_vars .= 'SOURCES = ' . variable_value ('SOURCES') . "\n\n"
4055       if variable_value ('SOURCES');
4058     target_error ('.SUFFIXES',
4059                   "use variable `SUFFIXES', not target `.SUFFIXES'")
4060       if target_defined ('.SUFFIXES');
4062     # Note: AIX 4.1 /bin/make will fail if any suffix rule appears
4063     # before .SUFFIXES.  So we make sure that .SUFFIXES appears before
4064     # anything else, by sticking it right after the default: target.
4065     $output_header .= ".SUFFIXES:\n";
4066     if (@suffixes || variable_defined ('SUFFIXES'))
4067     {
4068         # Make sure suffixes has unique elements.  Sort them to ensure
4069         # the output remains consistent.  However, $(SUFFIXES) is
4070         # always at the start of the list, unsorted.  This is done
4071         # because make will choose rules depending on the ordering of
4072         # suffixes, and this lets the user have some control.  Push
4073         # actual suffixes, and not $(SUFFIXES).  Some versions of make
4074         # do not like variable substitutions on the .SUFFIXES line.
4075         my @user_suffixes = (variable_defined ('SUFFIXES')
4076                              ? &variable_value_as_list_recursive ('SUFFIXES', '')
4077                              : ());
4079         my %suffixes = map { $_ => 1 } @suffixes;
4080         delete @suffixes{@user_suffixes};
4082         $output_header .= (".SUFFIXES: "
4083                            . join (' ', @user_suffixes, sort keys %suffixes)
4084                            . "\n");
4085     }
4087     $output_trailer .= file_contents ('footer');
4090 # Deal with installdirs target.
4091 sub handle_installdirs ()
4093     $output_rules .=
4094       &file_contents ('install',
4095                       ('_am_installdirs'
4096                        => variable_value ('_am_installdirs') || '',
4097                        'installdirs-local'
4098                        => (target_defined ('installdirs-local')
4099                            ? ' installdirs-local' : '')));
4103 # Deal with all and all-am.
4104 sub handle_all ($)
4106     my ($makefile) = @_;
4108     # Output `all-am'.
4110     # Put this at the beginning for the sake of non-GNU makes.  This
4111     # is still wrong if these makes can run parallel jobs.  But it is
4112     # right enough.
4113     unshift (@all, basename ($makefile));
4115     foreach my $spec (@config_headers)
4116       {
4117         my ($out, @ins) = split_config_file_spec ($spec);
4118         push (@all, basename ($out))
4119           if dirname ($out) eq $relative_dir;
4120       }
4122     # Install `all' hooks.
4123     if (&target_defined ("all-local"))
4124     {
4125       push (@all, "all-local");
4126       &depend ('.PHONY', "all-local");
4127     }
4129     &pretty_print_rule ("all-am:", "\t\t", @all);
4130     &depend ('.PHONY', 'all-am', 'all');
4133     # Output `all'.
4135     my @local_headers = ();
4136     push @local_headers, '$(BUILT_SOURCES)'
4137       if variable_defined ('BUILT_SOURCES');
4138     foreach my $spec (@config_headers)
4139       {
4140         my ($out, @ins) = split_config_file_spec ($spec);
4141         push @local_headers, basename ($out)
4142           if dirname ($out) eq $relative_dir;
4143       }
4145     if (@local_headers)
4146       {
4147         # We need to make sure config.h is built before we recurse.
4148         # We also want to make sure that built sources are built
4149         # before any ordinary `all' targets are run.  We can't do this
4150         # by changing the order of dependencies to the "all" because
4151         # that breaks when using parallel makes.  Instead we handle
4152         # things explicitly.
4153         $output_all .= ("all: @local_headers"
4154                         . "\n\t"
4155                         . '$(MAKE) $(AM_MAKEFLAGS) '
4156                         . (variable_defined ('SUBDIRS')
4157                            ? 'all-recursive' : 'all-am')
4158                         . "\n\n");
4159       }
4160     else
4161       {
4162         $output_all .= "all: " . (variable_defined ('SUBDIRS')
4163                                   ? 'all-recursive' : 'all-am') . "\n\n";
4164       }
4168 # Handle check merge target specially.
4169 sub do_check_merge_target
4171     if (&target_defined ('check-local'))
4172     {
4173         # User defined local form of target.  So include it.
4174         push (@check_tests, 'check-local');
4175         &depend ('.PHONY', 'check-local');
4176     }
4178     # In --cygnus mode, check doesn't depend on all.
4179     if ($cygnus_mode)
4180     {
4181         # Just run the local check rules.
4182         &pretty_print_rule ('check-am:', "\t\t", @check);
4183     }
4184     else
4185     {
4186         # The check target must depend on the local equivalent of
4187         # `all', to ensure all the primary targets are built.  Then it
4188         # must build the local check rules.
4189         $output_rules .= "check-am: all-am\n";
4190         &pretty_print_rule ("\t\$(MAKE) \$(AM_MAKEFLAGS)", "\t  ",
4191                             @check)
4192             if @check;
4193     }
4194     &pretty_print_rule ("\t\$(MAKE) \$(AM_MAKEFLAGS)", "\t  ",
4195                         @check_tests)
4196         if @check_tests;
4198     &depend ('.PHONY', 'check', 'check-am');
4199     $output_rules .= ("check: "
4200                       . (variable_defined ('SUBDIRS')
4201                          ? 'check-recursive' : 'check-am')
4202                       . "\n");
4205 # Handle all 'clean' targets.
4206 sub handle_clean
4208     my %transform;
4210     # Don't include `MAINTAINER'; it is handled specially below.
4211     foreach my $name ('MOSTLY', '', 'DIST')
4212     {
4213       $transform{"${name}CLEAN"} = variable_defined ("${name}CLEANFILES");
4214     }
4216     # Built sources are automatically removed by maintainer-clean.
4217     push (@maintainer_clean_files, '$(BUILT_SOURCES)')
4218         if variable_defined ('BUILT_SOURCES');
4219     push (@maintainer_clean_files, '$(MAINTAINERCLEANFILES)')
4220         if variable_defined ('MAINTAINERCLEANFILES');
4222     $output_rules .= &file_contents ('clean',
4223                                      (%transform,
4224                                       'MCFILES'
4225                                       # Join with no space to avoid
4226                                       # spurious `test -z' success at
4227                                       # runtime.
4228                                       => join ('', @maintainer_clean_files),
4229                                       'MFILES'
4230                                       # A space is required in the join here.
4231                                       => "@maintainer_clean_files"));
4235 # &depend ($CATEGORY, @DEPENDENDEES)
4236 # ----------------------------------
4237 # The target $CATEGORY depends on @DEPENDENDEES.
4238 sub depend
4240     my ($category, @dependendees) = @_;
4241     {
4242       push (@{$dependencies{$category}}, @dependendees);
4243     }
4247 # &target_cmp ($A, $B)
4248 # --------------------
4249 # Subroutine for &handle_factored_dependencies to let `.PHONY' be last.
4250 sub target_cmp
4252     return 0
4253         if $a eq $b;
4254     return -1
4255         if $b eq '.PHONY';
4256     return 1
4257         if $a eq '.PHONY';
4258     return $a cmp $b;
4262 # &handle_factored_dependencies ()
4263 # --------------------------------
4264 # Handle everything related to gathered targets.
4265 sub handle_factored_dependencies
4267     # Reject bad hooks.
4268     foreach my $utarg ('uninstall-data-local', 'uninstall-data-hook',
4269                        'uninstall-exec-local', 'uninstall-exec-hook')
4270     {
4271         if (&target_defined ($utarg))
4272         {
4273             my $x = $utarg;
4274             $x =~ s/(data|exec)-//;
4275             target_error ($utarg, "use `$x', not `$utarg'");
4276         }
4277     }
4279     if (&target_defined ('install-local'))
4280     {
4281         target_error ('install-local',
4282                       "use `install-data-local' or `install-exec-local', "
4283                       . "not `install-local'");
4284     }
4286     if (!defined $options{'no-installinfo'}
4287         && &target_defined ('install-info-local'))
4288     {
4289         target_error ('install-info-local',
4290                       "`install-info-local' target defined but "
4291                       . "`no-installinfo' option not in use");
4292     }
4294     # Install the -local hooks.
4295     foreach (keys %dependencies)
4296     {
4297       # Hooks are installed on the -am targets.
4298       s/-am$// or next;
4299       if (&target_defined ("$_-local"))
4300         {
4301           depend ("$_-am", "$_-local");
4302           &depend ('.PHONY', "$_-local");
4303         }
4304     }
4306     # Install the -hook hooks.
4307     # FIXME: Why not be as liberal as we are with -local hooks?
4308     foreach ('install-exec', 'install-data', 'uninstall')
4309     {
4310       if (&target_defined ("$_-hook"))
4311         {
4312           $actions{"$_-am"} .=
4313             ("\t\@\$(NORMAL_INSTALL)\n"
4314              . "\t" . '$(MAKE) $(AM_MAKEFLAGS) ' . "$_-hook\n");
4315         }
4316     }
4318     # All the required targets are phony.
4319     depend ('.PHONY', keys %required_targets);
4321     # Actually output gathered targets.
4322     foreach (sort target_cmp keys %dependencies)
4323     {
4324         # If there is nothing about this guy, skip it.
4325         next
4326           unless (@{$dependencies{$_}}
4327                   || $actions{$_}
4328                   || $required_targets{$_});
4329         &pretty_print_rule ("$_:", "\t",
4330                             uniq (sort @{$dependencies{$_}}));
4331         $output_rules .= $actions{$_}
4332           if defined $actions{$_};
4333         $output_rules .= "\n";
4334     }
4338 # &handle_tests_dejagnu ()
4339 # ------------------------
4340 sub handle_tests_dejagnu
4342     push (@check_tests, 'check-DEJAGNU');
4343     $output_rules .= file_contents ('dejagnu');
4347 # Handle TESTS variable and other checks.
4348 sub handle_tests
4350     if (defined $options{'dejagnu'})
4351     {
4352         &handle_tests_dejagnu;
4353     }
4354     else
4355     {
4356         foreach my $c ('DEJATOOL', 'RUNTEST', 'RUNTESTFLAGS')
4357         {
4358             macro_error ($c,
4359                          "`$c' defined but `dejagnu' not in `AUTOMAKE_OPTIONS'")
4360               if variable_defined ($c);
4361         }
4362     }
4364     if (variable_defined ('TESTS'))
4365     {
4366         push (@check_tests, 'check-TESTS');
4367         $output_rules .= &file_contents ('check');
4368     }
4371 # Handle Emacs Lisp.
4372 sub handle_emacs_lisp
4374     my @elfiles = &am_install_var ('-candist', 'lisp', 'LISP',
4375                                    'lisp', 'noinst');
4377     return if ! @elfiles;
4379     # Generate .elc files.
4380     my @elcfiles = map { $_ . 'c' } @elfiles;
4381     define_pretty_variable ('ELCFILES', '', @elcfiles);
4383     push (@all, '$(ELCFILES)');
4385     &am_error ("`lisp_LISP' defined but `AM_PATH_LISPDIR' not in `$configure_ac'")
4386       if ! $am_lispdir_location && variable_defined ('lisp_LISP');
4388     require_conf_file ($am_lispdir_location, FOREIGN, 'elisp-comp');
4389     &define_variable ('elisp_comp', $config_aux_dir . '/elisp-comp');
4392 # Handle Python
4393 sub handle_python
4395     my @pyfiles = &am_install_var ('-defaultdist', 'python', 'PYTHON',
4396                                    'python', 'noinst');
4397     return if ! @pyfiles;
4399     # Found some python.
4400     &am_error ("`python_PYTHON' defined but `AM_PATH_PYTHON' not in `$configure_ac'")
4401         if ! $pythondir_location && variable_defined ('python_PYTHON');
4403     require_conf_file ($pythondir_location, FOREIGN, 'py-compile');
4404     &define_variable ('py_compile', $config_aux_dir . '/py-compile');
4407 # Handle Java.
4408 sub handle_java
4410     my @sourcelist = &am_install_var ('-candist',
4411                                       'java', 'JAVA',
4412                                       'java', 'noinst', 'check');
4413     return if ! @sourcelist;
4415     my @prefix = am_primary_prefixes ('JAVA', 1,
4416                                       'java', 'noinst', 'check');
4418     my $dir;
4419     foreach my $curs (@prefix)
4420       {
4421         next
4422           if $curs eq 'EXTRA';
4424         macro_error ($curs . '_JAVA',
4425                      "multiple _JAVA primaries in use")
4426           if defined $dir;
4427         $dir = $curs;
4428       }
4431     push (@all, 'class' . $dir . '.stamp');
4435 # Handle some of the minor options.
4436 sub handle_minor_options
4438     if (defined $options{'readme-alpha'})
4439     {
4440         if ($relative_dir eq '.')
4441         {
4442             if ($package_version !~ /^$GNITS_VERSION_PATTERN$/)
4443             {
4444                 # FIXME: allow real filename.
4445                 file_error ($package_version_location,
4446                             "version `$package_version' doesn't follow Gnits standards");
4447             }
4448             elsif (defined $1 && -f 'README-alpha')
4449             {
4450                 # This means we have an alpha release.  See
4451                 # GNITS_VERSION_PATTERN for details.
4452                 require_file_with_macro ('AUTOMAKE_OPTIONS',
4453                                          FOREIGN, 'README-alpha');
4454             }
4455         }
4456     }
4459 ################################################################
4461 # ($OUTPUT, @INPUTS)
4462 # &split_config_file_spec ($SPEC)
4463 # -------------------------------
4464 # Decode the Autoconf syntax for config files (files, headers, links
4465 # etc.).
4466 sub split_config_file_spec ($)
4468   my ($spec) = @_;
4469   my ($output, @inputs) = split (/:/, $spec);
4471   push @inputs, "$output.in"
4472     unless @inputs;
4474   return ($output, @inputs);
4478 my %make_list;
4480 # &scan_autoconf_config_files ($CONFIG-FILES)
4481 # -------------------------------------------
4482 # Study $CONFIG-FILES which is the first argument to AC_CONFIG_FILES
4483 # (or AC_OUTPUT).
4484 sub scan_autoconf_config_files
4486     my ($config_files) = @_;
4487     # Look at potential Makefile.am's.
4488     foreach (split ' ', $config_files)
4489     {
4490         # Must skip empty string for Perl 4.
4491         next if $_ eq "\\" || $_ eq '';
4493         # Handle $local:$input syntax.  Note that we ignore
4494         # every input file past the first, though we keep
4495         # those around for later.
4496         my ($local, $input, @rest) = split (/:/);
4497         if (! $input)
4498         {
4499             $input = $local;
4500         }
4501         else
4502         {
4503             # FIXME: should be error if .in is missing.
4504             $input =~ s/\.in$//;
4505         }
4507         if (-f $input . '.am')
4508         {
4509             # We have a file that automake should generate.
4510             $make_list{$input} = join (':', ($local, @rest));
4511         }
4512         else
4513         {
4514             # We have a file that automake should cause to be
4515             # rebuilt, but shouldn't generate itself.
4516             push (@other_input_files, $_);
4517         }
4518     }
4522 # &scan_autoconf_traces ($FILENAME)
4523 # ---------------------------------
4524 # FIXME: For the time being, we don't care about the FILENAME.
4525 sub scan_autoconf_traces ($)
4527   my ($filename) = @_;
4529   my @traced = qw(AC_CANONICAL_HOST
4530                   AC_CANONICAL_SYSTEM
4531                   AC_CONFIG_AUX_DIR
4532                   AC_CONFIG_FILES
4533                   AC_INIT
4534                   AC_LIBSOURCE
4535                   AC_PROG_LEX
4536                   AC_PROG_LIBTOOL AM_PROG_LIBTOOL
4537                   AC_SUBST
4538                   AM_AUTOMAKE_VERSION
4539                   AM_CONDITIONAL
4540                   AM_CONFIG_HEADER
4541                   AM_C_PROTOTYPES
4542                   AM_GNU_GETTEXT
4543                   AM_INIT_AUTOMAKE
4544                   AM_MAINTAINER_MODE
4545                   AM_PATH_LISPDIR
4546                   AM_PATH_PYTHON
4547                   AM_PROG_CC_C_O);
4549   my $traces = "$ENV{amtraces} ";
4551   # Use a separator unlikely to be used, not `:', the default, which
4552   # has a precise meaning for AC_CONFIG_FILES and so on.
4553   $traces .= join (' ',
4554                    map { "--trace=$_" . ':\$f:\$l::\$n::\${::}%' } @traced);
4556   my $tracefh = new Automake::XFile ("$traces |");
4557   verbose "reading $traces";
4559   while ($_ = $tracefh->getline)
4560     {
4561       chomp;
4562       my ($here, @args) = split /::/;
4563       my $macro = $args[0];
4565       # Alphabetical ordering please.
4566       if ($macro eq 'AC_CANONICAL_HOST')
4567         {
4568           if (! $seen_canonical)
4569             {
4570               $seen_canonical = AC_CANONICAL_HOST;
4571               $canonical_location = $here;
4572             };
4573         }
4574       elsif ($macro eq 'AC_CANONICAL_SYSTEM')
4575         {
4576           $seen_canonical = AC_CANONICAL_SYSTEM;
4577           $canonical_location = $here;
4578         }
4579       elsif ($macro eq 'AC_CONFIG_AUX_DIR')
4580         {
4581           @config_aux_path = $args[1];
4582           $config_aux_dir_set_in_configure_in = 1;
4583         }
4584       elsif ($macro eq 'AC_CONFIG_FILES')
4585         {
4586           # Look at potential Makefile.am's.
4587           $ac_config_files_location = $here;
4588           &scan_autoconf_config_files ($args[1]);
4589         }
4590       elsif ($macro eq 'AC_INIT')
4591         {
4592           if (defined $args[2])
4593             {
4594               $package_version = $args[2];
4595               $package_version_location = $here;
4596             }
4597         }
4598       elsif ($macro eq 'AC_LIBSOURCE')
4599         {
4600           $libsources{$args[1]} = $here;
4601         }
4602       elsif ($macro =~ /^A(C|M)_PROG_LIBTOOL$/)
4603         {
4604           $seen_libtool = $here;
4605         }
4606       elsif ($macro eq 'AC_PROG_LEX')
4607         {
4608           $seen_prog_lex = $here;
4609         }
4610       elsif ($macro eq 'AC_SUBST')
4611         {
4612           # Just check for alphanumeric in AC_SUBST.  If you do
4613           # AC_SUBST(5), then too bad.
4614           $configure_vars{$args[1]} = $here
4615             if $args[1] =~ /^\w+$/;
4616         }
4617       elsif ($macro eq 'AM_AUTOMAKE_VERSION')
4618         {
4619           file_error ($here,
4620                       "version mismatch.  This is Automake $VERSION,\n" .
4621                       "but the definition used by this AM_INIT_AUTOMAKE\n" .
4622                       "comes from Automake $args[1].  You should recreate\n" .
4623                       "aclocal.m4 with aclocal and run automake again.\n")
4624               if ($VERSION ne $args[1]);
4626           $seen_automake_version = 1;
4627         }
4628       elsif ($macro eq 'AM_CONDITIONAL')
4629         {
4630           $configure_cond{$args[1]} = $here;
4631         }
4632       elsif ($macro eq 'AM_CONFIG_HEADER')
4633         {
4634           $config_header_location = $here;
4635           push @config_headers, split (' ', $args[1]);
4636         }
4637       elsif ($macro eq 'AM_C_PROTOTYPES')
4638         {
4639           $am_c_prototypes = $here;
4640         }
4641       elsif ($macro eq 'AM_GNU_GETTEXT')
4642         {
4643           $seen_gettext = $here;
4644           $ac_gettext_location = $here;
4645         }
4646       elsif ($macro eq 'AM_INIT_AUTOMAKE')
4647         {
4648           $seen_init_automake = $here;
4649           if (defined $args[2])
4650             {
4651               $package_version = $args[2];
4652               $package_version_location = $here;
4653             }
4654           elsif (defined $args[1])
4655             {
4656               $global_options = $args[1];
4657             }
4658         }
4659       elsif ($macro eq 'AM_MAINTAINER_MODE')
4660         {
4661           $seen_maint_mode = $here;
4662         }
4663       elsif ($macro eq 'AM_PATH_LISPDIR')
4664         {
4665           $am_lispdir_location = $here;
4666         }
4667       elsif ($macro eq 'AM_PATH_PYTHON')
4668         {
4669           $pythondir_location = $here;
4670         }
4671       elsif ($macro eq 'AM_PROG_CC_C_O')
4672         {
4673           $seen_cc_c_o = $here;
4674         }
4675    }
4679 # &scan_one_autoconf_file ($FILENAME)
4680 # -----------------------------------
4681 # Scan one file for interesting things.  Subroutine of
4682 # &scan_autoconf_files.
4683 sub scan_one_autoconf_file
4685     my ($filename) = @_;
4687     # Some macros already provide the right traces to enable generic
4688     # code and specific arguments, instead of dedicated code.  But
4689     # currently we don't handle traces.  Rewrite these dedicated
4690     # macros handling into the generic macro invocation, and let our
4691     # generic case handle them.
4693     my %generalize =
4694       (
4695        'AC_FUNC_ALLOCA'           => 'AC_LIBSOURCES([alloca.c])',
4696        'AC_FUNC_GETLOADAVG'       => 'AC_LIBSOURCES([getloadavg.c])',
4697        'AC_FUNC_MEMCMP'           => 'AC_LIBSOURCES([memcmp.c])',
4698        'AC_STRUCT_ST_BLOCKS'      => 'AC_LIBSOURCES([fileblocks.c])',
4699        'A[CM]_REPLACE_GNU_GETOPT' => 'AC_LIBSOURCES([getopt.c, getopt1.c])',
4700        'A[CM]_FUNC_STRTOD'        => 'AC_LIBSOURCES([strtod.c])',
4701        'AM_WITH_REGEX'      => 'AC_LIBSOURCES([rx.c, rx.h, regex.c, regex.h])',
4702        'AC_FUNC_MKTIME'           => 'AC_LIBSOURCES([mktime.c])',
4703        'A[CM]_FUNC_ERROR_AT_LINE' => 'AC_LIBSOURCES([error.c, error.h])',
4704        'A[CM]_FUNC_OBSTACK'       => 'AC_LIBSOURCES([obstack.c, obstack.h])',
4705       );
4707     my $configfh = new Automake::XFile ("< $filename");
4708     verbose "reading $filename";
4710     my ($in_ac_output, $in_ac_replace) = (0, 0);
4711     while ($_ = $configfh->getline)
4712     {
4713         # Remove comments from current line.
4714         s/\bdnl\b.*$//;
4715         s/\#.*$//;
4717         # Skip macro definitions.  Otherwise we might be confused into
4718         # thinking that a macro that was only defined was actually
4719         # used.
4720         next if /AC_DEFUN/;
4722         # Follow includes.  This is a weirdness commonly in use at
4723         # Cygnus and hopefully nowhere else.
4724         if (/sinclude\((.*)\)/ && -f $1)
4725         {
4726             # $_ being local, if we don't preserve it, when coming
4727             # back we will have $_ undefined, which is bad for the
4728             # the rest of this routine.
4729             my $underscore = $_;
4730             &scan_one_autoconf_file ($1);
4731             $_ = $underscore;
4732         }
4734         for my $generalize (keys %generalize)
4735           {
4736             s/\b$generalize\b/$generalize{$generalize}/g;
4737           }
4740         my $here = "$filename:$.";
4742         # Populate libobjs array.
4743         if (/LIBOBJS="(.*)\s+\$LIBOBJS"/
4744                || /LIBOBJS="\$LIBOBJS\s+(.*)"/)
4745         {
4746             foreach my $libobj_iter (split (' ', $1))
4747             {
4748                 if ($libobj_iter =~ /^(.*)\.o(bj)?$/
4749                     || $libobj_iter =~ /^(.*)\.\$ac_objext$/
4750                     || $libobj_iter =~ /^(.*)\.\$\{ac_objext\}$/)
4751                 {
4752                     $libsources{$1 . '.c'} = $here;
4753                 }
4754             }
4755         }
4756         elsif (/AC_LIBOBJ\(([^)]+)\)/)
4757         {
4758             $libsources{unquote_m4_arg ($1) . ".c"} = $here;
4759         }
4760         elsif (/AC_LIBSOURCE\(([^)]+)\)/)
4761         {
4762             $libsources{&unquote_m4_arg ($1)} = $here;
4763         }
4764         elsif (/AC_LIBSOURCES\(([^)]+)\)/)
4765         {
4766             foreach my $lc_iter (split (/[, ]+/, &unquote_m4_arg ($1)))
4767             {
4768                 $libsources{$lc_iter} = $here;
4769             }
4770         }
4772         if (! $in_ac_replace && s/AC_REPLACE_FUNCS\s*\(\[?//)
4773         {
4774             $in_ac_replace = 1;
4775         }
4776         if ($in_ac_replace)
4777         {
4778             $in_ac_replace = 0 if s/[\]\)].*$//;
4779             # Remove trailing backslash.
4780             s/\\$//;
4781             foreach (split)
4782             {
4783                 # Need to skip empty elements for Perl 4.
4784                 next if $_ eq '';
4785                 $libsources{$_ . '.c'} = $here;
4786             }
4787         }
4789         if (/$obsolete_rx/o)
4790         {
4791             my $hint = '';
4792             if ($obsolete_macros{$1} ne '')
4793             {
4794                 $hint = '; ' . $obsolete_macros{$1};
4795             }
4796             file_error ($here, "`$1' is obsolete$hint");
4797         }
4799         # Process the AC_OUTPUT and AC_CONFIG_FILES macros.
4800         if (! $in_ac_output && s/(AC_(OUTPUT|CONFIG_FILES))\s*\(\[?//)
4801         {
4802             $in_ac_output = $1;
4803             $ac_config_files_location = $here;
4804         }
4805         if ($in_ac_output)
4806         {
4807             my $closing = 0;
4808             if (s/[\]\),].*$//)
4809             {
4810                 $in_ac_output = 0;
4811                 $closing = 1;
4812             }
4814             # Look at potential Makefile.am's.
4815             &scan_autoconf_config_files ($_);
4817             if ($closing
4818                 && scalar keys %make_list == 0
4819                 && @other_input_files == 0)
4820             {
4821                 file_error ($ac_config_files_location,
4822                             "no files mentioned in `$in_ac_output'");
4823                 exit 1;
4824             }
4825         }
4827         if (/$AC_CONFIG_AUX_DIR_PATTERN/o)
4828         {
4829             @config_aux_path = &unquote_m4_arg ($1);
4830             $config_aux_dir_set_in_configure_in = $here;
4831         }
4833         # Check for ansi2knr.
4834         $am_c_prototypes = $here if /AM_C_PROTOTYPES/;
4836         # Check for `-c -o' code.
4837         $seen_cc_c_o = $here if /AM_PROG_CC_C_O/;
4839         # Check for NLS support.
4840         if (/AM_GNU_GETTEXT/)
4841         {
4842             $seen_gettext = $here;
4843             $ac_gettext_location = $here;
4844         }
4846         # Handle configuration headers.  A config header of `[$1]'
4847         # means we are actually scanning AM_CONFIG_HEADER from
4848         # aclocal.m4.  Same thing with a leading underscore.
4849         if (/(?<!_)A([CM])_CONFIG_HEADERS?\s*\((.*)\)/
4850             && $2 ne '[$1]')
4851         {
4852             file_error ($here,
4853                "`automake requires `AM_CONFIG_HEADER', not `AC_CONFIG_HEADER'")
4854               if $1 eq 'C';
4856             $config_header_location = $here;
4857             push @config_headers, split (' ', unquote_m4_arg ($2));
4858         }
4860         # Handle AC_CANONICAL_*.  Always allow upgrading to
4861         # AC_CANONICAL_SYSTEM, but never downgrading.
4862         if (/AC_CANONICAL_HOST/ || /AC_CYGWIN/ || /AC_EMXOS2/ || /AC_MINGW32/)
4863           {
4864             if (! $seen_canonical)
4865               {
4866                 $seen_canonical = AC_CANONICAL_HOST;
4867                 $canonical_location = $here;
4868               }
4869           }
4870         if (/AC_CANONICAL_SYSTEM/)
4871           {
4872             $seen_canonical = AC_CANONICAL_SYSTEM;
4873             $canonical_location = $here;
4874           }
4876         # If using X, include some extra variable definitions.  NOTE
4877         # we don't want to force these into CFLAGS or anything,
4878         # because not all programs will necessarily use X.
4879         if (/AC_PATH_XTRA/)
4880           {
4881             foreach my $var (qw(X_CFLAGS X_LIBS X_EXTRA_LIBS X_PRE_LIBS))
4882               {
4883                 $configure_vars{$var} = $here;
4884               }
4885           }
4887         # AM_INIT_AUTOMAKE with any number of argument
4888         if (/AM_INIT_AUTOMAKE/)
4889         {
4890             $seen_init_automake = $here;
4891         }
4893         # AC_INIT or AM_INIT_AUTOMAKE with two arguments
4894         if (/$AC_INIT_PATTERN/o || /$AM_INIT_AUTOMAKE_PATTERN/o)
4895         {
4896             if ($1 =~ /$AM_PACKAGE_VERSION_PATTERN/o)
4897             {
4898                 $package_version = $1;
4899                 $package_version_location = $here;
4900             }
4901         }
4903         # AM_INIT_AUTOMAKE with one argument.
4904         if (/AM_INIT_AUTOMAKE\(([^),]+)\)/)
4905         {
4906             $global_options = &unquote_m4_arg ($1);
4907         }
4909         if (/AM_AUTOMAKE_VERSION\(([^)]+)\)/)
4910         {
4911             my $vers = &unquote_m4_arg ($1);
4912             file_error ($here,
4913                         "version mismatch.  This is Automake $VERSION, " .
4914                         "but $filename\nwas generated for Automake $vers.  " .
4915                         "You should recreate\n$filename with aclocal and " .
4916                         "run automake again.\n")
4917                     if ($VERSION ne $vers);
4919             $seen_automake_version = 1;
4920         }
4922         if (/AM_PROG_LEX/)
4923         {
4924             $configure_vars{'LEX'} = $here;
4925             $configure_vars{'LEX_OUTPUT_ROOT'} = $here;
4926             $configure_vars{'LEXLIB'} = $here;
4927             $seen_prog_lex = $here;
4928         }
4929         if (/AC_PROG_LEX/ && $filename =~ /configure\.(ac|in)$/)
4930         {
4931             $configure_vars{'LEX'} = $here;
4932             $configure_vars{'LEX_OUTPUT_ROOT'} = $here;
4933             $configure_vars{'LEXLIB'} = $here;
4934             $seen_prog_lex = $here;
4935             file_warning ($here,
4936                    "automake requires `AM_PROG_LEX', not `AC_PROG_LEX'");
4937         }
4939         if (/AC_PROG_(F77|YACC|RANLIB|CC|CXXCPP|CXX|LEX|AWK|CPP|LN_S)/)
4940         {
4941             $configure_vars{$1} = $here;
4942         }
4943         if (/$AC_CHECK_PATTERN/o)
4944         {
4945             $configure_vars{$3} = $here;
4946         }
4947         if (/$AM_MISSING_PATTERN/o
4948             && $1 ne 'ACLOCAL'
4949             && $1 ne 'AUTOCONF'
4950             && $1 ne 'AUTOMAKE'
4951             && $1 ne 'AUTOHEADER'
4952             # AM_INIT_AUTOMAKE is AM_MISSING_PROG'ing MAKEINFO.  But
4953             # we handle it elsewhere.
4954             && $1 ne 'MAKEINFO')
4955         {
4956             $configure_vars{$1} = $here;
4957         }
4959         # Explicitly avoid ANSI2KNR -- we AC_SUBST that in protos.m4,
4960         # but later define it elsewhere.  This is pretty hacky.  We
4961         # also explicitly avoid INSTALL_SCRIPT and some other
4962         # variables because they are defined in header-vars.am.
4963         # AMDEPBACKSLASH might be subst'd by `\', which certainly would
4964         # not be appreciated by Make.
4965         if (/$AC_SUBST_PATTERN/o
4966             && $1 ne 'ANSI2KNR'
4967             && $1 ne 'INSTALL_SCRIPT'
4968             && $1 ne 'INSTALL_DATA'
4969             && $1 ne 'AMDEPBACKSLASH')
4970         {
4971             $configure_vars{$1} = $here;
4972         }
4974         if (/AM_MAINTAINER_MODE/)
4975         {
4976             $seen_maint_mode = $here;
4977             $configure_cond{'MAINTAINER_MODE'} = $here;
4978         }
4980         $am_lispdir_location = $here if /AM_PATH_LISPDIR/;
4982         if (/AM_PATH_PYTHON/)
4983           {
4984             $pythondir_location = $here;
4985             $configure_vars{'pythondir'} = $here;
4986             $configure_vars{'PYTHON'} = $here;
4987           }
4989         if (/A(C|M)_PROG_LIBTOOL/)
4990         {
4991             # We're not ready for this yet.  People still use a
4992             # libtool with no AC_PROG_LIBTOOL.  Once that is the
4993             # dominant version we can reenable this code -- but next
4994             # time by mentioning the macro in %obsolete_macros, both
4995             # here and in aclocal.in.
4997             # if (/AM_PROG_LIBTOOL/)
4998             # {
4999             #   file_warning ($here, "`AM_PROG_LIBTOOL' is obsolete, use `AC_PROG_LIBTOOL' instead");
5000             # }
5001             $seen_libtool = $here;
5002             $configure_vars{'LIBTOOL'} = $here;
5003             $configure_vars{'RANLIB'} = $here;
5004             $configure_vars{'CC'} = $here;
5005             # AC_PROG_LIBTOOL runs AC_CANONICAL_HOST.  Make sure we
5006             # never downgrade (if we've seen AC_CANONICAL_SYSTEM).
5007             $seen_canonical = AC_CANONICAL_HOST if ! $seen_canonical;
5008         }
5010         $seen_multilib = $here if (/AM_ENABLE_MULTILIB/);
5012         if (/$AM_CONDITIONAL_PATTERN/o)
5013         {
5014             $configure_cond{$1} = $here;
5015         }
5017         # Check for Fortran 77 intrinsic and run-time libraries.
5018         if (/AC_F77_LIBRARY_LDFLAGS/)
5019         {
5020             $configure_vars{'FLIBS'} = $here;
5021         }
5022     }
5026 # &scan_autoconf_files ()
5027 # -----------------------
5028 # Check whether we use `configure.ac' or `configure.in'.
5029 # Scan it (and possibly `aclocal.m4') for interesting things.
5030 # We must scan aclocal.m4 because there might be AC_SUBSTs and such there.
5031 sub scan_autoconf_files
5033     # Reinitialize libsources here.  This isn't really necessary,
5034     # since we currently assume there is only one configure.ac.  But
5035     # that won't always be the case.
5036     %libsources = ();
5038     $configure_ac = find_configure_ac;
5039     die "$me: `configure.ac' or `configure.in' is required\n"
5040         if !$configure_ac;
5042     if (defined $ENV{'amtraces'})
5043     {
5044         print STDERR "$me: Autoconf traces is an experimental feature\n";
5045         print STDERR "$me: use at your own risks\n";
5047         scan_autoconf_traces ($configure_ac);
5048     }
5049     else
5050       {
5051         scan_one_autoconf_file ($configure_ac);
5052         scan_one_autoconf_file ('aclocal.m4')
5053           if -f 'aclocal.m4';
5054       }
5056     # Set input and output files if not specified by user.
5057     if (! @input_files)
5058     {
5059         @input_files = sort keys %make_list;
5060         %output_files = %make_list;
5061     }
5063     @configure_input_files = sort keys %make_list;
5065     conf_error ("`AM_INIT_AUTOMAKE' must be used")
5066         if ! $seen_init_automake;
5068     if (! $seen_automake_version)
5069     {
5070         if (-f 'aclocal.m4')
5071         {
5072             file_error ($seen_init_automake || $me,
5073                         "your implementation of AM_INIT_AUTOMAKE comes from " .
5074                         "an\nold Automake version.  You should recreate " .
5075                         "aclocal.m4\nwith aclocal and run automake again.\n");
5076         }
5077         else
5078         {
5079             file_error ($seen_init_automake || $me,
5080                         "no proper implementation of AM_INIT_AUTOMAKE was " .
5081                         "found,\nprobably because aclocal.m4 is missing...\n" .
5082                         "You should run aclocal to create this file, then\n" .
5083                         "run automake again.\n");
5084         }
5085     }
5087     # Look for some files we need.  Always check for these.  This
5088     # check must be done for every run, even those where we are only
5089     # looking at a subdir Makefile.  We must set relative_dir so that
5090     # the file-finding machinery works.
5091     # FIXME: Is this broken because it needs dynamic scopes.
5092     # My tests seems to show it's not the case.
5093     $relative_dir = '.';
5094     require_conf_file ($configure_ac, FOREIGN,
5095                        'install-sh', 'mkinstalldirs', 'missing');
5096     am_error ("`install.sh' is an anachronism; use `install-sh' instead")
5097         if -f $config_aux_path[0] . '/install.sh';
5099     require_conf_file ($pythondir_location, FOREIGN, 'py-compile')
5100       if $pythondir_location;
5102     # Preserve dist_common for later.
5103     $configure_dist_common = variable_value ('DIST_COMMON', 'TRUE') || '';
5106 ################################################################
5108 # Set up for Cygnus mode.
5109 sub check_cygnus
5111     return unless $cygnus_mode;
5113     &set_strictness ('foreign');
5114     $options{'no-installinfo'} = 1;
5115     $options{'no-dependencies'} = 1;
5116     $use_dependencies = 0;
5118     conf_error ("`AM_MAINTAINER_MODE' required when --cygnus specified")
5119       if !$seen_maint_mode;
5122 # Do any extra checking for GNU standards.
5123 sub check_gnu_standards
5125     if ($relative_dir eq '.')
5126     {
5127         # In top level (or only) directory.
5128         require_file ("$am_file.am", GNU,
5129                       qw(INSTALL NEWS README COPYING AUTHORS ChangeLog));
5130     }
5132     if ($strictness >= GNU
5133         && defined $options{'no-installman'})
5134     {
5135         macro_error ('AUTOMAKE_OPTIONS',
5136                      "option `no-installman' disallowed by GNU standards");
5137     }
5139     if ($strictness >= GNU
5140         && defined $options{'no-installinfo'})
5141     {
5142         macro_error ('AUTOMAKE_OPTIONS',
5143                      "option `no-installinfo' disallowed by GNU standards");
5144     }
5147 # Do any extra checking for GNITS standards.
5148 sub check_gnits_standards
5150     if ($relative_dir eq '.')
5151     {
5152         # In top level (or only) directory.
5153         require_file ("$am_file.am", GNITS, 'THANKS');
5154     }
5157 ################################################################
5159 # Functions to handle files of each language.
5161 # Each `lang_X_rewrite($DIRECTORY, $BASE, $EXT)' function follows a
5162 # simple formula: Return value is $LANG_SUBDIR if the resulting object
5163 # file should be in a subdir if the source file is, $LANG_PROCESS if
5164 # file is to be dealt with, $LANG_IGNORE otherwise.
5166 # Much of the actual processing is handled in
5167 # handle_single_transform_list.  These functions exist so that
5168 # auxiliary information can be recorded for a later cleanup pass.
5169 # Note that the calls to these functions are computed, so don't bother
5170 # searching for their precise names in the source.
5172 # This is just a convenience function that can be used to determine
5173 # when a subdir object should be used.
5174 sub lang_sub_obj
5176     return defined $options{'subdir-objects'} ? $LANG_SUBDIR : $LANG_PROCESS;
5179 # Rewrite a single C source file.
5180 sub lang_c_rewrite
5182     my ($directory, $base, $ext) = @_;
5184     if (defined $options{'ansi2knr'} && $base =~ /_$/)
5185     {
5186         # FIXME: include line number in error.
5187         am_error ("C source file `$base.c' would be deleted by ansi2knr rules");
5188     }
5190     my $r = $LANG_PROCESS;
5191     if (defined $options{'subdir-objects'})
5192     {
5193         $r = $LANG_SUBDIR;
5194         $base = $directory . '/' . $base
5195             unless $directory eq '.' || $directory eq '';
5197         if (! $seen_cc_c_o)
5198         {
5199             # Only give error once.
5200             $seen_cc_c_o = 1;
5201             # FIXME: line number.
5202             am_error ("C objects in subdir but `AM_PROG_CC_C_O' not in `$configure_ac'");
5203         }
5205         require_conf_file ("$am_file.am", FOREIGN, 'compile');
5207         # In this case we already have the directory information, so
5208         # don't add it again.
5209         $de_ansi_files{$base} = '';
5210     }
5211     else
5212     {
5213         $de_ansi_files{$base} = (($directory eq '.' || $directory eq '')
5214                                  ? ''
5215                                  : "$directory/");
5216     }
5218     return $r;
5221 # Rewrite a single C++ source file.
5222 sub lang_cxx_rewrite
5224     return &lang_sub_obj;
5227 # Rewrite a single header file.
5228 sub lang_header_rewrite
5230     # Header files are simply ignored.
5231     return $LANG_IGNORE;
5234 # Rewrite a single yacc file.
5235 sub lang_yacc_rewrite
5237     my ($directory, $base, $ext) = @_;
5239     my $r = &lang_sub_obj;
5240     (my $newext = $ext) =~ tr/y/c/;
5241     return ($r, $newext);
5244 # Rewrite a single yacc++ file.
5245 sub lang_yaccxx_rewrite
5247     my ($directory, $base, $ext) = @_;
5249     my $r = &lang_sub_obj;
5250     (my $newext = $ext) =~ tr/y/c/;
5251     return ($r, $newext);
5254 # Rewrite a single lex file.
5255 sub lang_lex_rewrite
5257     my ($directory, $base, $ext) = @_;
5259     my $r = &lang_sub_obj;
5260     (my $newext = $ext) =~ tr/l/c/;
5261     return ($r, $newext);
5264 # Rewrite a single lex++ file.
5265 sub lang_lexxx_rewrite
5267     my ($directory, $base, $ext) = @_;
5269     my $r = &lang_sub_obj;
5270     (my $newext = $ext) =~ tr/l/c/;
5271     return ($r, $newext);
5274 # Rewrite a single assembly file.
5275 sub lang_asm_rewrite
5277     return &lang_sub_obj;
5280 # Rewrite a single Fortran 77 file.
5281 sub lang_f77_rewrite
5283     return $LANG_PROCESS;
5286 # Rewrite a single preprocessed Fortran 77 file.
5287 sub lang_ppf77_rewrite
5289     return $LANG_PROCESS;
5292 # Rewrite a single ratfor file.
5293 sub lang_ratfor_rewrite
5295     return $LANG_PROCESS;
5298 # Rewrite a single Objective C file.
5299 sub lang_objc_rewrite
5301     return &lang_sub_obj;
5304 # Rewrite a single Java file.
5305 sub lang_java_rewrite
5307     return $LANG_SUBDIR;
5310 # The lang_X_finish functions are called after all source file
5311 # processing is done.  Each should handle defining rules for the
5312 # language, etc.  A finish function is only called if a source file of
5313 # the appropriate type has been seen.
5315 sub lang_c_finish
5317     # Push all libobjs files onto de_ansi_files.  We actually only
5318     # push files which exist in the current directory, and which are
5319     # genuine source files.
5320     foreach my $file (keys %libsources)
5321     {
5322         if ($file =~ /^(.*)\.[cly]$/ && -f "$relative_dir/$file")
5323         {
5324             $de_ansi_files{$1} = (($relative_dir eq '.' || $relative_dir eq '')
5325                                   ? ''
5326                                   : "$relative_dir/");
5327         }
5328     }
5330     if (defined $options{'ansi2knr'} && keys %de_ansi_files)
5331     {
5332         # Make all _.c files depend on their corresponding .c files.
5333         my @objects;
5334         foreach my $base (sort keys %de_ansi_files)
5335         {
5336             # Each _.c file must depend on ansi2knr; otherwise it
5337             # might be used in a parallel build before it is built.
5338             # We need to support files in the srcdir and in the build
5339             # dir (because these files might be auto-generated.  But
5340             # we can't use $< -- some makes only define $< during a
5341             # suffix rule.
5342             my $ansfile = $de_ansi_files{$base} . $base . '.c';
5343             $output_rules .= ($base . "_.c: $ansfile \$(ANSI2KNR)\n\t"
5344                               . '$(CPP) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) '
5345                               . '`if test -f $(srcdir)/' . $ansfile
5346                               . '; then echo $(srcdir)/' . $ansfile
5347                               . '; else echo ' . $ansfile . '; fi` '
5348                               . "| sed 's/^# \\([0-9]\\)/#line \\1/' "
5349                               . '| $(ANSI2KNR) > ' . $base . "_.c"
5350                               # If ansi2knr fails then we shouldn't
5351                               # create the _.c file
5352                               . " || rm -f ${base}_.c\n");
5353             push (@objects, $base . '_.$(OBJEXT)');
5354             push (@objects, $base . '_.lo')
5355               if $seen_libtool;
5356         }
5358         # Make all _.o (and _.lo) files depend on ansi2knr.
5359         # Use a sneaky little hack to make it print nicely.
5360         &pretty_print_rule ('', '', @objects, ':', '$(ANSI2KNR)');
5361     }
5364 # This is a yacc helper which is called whenever we have decided to
5365 # compile a yacc file.
5366 sub lang_yacc_target_hook
5368     my ($self, $aggregate, $output, $input) = @_;
5370     my $flag = $aggregate . "_YFLAGS";
5371     if ((variable_defined ($flag)
5372          && &variable_value ($flag) =~ /$DASH_D_PATTERN/o)
5373         || (variable_defined ('YFLAGS')
5374             && &variable_value ('YFLAGS') =~ /$DASH_D_PATTERN/o))
5375     {
5376         (my $output_base = $output) =~ s/$KNOWN_EXTENSIONS_PATTERN$//;
5377         my $header = $output_base . '.h';
5379         # Found a `-d' that applies to the compilation of this file.
5380         # Add a dependency for the generated header file, and arrange
5381         # for that file to be included in the distribution.
5382         # FIXME: this fails for `nodist_*_SOURCES'.
5383         $output_rules .= "${header}: $output\n";
5384         &push_dist_common ($header);
5385         # If the files are built in the build directory, then we want
5386         # to remove them with `make clean'.  If they are in srcdir
5387         # they shouldn't be touched.  However, we can't determine this
5388         # statically, and the GNU rules say that yacc/lex output files
5389         # should be removed by maintainer-clean.  So that's what we
5390         # do.
5391         push (@maintainer_clean_files, $header);
5392     }
5395 # This is a helper for both lex and yacc.
5396 sub yacc_lex_finish_helper
5398     return if defined $language_scratch{'lex-yacc-done'};
5399     $language_scratch{'lex-yacc-done'} = 1;
5401     # If there is more than one distinct yacc (resp lex) source file
5402     # in a given directory, then the `ylwrap' program is required to
5403     # allow parallel builds to work correctly.  FIXME: for now, no
5404     # line number.
5405     require_conf_file ($configure_ac, FOREIGN, 'ylwrap');
5406     if ($config_aux_dir_set_in_configure_in)
5407     {
5408         &define_variable ('YLWRAP', $config_aux_dir . "/ylwrap");
5409     }
5410     else
5411     {
5412         &define_variable ('YLWRAP', '$(top_srcdir)/ylwrap');
5413     }
5416 sub lang_yacc_finish
5418     return if defined $language_scratch{'yacc-done'};
5419     $language_scratch{'yacc-done'} = 1;
5421     macro_error ('YACCFLAGS',
5422                  "`YACCFLAGS' obsolete; use `YFLAGS' instead")
5423       if variable_defined ('YACCFLAGS');
5425     if (count_files_for_language ('yacc') > 1)
5426     {
5427         &yacc_lex_finish_helper;
5428     }
5432 sub lang_lex_finish
5434     return if defined $language_scratch{'lex-done'};
5435     $language_scratch{'lex-done'} = 1;
5437     am_error ("lex source seen but `AM_PROG_LEX' not in `$configure_ac'")
5438       unless $seen_prog_lex;
5440     if (count_files_for_language ('lex') > 1)
5441     {
5442         &yacc_lex_finish_helper;
5443     }
5447 # Given a hash table of linker names, pick the name that has the most
5448 # precedence.  This is lame, but something has to have global
5449 # knowledge in order to eliminate the conflict.  Add more linkers as
5450 # required.
5451 sub resolve_linker
5453     my (%linkers) = @_;
5455     foreach my $l (qw(GCJLINK CXXLINK F77LINK OBJCLINK))
5456     {
5457         return $l if defined $linkers{$l};
5458     }
5459     return 'LINK';
5462 # Called to indicate that an extension was used.
5463 sub saw_extension
5465     my ($ext) = @_;
5466     if (! defined $extension_seen{$ext})
5467     {
5468         $extension_seen{$ext} = 1;
5469     }
5470     else
5471     {
5472         ++$extension_seen{$ext};
5473     }
5476 # Return the number of files seen for a given language.  Knows about
5477 # special cases we care about.  FIXME: this is hideous.  We need
5478 # something that involves real language objects.  For instance yacc
5479 # and yaccxx could both derive from a common yacc class which would
5480 # know about the strange ylwrap requirement.  (Or better yet we could
5481 # just not support legacy yacc!)
5482 sub count_files_for_language
5484     my ($name) = @_;
5486     my @names;
5487     if ($name eq 'yacc' || $name eq 'yaccxx')
5488     {
5489         @names = ('yacc', 'yaccxx');
5490     }
5491     elsif ($name eq 'lex' || $name eq 'lexxx')
5492     {
5493         @names = ('lex', 'lexxx');
5494     }
5495     else
5496     {
5497         @names = ($name);
5498     }
5500     my $r = 0;
5501     foreach $name (@names)
5502     {
5503         my $lang = $languages{$name};
5504         foreach my $ext (@{$lang->extensions})
5505         {
5506             $r += $extension_seen{$ext}
5507                 if defined $extension_seen{$ext};
5508         }
5509     }
5511     return $r
5514 # Called to ask whether source files have been seen . If HEADERS is 1,
5515 # headers can be included.
5516 sub saw_sources_p
5518     my ($headers) = @_;
5520     # count all the sources
5521     my $count = 0;
5522     foreach my $val (values %extension_seen)
5523     {
5524         $count += $val;
5525     }
5527     if (!$headers)
5528     {
5529         $count -= count_files_for_language ('header');
5530     }
5532     return $count > 0;
5536 # register_language (%ATTRIBUTE)
5537 # ------------------------------
5538 # Register a single language.
5539 # Each %ATTRIBUTE is of the form ATTRIBUTE => VALUE.
5540 sub register_language (%)
5542     my (%option) = @_;
5544     # Set the defaults.
5545     $option{'ansi'} = 0
5546       unless defined $option{'ansi'};
5547     $option{'autodep'} = 'no'
5548       unless defined $option{'autodep'};
5549     $option{'linker'} = ''
5550       unless defined $option{'linker'};
5551     $option{'define_flag'} = 1
5552       unless defined $option{'define_flag'};
5554     my $lang = new Language (%option);
5556     # Fill indexes.
5557     grep ($extension_map{$_} = $lang->name, @{$lang->extensions});
5558     $languages{$lang->name} = $lang;
5560     # Update the pattern of known extensions.
5561     accept_extensions (@{$lang->extensions});
5564 # derive_suffix ($EXT, $OBJ)
5565 # --------------------------
5566 # This function is used to find a path from a user-specified suffix $EXT
5567 # to $OBJ or to some other suffix we recognize internally, eg `cc'.
5568 sub derive_suffix ($$)
5570     my ($source_ext, $obj) = @_;
5572     while (! $extension_map{$source_ext}
5573            && $source_ext ne $obj
5574            && defined $suffix_rules{$source_ext})
5575     {
5576         $source_ext = $suffix_rules{$source_ext};
5577     }
5579     return $source_ext;
5583 ################################################################
5585 # Pretty-print something.  HEAD is what should be printed at the
5586 # beginning of the first line, FILL is what should be printed at the
5587 # beginning of every subsequent line.
5588 sub pretty_print_internal
5590     my ($head, $fill, @values) = @_;
5592     my $column = length ($head);
5593     my $result = $head;
5595     # Fill length is number of characters.  However, each Tab
5596     # character counts for eight.  So we count the number of Tabs and
5597     # multiply by 7.
5598     my $fill_length = length ($fill);
5599     $fill_length += 7 * ($fill =~ tr/\t/\t/d);
5601     foreach (@values)
5602     {
5603         # "71" because we also print a space.
5604         if ($column + length ($_) > 71)
5605         {
5606             $result .= " \\\n" . $fill;
5607             $column = $fill_length;
5608         }
5609         $result .= ' ' if $result =~ /\S\z/;
5610         $result .= $_;
5611         $column += length ($_) + 1;
5612     }
5614     $result .= "\n";
5615     return $result;
5618 # Pretty-print something and append to output_vars.
5619 sub pretty_print
5621     $output_vars .= &pretty_print_internal (@_);
5624 # Pretty-print something and append to output_rules.
5625 sub pretty_print_rule
5627     $output_rules .= &pretty_print_internal (@_);
5631 ################################################################
5634 # $STRING
5635 # &conditional_string(@COND-STACK)
5636 # --------------------------------
5637 # Build a string which denotes the conditional in @COND-STACK.  Some
5638 # simplifications are done: `TRUE' entries are elided, and any `FALSE'
5639 # entry results in a return of `FALSE'.
5640 sub conditional_string
5642   my (@stack) = @_;
5644   if (grep (/^FALSE$/, @stack))
5645     {
5646       return 'FALSE';
5647     }
5648   else
5649     {
5650       return join (' ', uniq sort grep (!/^TRUE$/, @stack));
5651     }
5655 # $BOOLEAN
5656 # &conditional_true_when ($COND, $WHEN)
5657 # -------------------------------------
5658 # See if a conditional is true.  Both arguments are conditional
5659 # strings.  This returns true if the first conditional is true when
5660 # the second conditional is true.
5661 # For instance with $COND = `BAR FOO', and $WHEN = `BAR BAZ FOO',
5662 # obviously return 1, and 0 when, for instance, $WHEN = `FOO'.
5663 sub conditional_true_when ($$)
5665     my ($cond, $when) = @_;
5667     # Make a hash holding all the values from $WHEN.
5668     my %cond_vals = map { $_ => 1 } split (' ', $when);
5670     # Check each component of $cond, which looks `COND1 COND2'.
5671     foreach my $comp (split (' ', $cond))
5672     {
5673         # TRUE is always true.
5674         next if $comp eq 'TRUE';
5675         return 0 if ! defined $cond_vals{$comp};
5676     }
5678     return 1;
5682 # $BOOLEAN
5683 # &conditional_is_redundant ($COND, @WHENS)
5684 # ----------------------------------------
5685 # Determine whether $COND is redundant with respect to @WHENS.
5687 # Returns true if $COND is true for any of the conditions in @WHENS.
5689 # If there are no @WHENS, then behave as if @WHENS contained a single empty
5690 # condition.
5691 sub conditional_is_redundant ($@)
5693     my ($cond, @whens) = @_;
5695     if (@whens == 0)
5696     {
5697         return 1 if conditional_true_when ($cond, "");
5698     }
5699     else
5700     {
5701         foreach my $when (@whens)
5702         {
5703             return 1 if conditional_true_when ($cond, $when);
5704         }
5705     }
5707     return 0;
5711 # $NEGATION
5712 # condition_negate ($COND)
5713 # ------------------------
5714 sub condition_negate ($)
5716     my ($cond) = @_;
5718     $cond =~ s/TRUE$/TRUEO/;
5719     $cond =~ s/FALSE$/TRUE/;
5720     $cond =~ s/TRUEO$/FALSE/;
5722     return $cond;
5726 # Compare condition names.
5727 # Issue them in alphabetical order, foo_TRUE before foo_FALSE.
5728 sub by_condition
5730     # Be careful we might be comparing `' or `#'.
5731     $a =~ /^(.*)_(TRUE|FALSE)$/;
5732     my ($aname, $abool) = ($1 || '', $2 || '');
5733     $b =~ /^(.*)_(TRUE|FALSE)$/;
5734     my ($bname, $bbool) = ($1 || '', $2 || '');
5735     return ($aname cmp $bname
5736             # Don't bother with IFs, given that TRUE is after FALSE
5737             # just cmp in the reverse order.
5738             || $bbool cmp $abool
5739             # Just in case...
5740             || $a cmp $b);
5744 # &make_condition (@CONDITIONS)
5745 # -----------------------------
5746 # Transform a list of conditions (themselves can be an internal list
5747 # of conditions, e.g., @CONDITIONS = ('cond1 cond2', 'cond3')) into a
5748 # Make conditional (a pattern for AC_SUBST).
5749 # Correctly returns the empty string when there are no conditions.
5750 sub make_condition
5752     my $res = conditional_string (@_);
5754     # There are no conditions.
5755     if ($res eq '')
5756       {
5757         # Nothing to do.
5758       }
5759     # It's impossible.
5760     elsif ($res eq 'FALSE')
5761       {
5762         $res = '#';
5763       }
5764     # Build it.
5765     else
5766       {
5767         $res = '@' . $res . '@';
5768         $res =~ s/ /@@/g;
5769       }
5771     return $res;
5776 ## ------------------------------ ##
5777 ## Handling the condition stack.  ##
5778 ## ------------------------------ ##
5781 # $COND_STRING
5782 # cond_stack_if ($NEGATE, $COND, $WHERE)
5783 # --------------------------------------
5784 sub cond_stack_if ($$$)
5786   my ($negate, $cond, $where) = @_;
5788   file_error ($where, "$cond does not appear in AM_CONDITIONAL")
5789     if ! $configure_cond{$cond} && $cond !~ /^TRUE|FALSE$/;
5791   $cond = "${cond}_TRUE"
5792     unless $cond =~ /^TRUE|FALSE$/;
5793   $cond = condition_negate ($cond)
5794     if $negate;
5796   push (@cond_stack, $cond);
5798   return conditional_string (@cond_stack);
5802 # $COND_STRING
5803 # cond_stack_else ($NEGATE, $COND, $WHERE)
5804 # ----------------------------------------
5805 sub cond_stack_else ($$$)
5807   my ($negate, $cond, $where) = @_;
5809   if (! @cond_stack)
5810     {
5811       file_error ($where, "else without if");
5812       return;
5813     }
5815   $cond_stack[$#cond_stack] = condition_negate ($cond_stack[$#cond_stack]);
5817   # If $COND is given, check against it.
5818   if (defined $cond)
5819     {
5820       $cond = "${cond}_TRUE"
5821         unless $cond =~ /^TRUE|FALSE$/;
5822       $cond = condition_negate ($cond)
5823         if $negate;
5825       file_error ($where,
5826                   "else reminder ($negate$cond) incompatible with "
5827                   . "current conditional: $cond_stack[$#cond_stack]")
5828         if $cond_stack[$#cond_stack] ne $cond;
5829     }
5831   return conditional_string (@cond_stack);
5835 # $COND_STRING
5836 # cond_stack_endif ($NEGATE, $COND, $WHERE)
5837 # -----------------------------------------
5838 sub cond_stack_endif ($$$)
5840   my ($negate, $cond, $where) = @_;
5841   my $old_cond;
5843   if (! @cond_stack)
5844     {
5845       file_error ($where, "endif without if: $negate$cond");
5846       return;
5847     }
5850   # If $COND is given, check against it.
5851   if (defined $cond)
5852     {
5853       $cond = "${cond}_TRUE"
5854         unless $cond =~ /^TRUE|FALSE$/;
5855       $cond = condition_negate ($cond)
5856         if $negate;
5858       file_error ($where,
5859                   "endif reminder ($negate$cond) incompatible with "
5860                   . "current conditional: $cond_stack[$#cond_stack]")
5861         if $cond_stack[$#cond_stack] ne $cond;
5862     }
5864   pop @cond_stack;
5866   return conditional_string (@cond_stack);
5873 ## ------------------------ ##
5874 ## Handling the variables.  ##
5875 ## ------------------------ ##
5878 # check_ambiguous_conditional ($VAR, $COND)
5879 # -----------------------------------------
5880 # Check for an ambiguous conditional.  This is called when a variable
5881 # is being defined conditionally.  If we already know about a
5882 # definition that is true under the same conditions, then we have an
5883 # ambiguity.
5884 sub check_ambiguous_conditional ($$)
5886     my ($var, $cond) = @_;
5887     my $message = conditional_ambiguous_p ($var, $cond);
5888     if ($message ne '')
5889     {
5890         macro_error ($var, $message);
5891         macro_dump ($var);
5892     }
5895 # $STRING
5896 # conditional_ambiguous_p ($VAR, $COND)
5897 # -------------------------------------
5898 # Check for an ambiguous conditional.  Return an error message if we
5899 # have one, the empty string otherwise.
5900 sub conditional_ambiguous_p ($$)
5902     my ($var, $cond) = @_;
5903     foreach my $vcond (keys %{$var_value{$var}})
5904     {
5905        my $message;
5906        if ($vcond eq $cond)
5907        {
5908            return "$var multiply defined in condition $cond";
5909        }
5910        elsif (&conditional_true_when ($vcond, $cond))
5911        {
5912          return ("$var was already defined in condition $vcond, "
5913                  . "which implies condition $cond");
5914        }
5915        elsif (&conditional_true_when ($cond, $vcond))
5916        {
5917            return ("$var was already defined in condition $vcond, "
5918                    . "which is implied by condition $cond");
5919        }
5920    }
5922     return '';
5926 # &macro_define($VAR, $VAR_IS_AM, $TYPE, $COND, $VALUE, $WHERE)
5927 # -------------------------------------------------------------
5928 # The $VAR can go from Automake to user, but not the converse.
5929 sub macro_define ($$$$$$)
5931   my ($var, $var_is_am, $type, $cond, $value, $where) = @_;
5933   file_error ($where, "bad macro name `$var'")
5934     if $var !~ /$MACRO_PATTERN/o;
5936   $cond ||= 'TRUE';
5938   # An Automake variable must be consistently defined with the same
5939   # sign by Automake.  A user variable must be set by either `=' or
5940   # `:=', and later promoted to `+='.
5941   if ($var_is_am)
5942     {
5943       if (defined $var_type{$var} && $var_type{$var} ne $type)
5944         {
5945           file_error ($where,
5946                       ("$var was set with `$var_type{$var}=' "
5947                        . "and is now set with `$type='"));
5948         }
5949     }
5950   else
5951     {
5952       if (!defined $var_type{$var} && $type eq '+')
5953         {
5954           file_error ($where, "$var must be set with `=' before using `+='");
5955         }
5956     }
5957   $var_type{$var} = $type;
5959   # When adding, since we rewrite, don't try to preserve the
5960   # Automake continuation backslashes.
5961   $value =~ s/\\$//mg
5962     if $type eq '+' && $var_is_am;
5964   # Differentiate the first assignment (including with `+=').
5965   if ($type eq '+' && defined $var_value{$var}{$cond})
5966     {
5967       if (chomp $var_value{$var}{$cond})
5968         {
5969           # Insert a backslash before a trailing newline.
5970           $var_value{$var}{$cond} .= "\\\n";
5971         }
5972       elsif ($var_value{$var}{$cond})
5973         {
5974           # Insert a separator.
5975           $var_value{$var}{$cond} .= ' ';
5976         }
5977        $var_value{$var}{$cond} .= $value;
5978     }
5979   else
5980     {
5981       # The first assignment to a macro sets its location.  Ideally I
5982       # suppose we would associate line numbers with random bits of text.
5983       # FIXME: We sometimes redefine some variables, but we want to keep
5984       # the original location.  More subs are needed to handle
5985       # properly variables.  Once this done, remove this hack.
5986       $var_location{$var} = $where
5987         unless defined $var_location{$var};
5989       # If Automake tries to override a value specified by the user,
5990       # just don't let it do.
5991       if (defined $var_value{$var}{$cond} && !$var_is_am{$var} && $var_is_am)
5992         {
5993           if ($verbose)
5994             {
5995               print STDERR "$me: refusing to override the user definition of:\n";
5996               macro_dump ($var);
5997               print STDERR "$me: with `$cond' => `$value'\n";
5998             }
5999         }
6000       else
6001         {
6002           # There must be no previous value unless the user is redefining
6003           # an Automake variable or an AC_SUBST variable.
6004           check_ambiguous_conditional ($var, $cond)
6005             unless ($var_is_am{$var} && !$var_is_am
6006                     || exists $configure_vars{$var});
6008           $var_value{$var}{$cond} = $value;
6009         }
6010     }
6012   # An Automake variable can be given to the user, but not the converse.
6013   if (! defined $var_is_am{$var} || !$var_is_am)
6014     {
6015       $var_is_am{$var} = $var_is_am;
6016     }
6018   # Call var_VAR_trigger if it's defined.
6019   # This hook helps to update some internal state *while*
6020   # parsing the file.  For instance the handling of SUFFIXES
6021   # requires this (see var_SUFFIXES_trigger).
6022   my $var_trigger = "var_${var}_trigger";
6023   &$var_trigger($type, $value) if defined &$var_trigger;
6027 # &macro_delete ($VAR, [@CONDS])
6028 # ------------------------------
6029 # Forget about $VAR under the conditions @CONDS, or completely if
6030 # @CONDS is empty.
6031 sub macro_delete ($@)
6033   my ($var, @conds) = @_;
6035   if (!@conds)
6036     {
6037       delete $var_value{$var};
6038       delete $var_location{$var};
6039       delete $var_is_am{$var};
6040       delete $var_comment{$var};
6041       delete $var_type{$var};
6042     }
6043   else
6044     {
6045       foreach my $cond (@conds)
6046         {
6047           delete $var_value{$var}{$cond};
6048         }
6049     }
6053 # &macro_dump ($VAR)
6054 # ------------------
6055 sub macro_dump ($)
6057   my ($var) = @_;
6059   if (!exists $var_value{$var})
6060     {
6061       print STDERR "  $var does not exist\n";
6062     }
6063   else
6064     {
6065       my $var_is_am = $var_is_am{$var} ? "Automake" : "User";
6066       my $where = (defined $var_location{$var}
6067                    ? $var_location{$var} : "undefined");
6068       print STDERR "$var_comment{$var}"
6069         if defined $var_comment{$var};
6070       print STDERR "  $var ($var_is_am, where = $where) $var_type{$var}=\n";
6071       print STDERR "  {\n";
6072       foreach my $vcond (sort by_condition keys %{$var_value{$var}})
6073         {
6074           print STDERR "    $vcond => $var_value{$var}{$vcond}\n";
6075         }
6076       print STDERR "  }\n";
6077     }
6081 # &macros_dump ()
6082 # ---------------
6083 sub macros_dump ()
6085   my ($var) = @_;
6087   print STDERR "%var_value =\n";
6088   print STDERR "{\n";
6089   foreach my $var (sort (keys %var_value))
6090     {
6091       macro_dump ($var);
6092     }
6093   print STDERR "}\n";
6097 # $BOOLEAN
6098 # variable_defined ($VAR, [$COND])
6099 # ---------------------------------
6100 # See if a variable exists.  $VAR is the variable name, and $COND is
6101 # the condition which we should check.  If no condition is given, we
6102 # currently return true if the variable is defined under any
6103 # condition.
6104 sub variable_defined ($;$)
6106     my ($var, $cond) = @_;
6108     # Unfortunately we can't just check for $var_value{VAR}{COND}
6109     # as this would make perl create $condition{VAR}, which we
6110     # don't want.
6111     if (!exists $var_value{$var})
6112       {
6113         macro_error ($var, "`$var' is a target; expected a variable")
6114           if defined $targets{$var};
6115         # The variable is not defined
6116         return 0;
6117       }
6119     # The variable is not defined for the given condition.
6120     return 0
6121       if $cond && !exists $var_value{$var}{$cond};
6123     # Even a var_value examination is good enough for us.  FIXME:
6124     # really should maintain examined status on a per-condition basis.
6125     $content_seen{$var} = 1;
6126     return 1;
6130 # $BOOLEAN
6131 # variable_assert ($VAR, $WHERE)
6132 # ------------------------------
6133 # Make sure a variable exists.  $VAR is the variable name, and $WHERE
6134 # is the name of a macro which refers to $VAR.
6135 sub variable_assert ($$)
6137   my ($var, $where) = @_;
6139   return 1
6140     if variable_defined $var;
6142   macro_error ($where, "variable `$var' not defined");
6144   return 0;
6148 # Mark a variable as examined.
6149 sub examine_variable
6151     my ($var) = @_;
6152     variable_defined ($var);
6156 # &variable_conditions_recursive ($VAR)
6157 # -------------------------------------
6158 # Return the set of conditions for which a variable is defined.
6160 # If the variable is not defined conditionally, and is not defined in
6161 # terms of any variables which are defined conditionally, then this
6162 # returns the empty list.
6164 # If the variable is defined conditionally, but is not defined in
6165 # terms of any variables which are defined conditionally, then this
6166 # returns the list of conditions for which the variable is defined.
6168 # If the variable is defined in terms of any variables which are
6169 # defined conditionally, then this returns a full set of permutations
6170 # of the subvariable conditions.  For example, if the variable is
6171 # defined in terms of a variable which is defined for COND_TRUE,
6172 # then this returns both COND_TRUE and COND_FALSE.  This is
6173 # because we will need to define the variable under both conditions.
6174 sub variable_conditions_recursive ($)
6176     my ($var) = @_;
6178     %vars_scanned = ();
6180     my @new_conds = variable_conditions_recursive_sub ($var, '');
6181     # Now we want to return all permutations of the subvariable
6182     # conditions.
6183     my %allconds = ();
6184     foreach my $item (@new_conds)
6185     {
6186         foreach (split (' ', $item))
6187         {
6188             s/^(.*)_(TRUE|FALSE)$/$1_TRUE/;
6189             $allconds{$_} = 1;
6190         }
6191     }
6192     @new_conds = variable_conditions_permutations (sort keys %allconds);
6194     my %uniqify;
6195     foreach my $cond (@new_conds)
6196     {
6197         my $reduce = variable_conditions_reduce (split (' ', $cond));
6198         next
6199             if $reduce eq 'FALSE';
6200         $uniqify{$cond} = 1;
6201     }
6203     # Note we cannot just do `return sort keys %uniqify', because this
6204     # function is sometimes used in a scalar context.
6205     my @uniq_list = sort by_condition keys %uniqify;
6206     return @uniq_list;
6210 # @CONDS
6211 # variable_conditions ($VAR)
6212 # --------------------------
6213 # Get the list of conditions that a variable is defined with, without
6214 # recursing through the conditions of any subvariables.
6215 # Argument is $VAR: the variable to get the conditions of.
6216 # Returns the list of conditions.
6217 sub variable_conditions ($)
6219     my ($var) = @_;
6220     my @conds = keys %{$var_value{$var}};
6221     return sort by_condition @conds;
6225 # $BOOLEAN
6226 # &variable_conditionally_defined ($VAR)
6227 # --------------------------------------
6228 sub variable_conditionally_defined ($)
6230     my ($var) = @_;
6231     foreach my $cond (variable_conditions_recursive ($var))
6232       {
6233         return 1
6234           unless $cond =~ /^TRUE|FALSE$/;
6235       }
6236     return 0;
6241 # &variable_conditions_recursive_sub ($VAR, $PARENT)
6242 # -------------------------------------------------------
6243 # A subroutine of variable_conditions_recursive.  This returns all the
6244 # conditions of $VAR, including those of any sub-variables.
6245 sub variable_conditions_recursive_sub
6247     my ($var, $parent) = @_;
6248     my @new_conds = ();
6250     if (defined $vars_scanned{$var})
6251     {
6252         macro_error ($parent, "variable `$var' recursively defined");
6253         return ();
6254     }
6255     $vars_scanned{$var} = 1;
6257     my @this_conds = ();
6258     # Examine every condition under which $VAR is defined.
6259     foreach my $vcond (keys %{$var_value{$var}})
6260     {
6261         push (@this_conds, $vcond);
6263         # If $VAR references some other variable, then compute the
6264         # conditions for that subvariable.
6265         my @subvar_conds = ();
6266         foreach (split (' ', $var_value{$var}{$vcond}))
6267         {
6268             # If a comment seen, just leave.
6269             last if /^#/;
6271             # Handle variable substitutions.
6272             if (/^\$\{(.*)\}$/ || /^\$\((.*)\)$/)
6273             {
6274                 my $varname = $1;
6275                 if ($varname =~ /$SUBST_REF_PATTERN/o)
6276                 {
6277                     $varname = $1;
6278                 }
6281                 # Here we compute all the conditions under which the
6282                 # subvariable is defined.  Then we go through and add
6283                 # $VCOND to each.
6284                 my @svc = variable_conditions_recursive_sub ($varname, $var);
6285                 foreach my $item (@svc)
6286                 {
6287                     my $val = conditional_string ($vcond, split (' ', $item));
6288                     $val ||= 'TRUE';
6289                     push (@subvar_conds, $val);
6290                 }
6291             }
6292         }
6294         # If there are no conditional subvariables, then we want to
6295         # return this condition.  Otherwise, we want to return the
6296         # permutations of the subvariables, taking into account the
6297         # conditions of $VAR.
6298         if (! @subvar_conds)
6299         {
6300             push (@new_conds, $vcond);
6301         }
6302         else
6303         {
6304             push (@new_conds, variable_conditions_reduce (@subvar_conds));
6305         }
6306     }
6308     # Unset our entry in vars_scanned.  We only care about recursive
6309     # definitions.
6310     delete $vars_scanned{$var};
6312     # If we are being called on behalf of another variable, we need to
6313     # return all possible permutations of the conditions.  We have
6314     # already handled everything in @this_conds along with their
6315     # subvariables.  We now need to add any permutations that are not
6316     # in @this_conds.
6317     foreach my $this_cond (@this_conds)
6318     {
6319         my @perms =
6320             variable_conditions_permutations (split (' ', $this_cond));
6321         foreach my $perm (@perms)
6322         {
6323             my $ok = 1;
6324             foreach my $scan (@this_conds)
6325             {
6326                 if (&conditional_true_when ($perm, $scan)
6327                     || &conditional_true_when ($scan, $perm))
6328                 {
6329                     $ok = 0;
6330                     last;
6331                 }
6332             }
6333             next if ! $ok;
6335             # This permutation was not already handled, and is valid
6336             # for the parents.
6337             push (@new_conds, $perm);
6338         }
6339     }
6341     return @new_conds;
6345 # Filter a list of conditionals so that only the exclusive ones are
6346 # retained.  For example, if both `COND1_TRUE COND2_TRUE' and
6347 # `COND1_TRUE' are in the list, discard the latter.
6348 # If the list is empty, return TRUE
6349 sub variable_conditions_reduce
6351     my (@conds) = @_;
6352     my @ret = ();
6353     my $cond;
6354     while(@conds > 0)
6355     {
6356         $cond = shift(@conds);
6358         # FALSE is absorbent.
6359         return 'FALSE'
6360           if $cond eq 'FALSE';
6362         if (!conditional_is_redundant ($cond, @ret, @conds))
6363           {
6364             push (@ret, $cond);
6365           }
6366     }
6368     return "TRUE" if @ret == 0;
6369     return @ret;
6372 # @CONDS
6373 # invert_conditions (@CONDS)
6374 # --------------------------
6375 # Invert a list of conditionals.  Returns a set of conditionals which
6376 # are never true for any of the input conditionals, and when taken
6377 # together with the input conditionals cover all possible cases.
6379 # For example: invert_conditions("A_TRUE B_TRUE", "A_FALSE B_FALSE") will
6380 # return ("A_FALSE B_TRUE", "A_TRUE B_FALSE")
6381 sub invert_conditions
6383     my (@conds) = @_;
6385     my @notconds = ();
6386     foreach my $cond (@conds)
6387     {
6388         foreach my $perm (variable_conditions_permutations (split(' ', $cond)))
6389         {
6390             push @notconds, $perm
6391                     if ! conditional_is_redundant ($perm, @conds);
6392         }
6393     }
6394     return variable_conditions_reduce (@notconds);
6397 # Return a list of permutations of a conditional string.
6398 sub variable_conditions_permutations
6400     my (@comps) = @_;
6401     return ()
6402         if ! @comps;
6403     my $comp = shift (@comps);
6404     return variable_conditions_permutations (@comps)
6405         if $comp eq '';
6406     my $neg = condition_negate ($comp);
6408     my @ret;
6409     foreach my $sub (variable_conditions_permutations (@comps))
6410     {
6411         push (@ret, "$comp $sub");
6412         push (@ret, "$neg $sub");
6413     }
6414     if (! @ret)
6415     {
6416         push (@ret, $comp);
6417         push (@ret, $neg);
6418     }
6419     return @ret;
6423 # $BOOL
6424 # &check_variable_defined_unconditionally($VAR, $PARENT)
6425 # ------------------------------------------------------
6426 # Warn if a variable is conditionally defined.  This is called if we
6427 # are using the value of a variable.
6428 sub check_variable_defined_unconditionally ($$)
6430     my ($var, $parent) = @_;
6431     foreach my $cond (keys %{$var_value{$var}})
6432     {
6433         next
6434           if $cond =~ /^TRUE|FALSE$/;
6436         if ($parent)
6437         {
6438             macro_error ($parent,
6439                          "warning: automake does not support conditional definition of $var in $parent");
6440         }
6441         else
6442         {
6443             macro_error ($parent,
6444                          "warning: automake does not support $var being defined conditionally");
6445         }
6446     }
6450 # Get the TRUE value of a variable, warn if the variable is
6451 # conditionally defined.
6452 sub variable_value
6454     my ($var) = @_;
6455     &check_variable_defined_unconditionally ($var);
6456     return $var_value{$var}{'TRUE'};
6460 # @VALUES
6461 # &value_to_list ($VAR, $VAL, $COND)
6462 # ----------------------------------
6463 # Convert a variable value to a list, split as whitespace.  This will
6464 # recursively follow $(...) and ${...} inclusions.  It preserves @...@
6465 # substitutions.
6467 # If COND is 'all', then all values under all conditions should be
6468 # returned; if COND is a particular condition (all conditions are
6469 # surrounded by @...@) then only the value for that condition should
6470 # be returned; otherwise, warn if VAR is conditionally defined.
6471 # SCANNED is a global hash listing whose keys are all the variables
6472 # already scanned; it is an error to rescan a variable.
6473 sub value_to_list ($$$)
6475     my ($var, $val, $cond) = @_;
6476     my @result;
6478     # Strip backslashes
6479     $val =~ s/\\(\n|$)/ /g;
6481     foreach (split (' ', $val))
6482     {
6483         # If a comment seen, just leave.
6484         last if /^#/;
6486         # Handle variable substitutions.
6487         if (/^\$\{([^}]*)\}$/ || /^\$\(([^)]*)\)$/)
6488         {
6489             my $varname = $1;
6491             # If the user uses a losing variable name, just ignore it.
6492             # This isn't ideal, but people have requested it.
6493             next if ($varname =~ /\@.*\@/);
6495             my ($from, $to);
6496             my @temp_list;
6497             if ($varname =~ /$SUBST_REF_PATTERN/o)
6498             {
6499                 $varname = $1;
6500                 $to = $3;
6501                 $from = quotemeta $2;
6502             }
6504             # Find the value.
6505             @temp_list =
6506               variable_value_as_list_recursive_worker ($1, $cond, $var);
6508             # Now rewrite the value if appropriate.
6509             if (defined $from)
6510             {
6511                 grep (s/$from$/$to/, @temp_list);
6512             }
6514             push (@result, @temp_list);
6515         }
6516         else
6517         {
6518             push (@result, $_);
6519         }
6520     }
6522     return @result;
6526 # @VALUES
6527 # variable_value_as_list ($VAR, $COND, $PARENT)
6528 # ---------------------------------------------
6529 # Get the value of a variable given a specified condition. without
6530 # recursing through any subvariables.
6531 # Arguments are:
6532 #   $VAR    is the variable
6533 #   $COND   is the condition.  If this is not given, the value for the
6534 #           "TRUE" condition will be returned.
6535 #   $PARENT is the variable in which the variable is used: this is used
6536 #           only for error messages.
6537 # Returns the list of conditions.
6538 # For example, if A is defined as "foo $(B) bar", and B is defined as
6539 # "baz", this will return ("foo", "$(B)", "bar")
6540 sub variable_value_as_list
6542     my ($var, $cond, $parent) = @_;
6543     my @result;
6545     # Check defined
6546     return
6547       unless variable_assert $var, $parent;
6549     # Get value for given condition
6550     $cond ||= 'TRUE';
6551     my $onceflag;
6552     foreach my $vcond (keys %{$var_value{$var}})
6553     {
6554         my $val = $var_value{$var}{$vcond};
6556         if (&conditional_true_when ($vcond, $cond))
6557         {
6558             # Unless variable is not defined conditionally, there should only
6559             # be one value of $vcond true when $cond.
6560             &check_variable_defined_unconditionally ($var, $parent)
6561                     if $onceflag;
6562             $onceflag = 1;
6564             # Strip backslashes
6565             $val =~ s/\\(\n|$)/ /g;
6567             foreach (split (' ', $val))
6568             {
6569                 # If a comment seen, just leave.
6570                 last if /^#/;
6572                 push (@result, $_);
6573             }
6574         }
6575     }
6577     return @result;
6581 # @VALUE
6582 # &variable_value_as_list_recursive_worker ($VAR, $COND, $PARENT)
6583 # ---------------------------------------------------------------
6584 # Return contents of VAR as a list, split on whitespace.  This will
6585 # recursively follow $(...) and ${...} inclusions.  It preserves @...@
6586 # substitutions.  If COND is 'all', then all values under all
6587 # conditions should be returned; if COND is a particular condition
6588 # (all conditions are surrounded by @...@) then only the value for
6589 # that condition should be returned; otherwise, warn if VAR is
6590 # conditionally defined.  If PARENT is specified, it is the name of
6591 # the including variable; this is only used for error reports.
6592 sub variable_value_as_list_recursive_worker ($$$)
6594     my ($var, $cond, $parent) = @_;
6595     my @result = ();
6597     return
6598       unless variable_assert $var, $parent;
6600     if (defined $vars_scanned{$var})
6601     {
6602         # `vars_scanned' is a global we use to keep track of which
6603         # variables we've already examined.
6604         macro_error ($parent, "variable `$var' recursively defined");
6605     }
6606     elsif ($cond eq 'all')
6607     {
6608         $vars_scanned{$var} = 1;
6609         foreach my $vcond (keys %{$var_value{$var}})
6610         {
6611             my $val = $var_value{$var}{$vcond};
6612             push (@result, &value_to_list ($var, $val, $cond));
6613         }
6614     }
6615     else
6616     {
6617         $cond ||= 'TRUE';
6618         $vars_scanned{$var} = 1;
6619         my $onceflag;
6620         foreach my $vcond (keys %{$var_value{$var}})
6621         {
6622             my $val = $var_value{$var}{$vcond};
6623             if (&conditional_true_when ($vcond, $cond))
6624             {
6625                 # Warn if we have an ambiguity.  It's hard to know how
6626                 # to handle this case correctly.
6627                 &check_variable_defined_unconditionally ($var, $parent)
6628                     if $onceflag;
6629                 $onceflag = 1;
6630                 push (@result, &value_to_list ($var, $val, $cond));
6631             }
6632         }
6633     }
6635     # Unset our entry in vars_scanned.  We only care about recursive
6636     # definitions.
6637     delete $vars_scanned{$var};
6639     return @result;
6643 # &variable_output ($VAR, [@CONDS])
6644 # ---------------------------------
6645 # Output all the values of $VAR is @COND is not specified, else only
6646 # that corresponding to @COND.
6647 sub variable_output ($@)
6649   my ($var, @conds) = @_;
6651   @conds = keys %{$var_value{$var}}
6652     unless @conds;
6654   $output_vars .= $var_comment{$var}
6655     if defined $var_comment{$var};
6657   foreach my $cond (sort by_condition @conds)
6658     {
6659       my $val = $var_value{$var}{$cond};
6660       my $equals = $var_type{$var} eq ':' ? ':=' : '=';
6661       my $output_var = "$var $equals $val";
6662       $output_var =~ s/^/make_condition ($cond)/meg;
6663       $output_vars .= $output_var . "\n";
6664     }
6668 # &variable_pretty_output ($VAR, [@CONDS])
6669 # ----------------------------------------
6670 # Likewise, but pretty, i.e., we *split* the values at spaces.   Use only
6671 # with variables holding filenames.
6672 sub variable_pretty_output ($@)
6674   my ($var, @conds) = @_;
6676   @conds = keys %{$var_value{$var}}
6677     unless @conds;
6679   $output_vars .= $var_comment{$var}
6680     if defined $var_comment{$var};
6682   foreach my $cond (sort by_condition @conds)
6683     {
6684       my $val = $var_value{$var}{$cond};
6685       my $equals = $var_type{$var} eq ':' ? ':=' : '=';
6686       my $make_condition = make_condition ($cond);
6687       $output_vars .= pretty_print_internal ("$make_condition$var $equals",
6688                                              "$make_condition\t",
6689                                              split (' ' , $val));
6690     }
6694 # &variable_value_as_list_recursive ($VAR, $COND, $PARENT)
6695 # --------------------------------------------------------
6696 # This is just a wrapper for variable_value_as_list_recursive_worker that
6697 # initializes the global hash `vars_scanned'.  This hash is used to
6698 # avoid infinite recursion.
6699 sub variable_value_as_list_recursive ($$@)
6701     my ($var, $cond, $parent) = @_;
6702     %vars_scanned = ();
6703     return &variable_value_as_list_recursive_worker ($var, $cond, $parent);
6707 # &define_pretty_variable ($VAR, $COND, @VALUE)
6708 # ---------------------------------------------
6709 # Like define_variable, but the value is a list, and the variable may
6710 # be defined conditionally.  The second argument is the conditional
6711 # under which the value should be defined; this should be the empty
6712 # string to define the variable unconditionally.  The third argument
6713 # is a list holding the values to use for the variable.  The value is
6714 # pretty printed in the output file.
6715 sub define_pretty_variable ($$@)
6717     my ($var, $cond, @value) = @_;
6719     # Beware that an empty $cond has a different semantics for
6720     # macro_define and variable_pretty_output.
6721     $cond ||= 'TRUE';
6723     if (! variable_defined ($var, $cond))
6724     {
6725         macro_define ($var, 1, '', $cond, "@value", undef);
6726         variable_pretty_output ($var, $cond || 'TRUE');
6727         $content_seen{$var} = 1;
6728     }
6732 # define_variable ($VAR, $VALUE)
6733 # ------------------------------
6734 # Define a new user variable VAR to VALUE, but only if not already defined.
6735 sub define_variable ($$)
6737     my ($var, $value) = @_;
6738     define_pretty_variable ($var, 'TRUE', $value);
6742 # Like define_variable, but define a variable to be the configure
6743 # substitution by the same name.
6744 sub define_configure_variable ($)
6746     my ($var) = @_;
6747     if (! variable_defined ($var, 'TRUE'))
6748     {
6749         # A macro defined via configure is a `user' macro -- we should not
6750         # override it.
6751         macro_define ($var, 0, '', 'TRUE', subst $var, $configure_vars{$var});
6752         variable_pretty_output ($var, 'TRUE');
6753     }
6757 # define_compiler_variable ($LANG)
6758 # --------------------------------
6759 # Define a compiler variable.  We also handle defining the `LT'
6760 # version of the command when using libtool.
6761 sub define_compiler_variable ($)
6763     my ($lang) = @_;
6765     my ($var, $value) = ($lang->compiler, $lang->compile);
6766     &define_variable ($var, $value);
6767     &define_variable ("LT$var", "\$(LIBTOOL) --mode=compile $value")
6768       if $seen_libtool;
6772 # define_linker_variable ($LANG)
6773 # ------------------------------
6774 # Define linker variables.
6775 sub define_linker_variable ($)
6777     my ($lang) = @_;
6779     my ($var, $value) = ($lang->lder, $lang->ld);
6780     # CCLD = $(CC).
6781     &define_variable ($lang->lder, $lang->ld);
6782     # CCLINK = $(CCLD) blah blah...
6783     &define_variable ($lang->linker,
6784                       (($seen_libtool ? '$(LIBTOOL) --mode=link ' : '')
6785                        . $lang->link));
6788 ################################################################
6790 ## ---------------- ##
6791 ## Handling rules.  ##
6792 ## ---------------- ##
6794 # $BOOL
6795 # rule_define ($TARGET, $IS_AM, $COND, $WHERE)
6796 # --------------------------------------------
6797 # Define a new rule.  $TARGET is the rule name.  $IS_AM is a boolean
6798 # which is true if the new rule is defined by the user.  $COND is the
6799 # condition under which the rule is defined.  $WHERE is where the rule
6800 # is defined (file name or line number).  Returns true if it is ok to
6801 # define the rule, false otherwise.
6802 sub rule_define ($$$$)
6804   my ($target, $rule_is_am, $cond, $where) = @_;
6806   # For now `foo:' will override `foo$(EXEEXT):'.  This is temporary,
6807   # though, so we emit a warning.
6808   (my $noexe = $target) =~ s,\$\(EXEEXT\)$,,;
6809   if ($noexe ne $target && defined $targets{$noexe})
6810   {
6811       # The no-exeext option enables this feature.
6812       if (! defined $options{'no-exeext'})
6813       {
6814           macro_error ($noexe,
6815                        "deprecated feature: `$noexe' overrides `$noexe\$(EXEEXT)'\nchange your target to read `$noexe\$(EXEEXT)'");
6816       }
6817       # Don't define.
6818       return 0;
6819   }
6821   if (defined $targets{$target}
6822       && ($cond
6823           ? ! defined $target_conditional{$target}
6824           : defined $target_conditional{$target}))
6825   {
6826       target_error ($target,
6827                     "$target defined both conditionally and unconditionally");
6828   }
6830   # Value here doesn't matter; for targets we only note existence.
6831   $targets{$target} = $where;
6832   if ($cond)
6833   {
6834       if ($target_conditional{$target})
6835       {
6836           &check_ambiguous_conditional ($target, $cond);
6837       }
6838       $target_conditional{$target}{$cond} = $where;
6839   }
6841   # Check the rule for being a suffix rule. If so, store in a hash.
6842   # Either it's a rule for two known extensions...
6843   if ($target =~ /^($KNOWN_EXTENSIONS_PATTERN)($KNOWN_EXTENSIONS_PATTERN)$/
6844   # ...or it's a rule with unknown extensions (.i.e, the rule looks like
6845   # `.foo.bar:' but `.foo' or `.bar' are not declared in SUFFIXES
6846   # and are not known language extensions).
6847   # Automake will complete SUFFIXES from @suffixes automatically
6848   # (see handle_footer).
6849       || ($target =~ /$SUFFIX_RULE_PATTERN/o && accept_extensions($1)))
6850   {
6851       my $internal_ext = $2;
6853       # When tranforming sources to objects, Automake uses the
6854       # %suffix_rules to move from each source extension to
6855       # `.$(OBJEXT)', not to `.o' or `.obj'.  However some people
6856       # define suffix rules for `.o' or `.obj', so internally we will
6857       # consider these extensions equivalent to `.$(OBJEXT)'.  We
6858       # CANNOT rewrite the target (i.e., automagically replace `.o'
6859       # and `.obj' by `.$(OBJEXT)' in the output), or warn the user
6860       # that (s)he'd better use `.$(OBJEXT)', because Automake itself
6861       # output suffix rules for `.o' or `.obj'...
6862       $internal_ext = '.$(OBJEXT)' if ($2 eq '.o' || $2 eq '.obj');
6864       $suffix_rules{$1} = $internal_ext;
6865       verbose "Sources ending in $1 become $2";
6866       push @suffixes, $1, $2;
6867   }
6869   return 1;
6873 # See if a target exists.
6874 sub target_defined
6876     my ($target) = @_;
6877     return defined $targets{$target};
6881 ################################################################
6883 # &append_comments ($VARIABLE, $SPACING, $COMMENT)
6884 # ------------------------------------------------
6885 # Apped $COMMENT to the other comments for $VARIABLE, using
6886 # $SPACING as separator.
6887 sub append_comments ($$$)
6889     my ($var, $spacing, $comment) = @_;
6890     $var_comment{$var} .= $spacing
6891         if (!defined $var_comment{$var} || $var_comment{$var} !~ /\n$/o);
6892     $var_comment{$var} .= $comment;
6896 # &read_am_file ($AMFILE)
6897 # -----------------------
6898 # Read Makefile.am and set up %contents.  Simultaneously copy lines
6899 # from Makefile.am into $output_trailer or $output_vars as
6900 # appropriate.  NOTE we put rules in the trailer section.  We want
6901 # user rules to come after our generated stuff.
6902 sub read_am_file ($)
6904     my ($amfile) = @_;
6906     my $am_file = new Automake::XFile ("< $amfile");
6907     verbose "reading $amfile";
6909     my $spacing = '';
6910     my $comment = '';
6911     my $blank = 0;
6912     my $saw_bk = 0;
6914     while ($_ = $am_file->getline)
6915     {
6916         if (/$IGNORE_PATTERN/o)
6917         {
6918             # Merely delete comments beginning with two hashes.
6919         }
6920         elsif (/$WHITE_PATTERN/o)
6921         {
6922             file_error ("$amfile:$.",
6923                         "blank line following trailing backslash")
6924                 if $saw_bk;
6925             # Stick a single white line before the incoming macro or rule.
6926             $spacing = "\n";
6927             $blank = 1;
6928             # Flush all comments seen so far.
6929             if ($comment ne '')
6930             {
6931                 $output_vars .= $comment;
6932                 $comment = '';
6933             }
6934         }
6935         elsif (/$COMMENT_PATTERN/o)
6936         {
6937             # Stick comments before the incoming macro or rule.  Make
6938             # sure a blank line preceeds first block of comments.
6939             $spacing = "\n" unless $blank;
6940             $blank = 1;
6941             $comment .= $spacing . $_;
6942             $spacing = '';
6943         }
6944         else
6945         {
6946             last;
6947         }
6948         $saw_bk = /\\$/ && ! /$IGNORE_PATTERN/o;
6949     }
6951     # We save the conditional stack on entry, and then check to make
6952     # sure it is the same on exit.  This lets us conditonally include
6953     # other files.
6954     my @saved_cond_stack = @cond_stack;
6955     my $cond = conditional_string (@cond_stack);
6957     my $was_rule = 0;
6958     my $last_var_name = '';
6959     my $last_var_type = '';
6960     my $last_var_value = '';
6961     # FIXME: shouldn't use $_ in this loop; it is too big.
6962     while ($_)
6963     {
6964         my $here = "$amfile:$.";
6966         # Make sure the line is \n-terminated.
6967         chomp;
6968         $_ .= "\n";
6970         # Don't look at MAINTAINER_MODE_TRUE here.  That shouldn't be
6971         # used by users.  @MAINT@ is an anachronism now.
6972         $_ =~ s/\@MAINT\@//g
6973             unless $seen_maint_mode;
6975         my $new_saw_bk = /\\$/ && ! /$IGNORE_PATTERN/o;
6977         if (/$IGNORE_PATTERN/o)
6978         {
6979             # Merely delete comments beginning with two hashes.
6980         }
6981         elsif (/$WHITE_PATTERN/o)
6982         {
6983             # Stick a single white line before the incoming macro or rule.
6984             $spacing = "\n";
6985             file_error ($here, "blank line following trailing backslash")
6986                 if $saw_bk;
6987         }
6988         elsif (/$COMMENT_PATTERN/o)
6989         {
6990             # Stick comments before the incoming macro or rule.
6991             $comment .= $spacing . $_;
6992             $spacing = '';
6993             file_error ($here, "comment following trailing backslash")
6994                 if $saw_bk && $comment eq '';
6995         }
6996         elsif ($saw_bk)
6997         {
6998             if ($was_rule)
6999             {
7000                 $output_trailer .= &make_condition (@cond_stack);
7001                 $output_trailer .= $_;
7002             }
7003             else
7004             {
7005               $last_var_value .= ' '
7006                 unless $last_var_value =~ /\s$/;
7007               $last_var_value .= $_;
7009               if (!/\\$/)
7010                 {
7011                   append_comments $last_var_name, $spacing, $comment;
7012                   $comment = $spacing = '';
7013                   macro_define ($last_var_name, 0,
7014                                 $last_var_type, $cond,
7015                                 $last_var_value, $here)
7016                     if $cond ne 'FALSE';
7017                   push (@var_list, $last_var_name);
7018                 }
7019             }
7020         }
7022         elsif (/$IF_PATTERN/o)
7023           {
7024             $cond = cond_stack_if ($1, $2, $here);
7025           }
7026         elsif (/$ELSE_PATTERN/o)
7027           {
7028             $cond = cond_stack_else ($1, $2, $here);
7029           }
7030         elsif (/$ENDIF_PATTERN/o)
7031           {
7032             $cond = cond_stack_endif ($1, $2, $here);
7033           }
7035         elsif (/$RULE_PATTERN/o)
7036         {
7037             # Found a rule.
7038             $was_rule = 1;
7040             rule_define ($1, 0, $cond, $here);
7042             $output_trailer .= $comment . $spacing;
7043             $output_trailer .= &make_condition (@cond_stack);
7044             $output_trailer .= $_;
7045             $comment = $spacing = '';
7046         }
7047         elsif (/$ASSIGNMENT_PATTERN/o)
7048         {
7049             # Found a macro definition.
7050             $was_rule = 0;
7051             $last_var_name = $1;
7052             $last_var_type = $2;
7053             $last_var_value = $3;
7054             if ($3 ne '' && substr ($3, -1) eq "\\")
7055             {
7056                 # We preserve the `\' because otherwise the long lines
7057                 # that are generated will be truncated by broken
7058                 # `sed's.
7059                 $last_var_value = $3 . "\n";
7060             }
7062             if (!/\\$/)
7063               {
7064                 # FIXME: this doesn't always work correctly; it will
7065                 # group all comments for a given variable, no matter
7066                 # where defined.
7067                 # Accumulating variables must not be output.
7068                 append_comments $last_var_name, $spacing, $comment;
7069                 $comment = $spacing = '';
7071                 macro_define ($last_var_name, 0,
7072                               $last_var_type, $cond,
7073                               $last_var_value, $here)
7074                   if $cond ne 'FALSE';
7075                 push (@var_list, $last_var_name);
7076               }
7077         }
7078         elsif (/$INCLUDE_PATTERN/o)
7079         {
7080             my $path = $1;
7082             if ($path =~ s/^\$\(top_srcdir\)\///)
7083             {
7084                 push (@include_stack, "\$\(top_srcdir\)/$path");
7085             }
7086             else
7087             {
7088                 $path =~ s/\$\(srcdir\)\///;
7089                 push (@include_stack, "\$\(srcdir\)/$path");
7090                 $path = $relative_dir . "/" . $path;
7091             }
7092             &read_am_file ($path);
7093         }
7094         else
7095         {
7096             # This isn't an error; it is probably a continued rule.
7097             # In fact, this is what we assume.
7098             $was_rule = 1;
7099             $output_trailer .= $comment . $spacing;
7100             $output_trailer .= &make_condition  (@cond_stack);
7101             $output_trailer .= $_;
7102             $comment = $spacing = '';
7103             file_error ($here, "`#' comment at start of rule is unportable")
7104                 if $_ =~ /^\t\s*\#/;
7105         }
7107         $saw_bk = $new_saw_bk;
7108         $_ = $am_file->getline;
7109     }
7111     $output_trailer .= $comment;
7113     if ("@saved_cond_stack" ne "@cond_stack")
7114     {
7115         if (@cond_stack)
7116         {
7117             &am_error ("unterminated conditionals: @cond_stack");
7118         }
7119         else
7120         {
7121             # FIXME: better error message here.
7122             &am_error ("conditionals not nested in include file");
7123         }
7124     }
7128 # define_standard_variables ()
7129 # ----------------------------
7130 # A helper for read_main_am_file which initializes configure variables
7131 # and variables from header-vars.am.  This is a subr so we can call it
7132 # twice.
7133 sub define_standard_variables
7135     my $saved_output_vars = $output_vars;
7136     my ($comments, undef, $rules) =
7137       file_contents_internal (1, "$libdir/am/header-vars.am");
7139     # This will output the definitions in $output_vars, which we don't
7140     # want...
7141     foreach my $var (sort keys %configure_vars)
7142     {
7143         &define_configure_variable ($var);
7144         push (@var_list, $var);
7145     }
7147     # ... hence, we restore $output_vars.
7148     $output_vars = $saved_output_vars . $comments . $rules;
7151 # Read main am file.
7152 sub read_main_am_file
7154     my ($amfile) = @_;
7156     # This supports the strange variable tricks we are about to play.
7157     if (scalar keys %var_value > 0)
7158       {
7159         macros_dump ();
7160         prog_error ("variable defined before read_main_am_file");
7161       }
7163     # Generate copyright header for generated Makefile.in.
7164     # We do discard the output of predefined variables, handled below.
7165     $output_vars = ("# $in_file_name generated by automake "
7166                    . $VERSION . " from $am_file_name.\n");
7167     $output_vars .= '# ' . subst ('configure_input') . "\n";
7168     $output_vars .= $gen_copyright;
7170     # We want to predefine as many variables as possible.  This lets
7171     # the user set them with `+=' in Makefile.am.  However, we don't
7172     # want these initial definitions to end up in the output quite
7173     # yet.  So we just load them, but output them later.
7174     &define_standard_variables;
7176     # Read user file, which might override some of our values.
7177     &read_am_file ($amfile);
7179     # Output all the Automake variables.  If the user changed one,
7180     # then it is now marked as owned by the user.
7181     foreach my $var (uniq @var_list)
7182     {
7183         # Don't process user variables.
7184         variable_output ($var)
7185           unless !$var_is_am{$var};
7186     }
7188     # Now dump the user variables that were defined.  We do it in the same
7189     # order in which they were defined (skipping duplicates).
7190     foreach my $var (uniq @var_list)
7191     {
7192         # Don't process Automake variables.
7193         variable_output ($var)
7194           unless $var_is_am{$var};
7195     }
7198 ################################################################
7200 # $FLATTENED
7201 # &flatten ($STRING)
7202 # ------------------
7203 # Flatten the $STRING and return the result.
7204 sub flatten
7206   $_ = shift;
7208   s/\\\n//somg;
7209   s/\s+/ /g;
7210   s/^ //;
7211   s/ $//;
7213   return $_;
7217 # @PARAGRAPHS
7218 # &make_paragraphs ($MAKEFILE, [%TRANSFORM])
7219 # ------------------------------------------
7220 # Load a $MAKEFILE, apply the %TRANSFORM, and return it as a list of
7221 # paragraphs.
7222 sub make_paragraphs ($%)
7224     my ($file, %transform) = @_;
7226     # Complete %transform with global options and make it a Perl
7227     # $command.
7228     my $command =
7229       "s/$IGNORE_PATTERN//gm;"
7230         . transform (%transform,
7232                      'CYGNUS'          => $cygnus_mode,
7233                      'MAINTAINER-MODE'
7234                      => $seen_maint_mode ? subst ('MAINTAINER_MODE_TRUE') : '',
7236                      'SHAR'        => $options{'dist-shar'} || 0,
7237                      'BZIP2'       => $options{'dist-bzip2'} || 0,
7238                      'ZIP'         => $options{'dist-zip'} || 0,
7239                      'COMPRESS'    => $options{'dist-tarZ'} || 0,
7241                      'INSTALL-INFO' => !$options{'no-installinfo'},
7242                      'INSTALL-MAN'  => !$options{'no-installman'},
7243                      'CK-NEWS'      => $options{'check-news'} || 0,
7245                      'SUBDIRS'      => variable_defined ('SUBDIRS'),
7246                      'TOPDIR'       => backname ($relative_dir),
7247                      'TOPDIR_P'     => $relative_dir eq '.',
7248                      'CONFIGURE-AC' => $configure_ac,
7250                      'BUILD'    => $seen_canonical == AC_CANONICAL_SYSTEM,
7251                      'HOST'     => $seen_canonical,
7252                      'TARGET'   => $seen_canonical == AC_CANONICAL_SYSTEM,
7254                      'LIBTOOL'      => defined $configure_vars{'LIBTOOL'})
7255           # We don't need more than two consecutive new-lines.
7256           . 's/\n{3,}/\n\n/g';
7258     # Swallow the file and apply the COMMAND.
7259     my $fc_file = new Automake::XFile "< $file";
7260     # Looks stupid?
7261     verbose "reading $file";
7262     my $saved_dollar_slash = $/;
7263     undef $/;
7264     $_ = $fc_file->getline;
7265     $/ = $saved_dollar_slash;
7266     eval $command;
7267     $fc_file->close;
7268     my $content = $_;
7270     # Split at unescaped new lines.
7271     my @lines = split (/(?<!\\)\n/, $content);
7272     my @res;
7274     while (defined ($_ = shift @lines))
7275       {
7276         my $paragraph = "$_";
7277         # If we are a rule, eat as long as we start with a tab.
7278         if (/$RULE_PATTERN/smo)
7279           {
7280             while (defined ($_ = shift @lines) && $_ =~ /^\t/)
7281               {
7282                 $paragraph .= "\n$_";
7283               }
7284             unshift (@lines, $_);
7285           }
7287         # If we are a comments, eat as much comments as you can.
7288         elsif (/$COMMENT_PATTERN/smo)
7289           {
7290             while (defined ($_ = shift @lines)
7291                    && $_ =~ /$COMMENT_PATTERN/smo)
7292               {
7293                 $paragraph .= "\n$_";
7294               }
7295             unshift (@lines, $_);
7296           }
7298         push @res, $paragraph;
7299         $paragraph = '';
7300       }
7302     return @res;
7307 # ($COMMENT, $VARIABLES, $RULES)
7308 # &file_contents_internal ($IS_AM, $FILE, [%TRANSFORM])
7309 # -----------------------------------------------------
7310 # Return contents of a file from $libdir/am, automatically skipping
7311 # macros or rules which are already known. $IS_AM iff the caller is
7312 # reading an Automake file (as opposed to the user's Makefile.am).
7313 sub file_contents_internal ($$%)
7315     my ($is_am, $file, %transform) = @_;
7317     my $result_vars = '';
7318     my $result_rules = '';
7319     my $comment = '';
7320     my $spacing = '';
7322     # The following flags are used to track rules spanning across
7323     # multiple paragraphs.
7324     my $is_rule = 0;            # 1 if we are processing a rule.
7325     my $discard_rule = 0;       # 1 if the current rule should not be output.
7327     # We save the conditional stack on entry, and then check to make
7328     # sure it is the same on exit.  This lets us conditonally include
7329     # other files.
7330     my @saved_cond_stack = @cond_stack;
7331     my $cond = conditional_string (@cond_stack);
7333     foreach (make_paragraphs ($file, %transform))
7334     {
7335         # Sanity checks.
7336         file_error ($file, "blank line following trailing backslash:\n$_")
7337           if /\\$/;
7338         file_error ($file, "comment following trailing backslash:\n$_")
7339           if /\\#/;
7341         if (/^$/)
7342         {
7343             $is_rule = 0;
7344             # Stick empty line before the incoming macro or rule.
7345             $spacing = "\n";
7346         }
7347         elsif (/$COMMENT_PATTERN/mso)
7348         {
7349             $is_rule = 0;
7350             # Stick comments before the incoming macro or rule.
7351             $comment = "$_\n";
7352         }
7354         # Handle inclusion of other files.
7355         elsif (/$INCLUDE_PATTERN/o)
7356         {
7357             if ($cond ne 'FALSE')
7358               {
7359                 my $file = ($is_am ? "$libdir/am/" : '') . $1;
7360                 # N-ary `.=' fails.
7361                 my ($com, $vars, $rules)
7362                   = file_contents_internal ($is_am, $file, %transform);
7363                 $comment .= $com;
7364                 $result_vars .= $vars;
7365                 $result_rules .= $rules;
7366               }
7367         }
7369         # Handling the conditionals.
7370         elsif (/$IF_PATTERN/o)
7371           {
7372             $cond = cond_stack_if ($1, $2, $file);
7373           }
7374         elsif (/$ELSE_PATTERN/o)
7375           {
7376             $cond = cond_stack_else ($1, $2, $file);
7377           }
7378         elsif (/$ENDIF_PATTERN/o)
7379           {
7380             $cond = cond_stack_endif ($1, $2, $file);
7381           }
7383         # Handling rules.
7384         elsif (/$RULE_PATTERN/mso)
7385         {
7386           $is_rule = 1;
7387           $discard_rule = 0;
7388           # Separate relationship from optional actions: the first
7389           # `new-line tab" not preceded by backslash (continuation
7390           # line).
7391           # I'm quite shoked!  It seems that (\\\n|[^\n]) is not the
7392           # same as `([^\n]|\\\n)!!!  Don't swap it, it breaks.
7393           my $paragraph = $_;
7394           /^((?:\\\n|[^\n])*)(?:\n(\t.*))?$/som;
7395           my ($relationship, $actions) = ($1, $2 || '');
7397           # Separate targets from dependencies: the first colon.
7398           $relationship =~ /^([^:]+\S+) *: *(.*)$/som;
7399           my ($targets, $dependencies) = ($1, $2);
7400           # Remove the escaped new lines.
7401           # I don't know why, but I have to use a tmp $flat_deps.
7402           my $flat_deps = &flatten ($dependencies);
7403           my @deps = split (' ', $flat_deps);
7405           foreach (split (' ' , $targets))
7406             {
7407               # FIXME: We are not robust to people defining several targets
7408               # at once, only some of them being in %dependencies.  The
7409               # actions from the targets in %dependencies are usually generated
7410               # from the content of %actions, but if some targets in $targets
7411               # are not in %dependencies the ELSE branch will output
7412               # a rule for all $targets (i.e. the targets which are both
7413               # in %dependencies and $targets will have two rules).
7415               # FIXME: The logic here is not able to output a
7416               # multi-paragraph rule several time (e.g. for each conditional
7417               # it is defined for) because it only knows the first paragraph.
7419               # Output only if not in FALSE.
7420               if (defined $dependencies{$_}
7421                   && $cond ne 'FALSE')
7422                 {
7423                   &depend ($_, @deps);
7424                   $actions{$_} .= $actions;
7425                 }
7426               else
7427                 {
7428                   # Free-lance dependency.  Output the rule for all the
7429                   # targets instead of one by one.
7431                   # Work out all the conditions for which the target hasn't
7432                   # been defined
7433                   my @undefined_conds;
7434                   if (defined $target_conditional{$targets})
7435                     {
7436                       my @defined_conds = keys %{$target_conditional{$targets}};
7437                       @undefined_conds = invert_conditions(@defined_conds);
7438                     }
7439                   else
7440                     {
7441                       if (defined $targets{$targets})
7442                         {
7443                           # No conditions for which target hasn't been defined
7444                           @undefined_conds = ();
7445                         }
7446                       else
7447                         {
7448                           # Target hasn't been defined for any conditions
7449                           @undefined_conds = ("");
7450                         }
7451                     }
7453                   if ($cond ne 'FALSE')
7454                     {
7455                       for my $undefined_cond (@undefined_conds)
7456                       {
7457                           my $condparagraph = $paragraph;
7458                           $condparagraph =~ s/^/make_condition (@cond_stack, $undefined_cond)/gme;
7459                           if (rule_define ($targets, $is_am,
7460                                           "$cond $undefined_cond", $file))
7461                           {
7462                               $result_rules .=
7463                                   "$spacing$comment$condparagraph\n"
7464                           }
7465                           else
7466                           {
7467                               # Remember to discard next paragraphs
7468                               # if they belong to this rule.
7469                               $discard_rule = 1;
7470                           }
7471                       }
7472                       if ($#undefined_conds == -1)
7473                       {
7474                           # This target has already been defined, the rule
7475                           # has not been defined. Remember to discard next
7476                           # paragraphs if they belong to this rule.
7477                           $discard_rule = 1;
7478                       }
7479                     }
7480                   $comment = $spacing = '';
7481                   last;
7482                 }
7483             }
7484         }
7486         elsif (/$ASSIGNMENT_PATTERN/mso)
7487         {
7488             my ($var, $type, $val) = ($1, $2, $3);
7489             file_error ($file, "macro `$var' with trailing backslash")
7490               if /\\$/;
7492             $is_rule = 0;
7494             # Accumulating variables must not be output.
7495             append_comments $var, $spacing, $comment;
7496             macro_define ($var, $is_am, $type, $cond, $val, $file)
7497               if $cond ne 'FALSE';
7498             push (@var_list, $var);
7500             # If the user has set some variables we were in charge
7501             # of (which is detected by the first reading of
7502             # `header-vars.am'), we must not output them.
7503             $result_vars .= "$spacing$comment$_\n"
7504               if $type ne '+' && $var_is_am{$var} && $cond ne 'FALSE';
7506             $comment = $spacing = '';
7507         }
7508         else
7509         {
7510             # This isn't an error; it is probably some tokens which
7511             # configure is supposed to replace, such as `@SET-MAKE@',
7512             # or some part of a rule cut by an if/endif.
7513             if ($cond ne 'FALSE' && ! ($is_rule && $discard_rule))
7514               {
7515                 s/^/make_condition (@cond_stack)/gme;
7516                 $result_rules .= "$spacing$comment$_\n";
7517               }
7518             $comment = $spacing = '';
7519         }
7520     }
7522     if ("@saved_cond_stack" ne "@cond_stack")
7523     {
7524         if (@cond_stack)
7525         {
7526             &am_error ("unterminated conditionals: @cond_stack");
7527         }
7528         else
7529         {
7530             # FIXME: better error message here.
7531             &am_error ("conditionals not nested in include file");
7532         }
7533     }
7535     return ($comment, $result_vars, $result_rules);
7539 # $CONTENTS
7540 # &file_contents ($BASENAME, [%TRANSFORM])
7541 # ----------------------------------------
7542 # Return contents of a file from $libdir/am, automatically skipping
7543 # macros or rules which are already known.
7544 sub file_contents ($%)
7546     my ($basename, %transform) = @_;
7547     my ($comments, $variables, $rules) =
7548       file_contents_internal (1, "$libdir/am/$basename.am", %transform);
7549     return "$comments$variables$rules";
7553 # $REGEXP
7554 # &transform (%PAIRS)
7555 # -------------------
7556 # Foreach ($TOKEN, $VAL) in %PAIRS produce a replacement expression suitable
7557 # for file_contents which:
7558 #   - replaces %$TOKEN% with $VAL,
7559 #   - enables/disables ?$TOKEN? and ?!$TOKEN?,
7560 #   - replaces %?$TOKEN% with TRUE or FALSE.
7561 sub transform (%)
7563     my (%pairs) = @_;
7564     my $result = '';
7566     while (my ($token, $val) = each %pairs)
7567     {
7568         $result .= "s/\Q%$token%\E/\Q$val\E/gm;";
7569         if ($val)
7570         {
7571             $result .= "s/\Q?$token?\E//gm;s/^.*\Q?!$token?\E.*\\n//gm;";
7572             $result .= "s/\Q%?$token%\E/TRUE/gm;";
7573         }
7574         else
7575         {
7576             $result .= "s/\Q?!$token?\E//gm;s/^.*\Q?$token?\E.*\\n//gm;";
7577             $result .= "s/\Q%?$token%\E/FALSE/gm;";
7578         }
7579     }
7581     return $result;
7585 # &append_exeext ($MACRO)
7586 # -----------------------
7587 # Macro is an Automake magic macro which primary is PROGRAMS, e.g.
7588 # bin_PROGRAMS.  Make sure these programs have $(EXEEXT) appended.
7589 sub append_exeext ($)
7591   my ($macro) = @_;
7593   prog_error "append_exeext ($macro)"
7594     unless $macro =~ /_PROGRAMS$/;
7596   my @conds = variable_conditions_recursive ($macro);
7598   my @condvals;
7599   foreach my $cond (@conds)
7600     {
7601       my @one_binlist = ();
7602       my @condval = variable_value_as_list_recursive ($macro, $cond);
7603       foreach my $rcurs (@condval)
7604         {
7605           # Skip autoconf substs.  Also skip if the user
7606           # already applied $(EXEEXT).
7607           if ($rcurs =~ /^\@.*\@$/ || $rcurs =~ /\$\(EXEEXT\)$/)
7608             {
7609               push (@one_binlist, $rcurs);
7610             }
7611           else
7612             {
7613               push (@one_binlist, $rcurs . '$(EXEEXT)');
7614             }
7615         }
7617       push (@condvals, $cond);
7618       push (@condvals, "@one_binlist");
7619     }
7621   macro_delete ($macro);
7622   while (@condvals)
7623     {
7624       my $cond = shift (@condvals);
7625       my @val = split (' ', shift (@condvals));
7626       define_pretty_variable ($macro, $cond, @val);
7627     }
7631 # @PREFIX
7632 # &am_primary_prefixes ($PRIMARY, $CAN_DIST, @PREFIXES)
7633 # -----------------------------------------------------
7634 # Find all variable prefixes that are used for install directories.  A
7635 # prefix `zar' qualifies iff:
7637 # * `zardir' is a variable.
7638 # * `zar_PRIMARY' is a variable.
7640 # As a side effect, it looks for misspellings.  It is an error to have
7641 # a variable ending in a "reserved" suffix whose prefix is unknown, eg
7642 # "bni_PROGRAMS".  However, unusual prefixes are allowed if a variable
7643 # of the same name (with "dir" appended) exists.  For instance, if the
7644 # variable "zardir" is defined, then "zar_PROGRAMS" becomes valid.
7645 # This is to provide a little extra flexibility in those cases which
7646 # need it.
7647 sub am_primary_prefixes ($$@)
7649     my ($primary, $can_dist, @prefixes) = @_;
7651     local $_;
7652     my %valid = map { $_ => 0 } @prefixes;
7653     $valid{'EXTRA'} = 0;
7654     foreach my $varname (keys %var_value)
7655     {
7656         # Automake is allowed to define variables that look like they
7657         # are magic variables, such as INSTALL_DATA.
7658         next
7659           if $var_is_am{$varname};
7661         if ($varname =~ /^(nobase_)?(dist_|nodist_)?(.*)_$primary$/)
7662         {
7663             my ($base, $dist, $X) = ($1 || '', $2 || '', $3 || '');
7664             if ($dist ne '' && ! $can_dist)
7665             {
7666                 # Note that a configure variable is always legitimate.
7667                 # It is natural to name such variables after the
7668                 # primary, so we explicitly allow it.
7669                 macro_error ($varname,
7670                             "invalid variable `$varname': `dist' is forbidden")
7671                   if ! exists $configure_vars{$varname};
7672             }
7673             elsif (! defined $valid{$X} && ! variable_defined ("${X}dir"))
7674             {
7675                 # Note that a configure variable is always legitimate.
7676                 # It is natural to name such variables after the
7677                 # primary, so we explicitly allow it.
7678                 macro_error ($varname, "invalid variable `$varname'")
7679                   if ! exists $configure_vars{$varname};
7680             }
7681             else
7682             {
7683                 # Ensure all extended prefixes are actually used.
7684                 $valid{"$base$dist$X"} = 1;
7685             }
7686         }
7687     }
7689     # Return only those which are actually defined.
7690     return sort grep { variable_defined ($_ . '_' . $primary) } keys %valid;
7694 # Handle `where_HOW' variable magic.  Does all lookups, generates
7695 # install code, and possibly generates code to define the primary
7696 # variable.  The first argument is the name of the .am file to munge,
7697 # the second argument is the primary variable (eg HEADERS), and all
7698 # subsequent arguments are possible installation locations.  Returns
7699 # list of all values of all _HOW targets.
7701 # FIXME: this should be rewritten to be cleaner.  It should be broken
7702 # up into multiple functions.
7704 # Usage is: am_install_var (OPTION..., file, HOW, where...)
7705 sub am_install_var
7707     my (@args) = @_;
7709     my $do_require = 1;
7710     my $can_dist = 0;
7711     my $default_dist = 0;
7712     while (@args)
7713     {
7714         if ($args[0] eq '-noextra')
7715         {
7716             $do_require = 0;
7717         }
7718         elsif ($args[0] eq '-candist')
7719         {
7720             $can_dist = 1;
7721         }
7722         elsif ($args[0] eq '-defaultdist')
7723         {
7724             $default_dist = 1;
7725             $can_dist = 1;
7726         }
7727         elsif ($args[0] !~ /^-/)
7728         {
7729             last;
7730         }
7731         shift (@args);
7732     }
7734     my ($file, $primary, @prefix) = @args;
7736     # Now that configure substitutions are allowed in where_HOW
7737     # variables, it is an error to actually define the primary.  We
7738     # allow `JAVA', as it is customarily used to mean the Java
7739     # interpreter.  This is but one of several Java hacks.  Similarly,
7740     # `PYTHON' is customarily used to mean the Python interpreter.
7741     macro_error ($primary, "`$primary' is an anachronism")
7742         if variable_defined ($primary)
7743             && ($primary ne 'JAVA' && $primary ne 'PYTHON');
7746     # Get the prefixes which are valid and actually used.
7747     @prefix = am_primary_prefixes ($primary, $can_dist, @prefix);
7749     # If a primary includes a configure substitution, then the EXTRA_
7750     # form is required.  Otherwise we can't properly do our job.
7751     my $require_extra;
7752     my $warned_about_extra = 0;
7754     my @used = ();
7755     my @result = ();
7757     # True if the iteration is the first one.  Used for instance to
7758     # output parts of the associated file only once.
7759     my $first = 1;
7760     foreach my $X (@prefix)
7761     {
7762         my $nodir_name = $X;
7763         my $one_name = $X . '_' . $primary;
7765         my $strip_subdir = 1;
7766         # If subdir prefix should be preserved, do so.
7767         if ($nodir_name =~ /^nobase_/)
7768           {
7769             $strip_subdir = 0;
7770             $nodir_name =~ s/^nobase_//;
7771           }
7773         # If files should be distributed, do so.
7774         my $dist_p = 0;
7775         if ($can_dist)
7776           {
7777             $dist_p = (($default_dist && $nodir_name !~ /^nodist_/)
7778                        || (! $default_dist && $nodir_name =~ /^dist_/));
7779             $nodir_name =~ s/^(dist|nodist)_//;
7780           }
7782         # Append actual contents of where_PRIMARY variable to
7783         # result.
7784         foreach my $rcurs (&variable_value_as_list_recursive ($one_name, 'all'))
7785           {
7786             # Skip configure substitutions.  Possibly bogus.
7787             if ($rcurs =~ /^\@.*\@$/)
7788               {
7789                 if ($nodir_name eq 'EXTRA')
7790                   {
7791                     if (! $warned_about_extra)
7792                       {
7793                         $warned_about_extra = 1;
7794                         macro_error ($one_name,
7795                                      "`$one_name' contains configure substitution, but shouldn't");
7796                       }
7797                   }
7798                 # Check here to make sure variables defined in
7799                 # configure.ac do not imply that EXTRA_PRIMARY
7800                 # must be defined.
7801                 elsif (! defined $configure_vars{$one_name})
7802                   {
7803                     $require_extra = $one_name
7804                       if $do_require;
7805                   }
7807                 next;
7808               }
7810             push (@result, $rcurs);
7811           }
7813         # A blatant hack: we rewrite each _PROGRAMS primary to include
7814         # EXEEXT.
7815         append_exeext ($one_name)
7816           if $primary eq 'PROGRAMS';
7818         # "EXTRA" shouldn't be used when generating clean targets,
7819         # all, or install targets.  We used to warn if EXTRA_FOO was
7820         # defined uselessly, but this was annoying.
7821         next
7822           if $nodir_name eq 'EXTRA';
7824         if ($nodir_name eq 'check')
7825           {
7826             push (@check, '$(' . $one_name . ')');
7827           }
7828         else
7829           {
7830             push (@used, '$(' . $one_name . ')');
7831           }
7833         # Is this to be installed?
7834         my $install_p = $nodir_name ne 'noinst' && $nodir_name ne 'check';
7836         # If so, with install-exec? (or install-data?).
7837         my $exec_p = ($nodir_name =~ /$EXEC_DIR_PATTERN/o);
7839         # Singular form of $PRIMARY.
7840         (my $one_primary = $primary) =~ s/S$//;
7841         $output_rules .= &file_contents ($file,
7842                                          ('FIRST' => $first,
7844                                           'PRIMARY'     => $primary,
7845                                           'ONE_PRIMARY' => $one_primary,
7846                                           'DIR'         => $X,
7847                                           'NDIR'        => $nodir_name,
7848                                           'BASE'        => $strip_subdir,
7850                                           'EXEC'    => $exec_p,
7851                                           'INSTALL' => $install_p,
7852                                           'DIST'    => $dist_p));
7854         $first = 0;
7855     }
7857     # The JAVA variable is used as the name of the Java interpreter.
7858     # The PYTHON variable is used as the name of the Python interpreter.
7859     if (@used && $primary ne 'JAVA' && $primary ne 'PYTHON')
7860     {
7861         # Define it.
7862         define_pretty_variable ($primary, '', @used);
7863         $output_vars .= "\n";
7864     }
7866     if ($require_extra && ! variable_defined ('EXTRA_' . $primary))
7867     {
7868         macro_error ($require_extra,
7869                      "`$require_extra' contains configure substitution, but `EXTRA_$primary' not defined");
7870     }
7872     # Push here because PRIMARY might be configure time determined.
7873     push (@all, '$(' . $primary . ')')
7874         if @used && $primary ne 'JAVA' && $primary ne 'PYTHON';
7876     # Make the result unique.  This lets the user use conditionals in
7877     # a natural way, but still lets us program lazily -- we don't have
7878     # to worry about handling a particular object more than once.
7879     return uniq (sort @result);
7883 ################################################################
7885 # Each key in this hash is the name of a directory holding a
7886 # Makefile.in.  These variables are local to `is_make_dir'.
7887 my %make_dirs = ();
7888 my $make_dirs_set = 0;
7890 sub is_make_dir
7892     my ($dir) = @_;
7893     if (! $make_dirs_set)
7894     {
7895         foreach my $iter (@configure_input_files)
7896         {
7897             $make_dirs{dirname ($iter)} = 1;
7898         }
7899         # We also want to notice Makefile.in's.
7900         foreach my $iter (@other_input_files)
7901         {
7902             if ($iter =~ /Makefile\.in$/)
7903             {
7904                 $make_dirs{dirname ($iter)} = 1;
7905             }
7906         }
7907         $make_dirs_set = 1;
7908     }
7909     return defined $make_dirs{$dir};
7912 ################################################################
7914 # This variable is local to the "require file" set of functions.
7915 my @require_file_paths = ();
7917 # If a file name appears as a key in this hash, then it has already
7918 # been checked for.  This variable is local to the "require file"
7919 # functions.
7920 %require_file_found = ();
7923 # &maybe_push_required_file ($DIR, $FILE, $FULLFILE)
7924 # --------------------------------------------------
7925 # See if we want to push this file onto dist_common.  This function
7926 # encodes the rules for deciding when to do so.
7927 sub maybe_push_required_file
7929     my ($dir, $file, $fullfile) = @_;
7931     if ($dir eq $relative_dir)
7932     {
7933         push_dist_common ($file);
7934         return 1;
7935     }
7936     elsif ($relative_dir eq '.' && ! &is_make_dir ($dir))
7937     {
7938         # If we are doing the topmost directory, and the file is in a
7939         # subdir which does not have a Makefile, then we distribute it
7940         # here.
7941         push_dist_common ($fullfile);
7942         return 1;
7943     }
7944     return 0;
7948 # &require_file_internal ($WHERE, $MYSTRICT, @FILES)
7949 # --------------------------------------------------
7950 # Verify that the file must exist in the current directory.
7951 # $MYSTRICT is the strictness level at which this file becomes required.
7953 # Must set require_file_paths before calling this function.
7954 # require_file_paths is set to hold a single directory (the one in
7955 # which the first file was found) before return.
7956 sub require_file_internal ($$@)
7958     my ($where, $mystrict, @files) = @_;
7960     foreach my $file (@files)
7961     {
7962         my $fullfile;
7963         my $errdir;
7964         my $errfile;
7965         my $save_dir;
7967         my $found_it = 0;
7968         my $dangling_sym = 0;
7969         foreach my $dir (@require_file_paths)
7970         {
7971             $fullfile = $dir . "/" . $file;
7972             $errdir = $dir unless $errdir;
7974             # Use different name for "error filename".  Otherwise on
7975             # an error the bad file will be reported as eg
7976             # `../../install-sh' when using the default
7977             # config_aux_path.
7978             $errfile = $errdir . '/' . $file;
7980             if (-l $fullfile && ! -f $fullfile)
7981             {
7982                 $dangling_sym = 1;
7983                 last;
7984             }
7985             elsif (-f $fullfile)
7986             {
7987                 $found_it = 1;
7988                 maybe_push_required_file ($dir, $file, $fullfile);
7989                 $save_dir = $dir;
7990                 last;
7991             }
7992         }
7994         # `--force-missing' only has an effect if `--add-missing' is
7995         # specified.
7996         if ($found_it && (! $add_missing || ! $force_missing))
7997         {
7998             # Prune the path list.
7999             @require_file_paths = $save_dir;
8000         }
8001         else
8002         {
8003             # If we've already looked for it, we're done.  You might
8004             # wonder why we don't do this before searching for the
8005             # file.  If we do that, then something like
8006             # AC_OUTPUT(subdir/foo foo) will fail to put foo.in into
8007             # DIST_COMMON.
8008             if (! $found_it)
8009             {
8010                 next if defined $require_file_found{$file};
8011                 $require_file_found{$file} = 1;
8012             }
8014             if ($strictness >= $mystrict)
8015             {
8016                 if ($dangling_sym && $add_missing)
8017                 {
8018                     unlink ($fullfile);
8019                 }
8021                 my $trailer = '';
8022                 my $suppress = 0;
8024                 # Only install missing files according to our desired
8025                 # strictness level.
8026                 my $message = "required file `$errfile' not found";
8027                 if ($add_missing)
8028                 {
8029                     $suppress = 1;
8031                     if (-f ("$libdir/$file"))
8032                     {
8033                         # Install the missing file.  Symlink if we
8034                         # can, copy if we must.  Note: delete the file
8035                         # first, in case it is a dangling symlink.
8036                         $message = "installing `$errfile'";
8037                         # Windows Perl will hang if we try to delete a
8038                         # file that doesn't exist.
8039                         unlink ($errfile) if -f $errfile;
8040                         if ($symlink_exists && ! $copy_missing)
8041                         {
8042                             if (! symlink ("$libdir/$file", $errfile))
8043                             {
8044                                 $suppress = 0;
8045                                 $trailer = "; error while making link: $!";
8046                             }
8047                         }
8048                         elsif (system ('cp', "$libdir/$file", $errfile))
8049                         {
8050                             $suppress = 0;
8051                             $trailer = "\n    error while copying";
8052                         }
8053                     }
8055                     if (! maybe_push_required_file (dirname ($errfile),
8056                                                     $file, $errfile))
8057                     {
8058                         if (! $found_it)
8059                         {
8060                             # We have added the file but could not push it
8061                             # into DIST_COMMON (probably because this is
8062                             # an auxiliary file and we are not processing
8063                             # the top level Makefile). This is unfortunate,
8064                             # since it means we are using a file which is not
8065                             # distributed!
8067                             # Get Automake to be run again: on the second
8068                             # run the file will be found, and pushed into
8069                             # the toplevel DIST_COMMON automatically.
8070                             $automake_needs_to_reprocess_all_files = 1;
8071                         }
8072                     }
8074                     # Prune the path list.
8075                     @require_file_paths = &dirname ($errfile);
8076                 }
8078                 # If --force-missing was specified, and we have
8079                 # actually found the file, then do nothing.
8080                 next
8081                     if $found_it && $force_missing;
8083                 if ($suppress)
8084                 {
8085                   file_warning ($where, "$message$trailer");
8086                 }
8087                 else
8088                 {
8089                   file_error ($where, "$message$trailer");
8090                 }
8091             }
8092         }
8093     }
8096 # &require_file ($WHERE, $MYSTRICT, @FILES)
8097 # -----------------------------------------
8098 sub require_file ($$@)
8100     my ($where, $mystrict, @files) = @_;
8101     @require_file_paths = $relative_dir;
8102     require_file_internal ($where, $mystrict, @files);
8105 # &require_file_with_macro ($MACRO, $MYSTRICT, @FILES)
8106 # ----------------------------------------------------
8107 sub require_file_with_macro ($$@)
8109     my ($macro, $mystrict, @files) = @_;
8110     require_file ($var_location{$macro}, $mystrict, @files);
8114 # &require_conf_file ($WHERE, $MYSTRICT, @FILES)
8115 # ----------------------------------------------
8116 # Looks in configuration path, as specified by AC_CONFIG_AUX_DIR.
8117 sub require_conf_file ($$@)
8119     my ($where, $mystrict, @files) = @_;
8120     @require_file_paths = @config_aux_path;
8121     require_file_internal ($where, $mystrict, @files);
8122     my $dir = $require_file_paths[0];
8123     @config_aux_path = @require_file_paths;
8124      # Avoid unsightly '/.'s.
8125     $config_aux_dir = '$(top_srcdir)' . ($dir eq '.' ? "" : "/$dir");
8129 # &require_conf_file_with_macro ($MACRO, $MYSTRICT, @FILES)
8130 # ---------------------------------------------------------
8131 sub require_conf_file_with_macro ($$@)
8133     my ($macro, $mystrict, @files) = @_;
8134     require_conf_file ($var_location{$macro}, $mystrict, @files);
8137 ################################################################
8139 # &require_build_directory ($DIRECTORY)
8140 # ------------------------------------
8141 # Emit rules to create $DIRECTORY if needed, and return
8142 # the file that any target requiring this directory should be made
8143 # dependent upon.
8144 sub require_build_directory ($)
8146     my $directory = shift;
8147     my $dirstamp = "$directory/.dirstamp";
8149     # Don't emit the rule twice.
8150     if (! defined $directory_map{$directory})
8151     {
8152         $directory_map{$directory} = 1;
8154         # Directory must be removed by `make distclean'.
8155         $compile_clean_files{$dirstamp} = DIST_CLEAN;
8157         $output_rules .= ("$dirstamp:\n"
8158                           . "\t\@\$(mkinstalldirs) $directory\n"
8159                           . "\t\@: > $dirstamp\n");
8160     }
8162     return $dirstamp;
8165 # &require_build_directory_maybe ($FILE)
8166 # --------------------------------------
8167 # If $FILE lies in a subdirectory, emit a rule to create this
8168 # directory and return the file that $FILE should be made
8169 # dependent upon.  Otherwise, just return the empty string.
8170 sub require_build_directory_maybe ($)
8172     my $file = shift;
8173     my $directory = dirname ($file);
8175     if ($directory ne '.')
8176     {
8177         return require_build_directory ($directory);
8178     }
8179     else
8180     {
8181         return '';
8182     }
8185 ################################################################
8187 # Push a list of files onto dist_common.
8188 sub push_dist_common
8190     prog_error ("push_dist_common run after handle_dist")
8191         if $handle_dist_run;
8192     macro_define ('DIST_COMMON', 1, '+', '', "@_", '');
8196 # Set strictness.
8197 sub set_strictness
8199     $strictness_name = $_[0];
8200     if ($strictness_name eq 'gnu')
8201     {
8202         $strictness = GNU;
8203     }
8204     elsif ($strictness_name eq 'gnits')
8205     {
8206         $strictness = GNITS;
8207     }
8208     elsif ($strictness_name eq 'foreign')
8209     {
8210         $strictness = FOREIGN;
8211     }
8212     else
8213     {
8214         die "$me: level `$strictness_name' not recognized\n";
8215     }
8219 ################################################################
8221 # Ensure a file exists.
8222 sub create
8224     use IO::File;
8225     my ($file) = @_;
8227     my $touch = new IO::File (">> $file");
8228     $touch->close;
8232 # Glob something.  Do this to avoid indentation screwups everywhere we
8233 # want to glob.  Gross!
8234 sub my_glob
8236     my ($pat) = @_;
8237     return <${pat}>;
8240 # Remove one level of brackets and strip leading spaces,
8241 # as does m4 to function arguments.
8242 sub unquote_m4_arg
8244     $_ = shift;
8245     s/^\s*//;
8247     my @letters = split //;
8248     my @result = ();
8249     my $depth = 0;
8251     foreach (@letters)
8252     {
8253         if ($_ eq '[')
8254         {
8255             ++$depth;
8256             next if $depth == 1;
8257         }
8258         elsif ($_ eq ']')
8259         {
8260             --$depth;
8261             next if $depth == 0;
8262             # don't count orphan right brackets
8263             $depth = 0 if $depth < 0;
8264         }
8265         push @result, $_;
8266     }
8267     return join '', @result;
8270 ################################################################
8272 # print_error ($LEADER, @ARGS)
8273 # ----------------------------
8274 # Do the work of printing the error message.  Join @ARGS with spaces,
8275 # then split at newlines and add $LEADER to each line.  Uses `warn' to
8276 # print message.  Set exit status.
8277 sub print_error
8279     my ($leader, @args) = @_;
8280     my $text = "@args";
8281     @args = split ("\n", $text);
8282     $text = $leader . join ("\n" . $leader, @args) . "\n";
8283     warn $text;
8284     $exit_status = 1;
8288 # Print an error message and set exit status.
8289 sub am_error (@)
8291     print_error ("$me: ${am_file}.am: ", @_);
8295 # &file_error ($FILE, @ARGS)
8296 # --------------------------
8297 sub file_error ($@)
8299     my ($file, @args) = @_;
8300     print_error ("$file: ", @args);
8304 # &macro_error ($MACRO, @ARGS)
8305 # ----------------------------
8306 # Report an error, @ARGS, about $MACRO.
8307 sub macro_error ($@)
8309     my ($macro, @args) = @_;
8310     file_error ($var_location{$macro}, @args);
8314 # &target_error ($TARGET, @ARGS)
8315 # ------------------------------
8316 # Report an error, @ARGS, about the rule $TARGET.
8317 sub target_error ($@)
8319     my ($target, @args) = @_;
8320     file_error ($targets{$target}, @args);
8324 # Like am_error, but while scanning configure.ac.
8325 sub conf_error
8327     # FIXME: can run in subdirs.
8328     print_error ("$me: $configure_ac: ", @_);
8331 # &file_warning ($FILE, @ARGS)
8332 # ----------------------------
8333 # Warning message with line number referring to configure.ac.
8334 # Does not affect exit_status
8335 sub file_warning ($@)
8337     my ($file, @args) = @_;
8339     my $saved_exit_status = $exit_status;
8340     my $sig = $SIG{'__WARN__'};
8341     $SIG{'__WARN__'} = 'DEFAULT';
8342     file_error ($file, @args);
8343     $exit_status = $saved_exit_status;
8344     $SIG{'__WARN__'} = $sig;
8347 # Tell user where our aclocal.m4 is, but only once.
8348 sub keyed_aclocal_warning ($)
8350     my ($key) = @_;
8351     warn "$me: macro `$key' can be generated by `aclocal'\n";
8354 # Print usage information.
8355 sub usage ()
8357     print <<EOF;
8358 Usage: $0 [OPTION] ... [Makefile]...
8360 Generate Makefile.in for configure from Makefile.am.
8362 Operation modes:
8363       --help             print this help, then exit
8364       --version          print version number, then exit
8365   -v, --verbose          verbosely list files processed
8366   -o, --output-dir=DIR   put generated Makefile.in's into DIR
8367       --no-force         only update Makefile.in's that are out of date
8369 Dependency tracking:
8370   -i, --ignore-deps      disable dependency tracking code
8371       --include-deps     enable dependency tracking code
8373 Flavors:
8374       --cygnus           assume program is part of Cygnus-style tree
8375       --foreign          set strictness to foreign
8376       --gnits            set strictness to gnits
8377       --gnu              set strictness to gnu
8379 Library files:
8380   -a, --add-missing      add missing standard files to package
8381       --libdir=DIR       directory storing library files
8382   -c, --copy             with -a, copy missing files (default is symlink)
8383   -f, --force-missing    force update of standard files
8386     my ($last, @lcomm);
8387     $last = '';
8388     foreach my $iter (sort ((@common_files, @common_sometimes)))
8389     {
8390         push (@lcomm, $iter) unless $iter eq $last;
8391         $last = $iter;
8392     }
8394     my @four;
8395     print "\nFiles which are automatically distributed, if found:\n";
8396     format USAGE_FORMAT =
8397   @<<<<<<<<<<<<<<<<   @<<<<<<<<<<<<<<<<   @<<<<<<<<<<<<<<<<   @<<<<<<<<<<<<<<<<
8398   $four[0],           $four[1],           $four[2],           $four[3]
8400     $~ = "USAGE_FORMAT";
8402     my $cols = 4;
8403     my $rows = int(@lcomm / $cols);
8404     my $rest = @lcomm % $cols;
8406     if ($rest)
8407     {
8408         $rows++;
8409     }
8410     else
8411     {
8412         $rest = $cols;
8413     }
8415     for (my $y = 0; $y < $rows; $y++)
8416     {
8417         @four = ("", "", "", "");
8418         for (my $x = 0; $x < $cols; $x++)
8419         {
8420             last if $y + 1 == $rows && $x == $rest;
8422             my $idx = (($x > $rest)
8423                        ?  ($rows * $rest + ($rows - 1) * ($x - $rest))
8424                        : ($rows * $x));
8426             $idx += $y;
8427             $four[$x] = $lcomm[$idx];
8428         }
8429         write;
8430     }
8432     print "\nReport bugs to <bug-automake\@gnu.org>.\n";
8434     exit 0;
8438 # &version ()
8439 # -----------
8440 # Print version information
8441 sub version ()
8443   print <<EOF;
8444 automake (GNU $PACKAGE) $VERSION
8445 Written by Tom Tromey <tromey\@redhat.com>.
8447 Copyright 2002 Free Software Foundation, Inc.
8448 This is free software; see the source for copying conditions.  There is NO
8449 warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
8451   exit 0;