For PR automake/358:
[platform/upstream/automake.git] / automake.in
1 #!@PERL@ -w
2 # -*- perl -*-
3 # @configure_input@
4
5 eval 'case $# in 0) exec @PERL@ -S "$0";; *) exec @PERL@ -S "$0" "$@";; esac'
6     if 0;
7
8 # automake - create Makefile.in from Makefile.am
9 # Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002
10 # Free Software Foundation, Inc.
11
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.
16
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.
21
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.
26
27 # Originally written by David Mackenzie <djm@gnu.ai.mit.edu>.
28 # Perl reimplementation by Tom Tromey <tromey@redhat.com>.
29
30 package Language;
31
32 BEGIN
33 {
34   my $perllibdir = $ENV{'perllibdir'} || '@datadir@/@PACKAGE@-@APIVERSION@';
35   unshift @INC, $perllibdir;
36 }
37
38 use Automake::Struct;
39 struct (# Short name of the language (c, f77...).
40         'name' => "\$",
41         # Nice name of the language (C, Fortran 77...).
42         'Name' => "\$",
43
44         # List of configure variables which must be defined.
45         'config_vars' => '@',
46
47         'ansi'    => "\$",
48         # `pure' is `1' or `'.  A `pure' language is one where, if
49         # all the files in a directory are of that language, then we
50         # do not require the C compiler or any code to call it.
51         'pure'   => "\$",
52
53         'autodep' => "\$",
54
55         # Name of the compiling variable (COMPILE).
56         'compiler'  => "\$",
57         # Content of the compiling variable.
58         'compile'  => "\$",
59         # Flag to require compilation without linking (-c).
60         'compile_flag' => "\$",
61         'extensions' => '@',
62         # A subroutine to compute a list of possible extensions of
63         # the product given the input extensions.
64         # (defaults to a subroutine which returns ('.$(OBJEXT)', '.lo'))
65         'output_extensions' => "\$",
66         # A list of flag variables used in 'compile'.
67         # (defaults to [])
68         'flags' => "@",
69
70         # The file to use when generating rules for this language.
71         # The default is 'depend2'.
72         'rule_file' => "\$",
73
74         # Name of the linking variable (LINK).
75         'linker' => "\$",
76         # Content of the linking variable.
77         'link' => "\$",
78
79         # Name of the linker variable (LD).
80         'lder' => "\$",
81         # Content of the linker variable ($(CC)).
82         'ld' => "\$",
83
84         # Flag to specify the output file (-o).
85         'output_flag' => "\$",
86         '_finish' => "\$",
87
88         # This is a subroutine which is called whenever we finally
89         # determine the context in which a source file will be
90         # compiled.
91         '_target_hook' => "\$");
92
93
94 sub finish ($)
95 {
96   my ($self) = @_;
97   if (defined $self->_finish)
98     {
99       &{$self->_finish} ();
100     }
101 }
102
103 sub target_hook ($$$$)
104 {
105     my ($self) = @_;
106     if (defined $self->_target_hook)
107     {
108         &{$self->_target_hook} (@_);
109     }
110 }
111
112 package Automake;
113
114 use strict 'vars', 'subs';
115 use Automake::General;
116 use Automake::XFile;
117 use Automake::Channels;
118 use Automake::Location;
119 use Automake::Conditional;
120 use File::Basename;
121 use Tie::RefHash;
122 use Carp;
123
124 ## ----------- ##
125 ## Constants.  ##
126 ## ----------- ##
127
128 # Parameters set by configure.  Not to be changed.  NOTE: assign
129 # VERSION as string so that eg version 0.30 will print correctly.
130 my $VERSION = '@VERSION@';
131 my $PACKAGE = '@PACKAGE@';
132 my $libdir = '@datadir@/@PACKAGE@-@APIVERSION@';
133
134 # Some regular expressions.  One reason to put them here is that it
135 # makes indentation work better in Emacs.
136
137 # Writting singled-quoted-$-terminated regexes is a pain because
138 # perl-mode thinks of $' as the ${'} variable (intead of a $ followed
139 # by a closing quote.  Letting perl-mode think the quote is not closed
140 # leads to all sort of misindentations.  On the other hand, defining
141 # regexes as double-quoted strings is far less readable.  So usually
142 # we will write:
143 #
144 #  $REGEX = '^regex_value' . "\$";
145
146 my $IGNORE_PATTERN = '^\s*##([^#\n].*)?\n';
147 my $WHITE_PATTERN = '^\s*' . "\$";
148 my $COMMENT_PATTERN = '^#';
149 my $TARGET_PATTERN='[$a-zA-Z_.@%][-.a-zA-Z0-9_(){}/$+@%]*';
150 # A rule has three parts: a list of targets, a list of dependencies,
151 # and optionally actions.
152 my $RULE_PATTERN =
153   "^($TARGET_PATTERN(?:(?:\\\\\n|\\s)+$TARGET_PATTERN)*) *:([^=].*|)\$";
154
155 my $SUFFIX_RULE_PATTERN =
156     '^(\.[a-zA-Z0-9_(){}$+@]+)(\.[a-zA-Z0-9_(){}$+@]+)' . "\$";
157 # Only recognize leading spaces, not leading tabs.  If we recognize
158 # leading tabs here then we need to make the reader smarter, because
159 # otherwise it will think rules like `foo=bar; \' are errors.
160 my $MACRO_PATTERN = '^[.A-Za-z0-9_@]+' . "\$";
161 my $ASSIGNMENT_PATTERN = '^ *([^ \t=:+]*)\s*([:+]?)=\s*(.*)' . "\$";
162 # This pattern recognizes a Gnits version id and sets $1 if the
163 # release is an alpha release.  We also allow a suffix which can be
164 # used to extend the version number with a "fork" identifier.
165 my $GNITS_VERSION_PATTERN = '\d+\.\d+([a-z]|\.\d+)?(-[A-Za-z0-9]+)?';
166
167 my $IF_PATTERN = '^if\s+(!?)\s*([A-Za-z][A-Za-z0-9_]*)\s*(?:#.*)?' . "\$";
168 my $ELSE_PATTERN =
169   '^else(?:\s+(!?)\s*([A-Za-z][A-Za-z0-9_]*))?\s*(?:#.*)?' . "\$";
170 my $ENDIF_PATTERN =
171   '^endif(?:\s+(!?)\s*([A-Za-z][A-Za-z0-9_]*))?\s*(?:#.*)?' . "\$";
172 my $PATH_PATTERN = '(\w|[/.-])+';
173 # This will pass through anything not of the prescribed form.
174 my $INCLUDE_PATTERN = ('^include\s+'
175                        . '((\$\(top_srcdir\)/' . $PATH_PATTERN . ')'
176                        . '|(\$\(srcdir\)/' . $PATH_PATTERN . ')'
177                        . '|([^/\$]' . $PATH_PATTERN . '))\s*(#.*)?' . "\$");
178
179 # This handles substitution references like ${foo:.a=.b}.
180 my $SUBST_REF_PATTERN = "^([^:]*):([^=]*)=(.*)\$";
181
182 # Match `-d' as a command-line argument in a string.
183 my $DASH_D_PATTERN = "(^|\\s)-d(\\s|\$)";
184 # Directories installed during 'install-exec' phase.
185 my $EXEC_DIR_PATTERN =
186   '^(?:bin|sbin|libexec|sysconf|localstate|lib|pkglib|.*exec.*)' . "\$";
187
188 # Constants to define the "strictness" level.
189 use constant FOREIGN => 0;
190 use constant GNU     => 1;
191 use constant GNITS   => 2;
192
193 # Values for AC_CANONICAL_*
194 use constant AC_CANONICAL_HOST   => 1;
195 use constant AC_CANONICAL_SYSTEM => 2;
196
197 # Values indicating when something should be cleaned.
198 use constant MOSTLY_CLEAN     => 0;
199 use constant CLEAN            => 1;
200 use constant DIST_CLEAN       => 2;
201 use constant MAINTAINER_CLEAN => 3;
202
203 # Libtool files.
204 my @libtool_files = qw(ltmain.sh config.guess config.sub);
205 # ltconfig appears here for compatibility with old versions of libtool.
206 my @libtool_sometimes = qw(ltconfig ltcf-c.sh ltcf-cxx.sh ltcf-gcj.sh);
207
208 # Commonly found files we look for and automatically include in
209 # DISTFILES.
210 my @common_files =
211     (qw(ABOUT-GNU ABOUT-NLS AUTHORS BACKLOG COPYING COPYING.DOC COPYING.LIB
212         COPYING.LESSER ChangeLog INSTALL NEWS README THANKS TODO acinclude.m4
213         ansi2knr.1 ansi2knr.c compile config.guess config.rpath config.sub
214         configure configure.ac configure.in depcomp elisp-comp
215         install-sh libversion.in mdate-sh missing mkinstalldirs
216         py-compile texinfo.tex ylwrap),
217      @libtool_files, @libtool_sometimes);
218
219 # Commonly used files we auto-include, but only sometimes.
220 my @common_sometimes =
221     qw(aclocal.m4 acconfig.h config.h.top config.h.bot stamp-vti);
222
223 # Standard directories from the GNU Coding Standards, and additional
224 # pkg* directories from Automake.  Stored in a hash for fast member check.
225 my %standard_prefix =
226     map { $_ => 1 } (qw(bin data exec include info lib libexec lisp
227                         localstate man man1 man2 man3 man4 man5 man6
228                         man7 man8 man9 oldinclude pkgdatadir
229                         pkgincludedir pkglibdir sbin sharedstate
230                         sysconf));
231
232 # Declare the macros that define known variables, so we can
233 # hint the user if she try to use one of these variables.
234
235 # Macros accessible via aclocal.
236 my %am_macro_for_var =
237   (
238    ANSI2KNR => 'AM_C_PROTOTYPES',
239    CCAS => 'AM_PROG_AS',
240    CCASFLAGS => 'AM_PROG_AS',
241    EMACS => 'AM_PATH_LISPDIR',
242    GCJ => 'AM_PROG_GCJ',
243    LEX => 'AM_PROG_LEX',
244    LIBTOOL => 'AC_PROG_LIBTOOL',
245    lispdir => 'AM_PATH_LISPDIR',
246    pkgpyexecdir => 'AM_PATH_PYTHON',
247    pkgpythondir => 'AM_PATH_PYTHON',
248    pyexecdir => 'AM_PATH_PYTHON',
249    PYTHON => 'AM_PATH_PYTHON',
250    pythondir => 'AM_PATH_PYTHON',
251    U => 'AM_C_PROTOTYPES',
252    );
253
254 # Macros shipped with Autoconf.
255 my %ac_macro_for_var =
256   (
257    CC => 'AC_PROG_CC',
258    CFLAGS => 'AC_PROG_CC',
259    CXX => 'AC_PROG_CXX',
260    CXXFLAGS => 'AC_PROG_CXX',
261    F77 => 'AC_PROG_F77',
262    F77FLAGS => 'AC_PROG_F77',
263    RANLIB => 'AC_PROG_RANLIB',
264    YACC => 'AC_PROG_YACC',
265    );
266
267 # Copyright on generated Makefile.ins.
268 my $gen_copyright = "\
269 # Copyright 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002
270 # Free Software Foundation, Inc.
271 # This Makefile.in is free software; the Free Software Foundation
272 # gives unlimited permission to copy and/or distribute it,
273 # with or without modifications, as long as this notice is preserved.
274
275 # This program is distributed in the hope that it will be useful,
276 # but WITHOUT ANY WARRANTY, to the extent permitted by law; without
277 # even the implied warranty of MERCHANTABILITY or FITNESS FOR A
278 # PARTICULAR PURPOSE.
279 ";
280
281 # These constants are returned by lang_*_rewrite functions.
282 # LANG_SUBDIR means that the resulting object file should be in a
283 # subdir if the source file is.  In this case the file name cannot
284 # have `..' components.
285 use constant LANG_IGNORE  => 0;
286 use constant LANG_PROCESS => 1;
287 use constant LANG_SUBDIR  => 2;
288
289 # These are used when keeping track of whether an object can be built
290 # by two different paths.
291 use constant COMPILE_LIBTOOL  => 1;
292 use constant COMPILE_ORDINARY => 2;
293
294 # We can't always associate a location to a variable or a rule,
295 # when its defined by Automake.  We use INTERNAL in this case.
296 use constant INTERNAL => new Automake::Location;
297
298 # The TRUE and FALSE conditionals.
299 use constant TRUE => new Automake::Conditional;
300 use constant FALSE => new Automake::Conditional "FALSE";
301 \f
302
303 ## ---------------------------------- ##
304 ## Variables related to the options.  ##
305 ## ---------------------------------- ##
306
307 # TRUE if we should always generate Makefile.in.
308 my $force_generation = 1;
309
310 # Strictness level as set on command line.
311 my $default_strictness = GNU;
312
313 # Name of strictness level, as set on command line.
314 my $default_strictness_name = 'gnu';
315
316 # This is TRUE if automatic dependency generation code should be
317 # included in generated Makefile.in.
318 my $cmdline_use_dependencies = 1;
319
320 # From the Perl manual.
321 my $symlink_exists = (eval 'symlink ("", "");', $@ eq '');
322
323 # TRUE if missing standard files should be installed.
324 my $add_missing = 0;
325
326 # TRUE if we should copy missing files; otherwise symlink if possible.
327 my $copy_missing = 0;
328
329 # TRUE if we should always update files that we know about.
330 my $force_missing = 0;
331
332
333 ## ---------------------------------------- ##
334 ## Variables filled during files scanning.  ##
335 ## ---------------------------------------- ##
336
337 # Name of the top autoconf input: `configure.ac' or `configure.in'.
338 my $configure_ac = '';
339
340 # Files found by scanning configure.ac for LIBOBJS.
341 my %libsources = ();
342
343 # Names used in AC_CONFIG_HEADER call.
344 my @config_headers = ();
345 # Where AC_CONFIG_HEADER appears.
346 my $config_header_location;
347
348 # Directory where output files go.  Actually, output files are
349 # relative to this directory.
350 my $output_directory;
351
352 # List of Makefile.am's to process, and their corresponding outputs.
353 my @input_files = ();
354 my %output_files = ();
355
356 # Complete list of Makefile.am's that exist.
357 my @configure_input_files = ();
358
359 # List of files in AC_CONFIG_FILES/AC_OUTPUT without Makefile.am's,
360 # and their outputs.
361 my @other_input_files = ();
362 # Where the last AC_CONFIG_FILES/AC_OUTPUT appears.
363 my $ac_config_files_location;
364
365 # List of directories to search for configure-required files.  This
366 # can be set by AC_CONFIG_AUX_DIR.
367 my @config_aux_path = qw(. .. ../..);
368 my $config_aux_dir = '';
369 my $config_aux_dir_set_in_configure_in = 0;
370
371 # Whether AM_GNU_GETTEXT has been seen in configure.ac.
372 my $seen_gettext = 0;
373 # Whether AM_GNU_GETTEXT([external]) is used.
374 my $seen_gettext_external = 0;
375 # Where AM_GNU_GETTEXT appears.
376 my $ac_gettext_location;
377
378 # TRUE if we've seen AC_CANONICAL_(HOST|SYSTEM).
379 my $seen_canonical = 0;
380 my $canonical_location;
381
382 # Where AM_MAINTAINER_MODE appears.
383 my $seen_maint_mode;
384
385 # Actual version we've seen.
386 my $package_version = '';
387
388 # Where version is defined.
389 my $package_version_location;
390
391 # TRUE if we've seen AC_ENABLE_MULTILIB.
392 my $seen_multilib = 0;
393
394 # TRUE if we've seen AM_PROG_CC_C_O
395 my $seen_cc_c_o = 0;
396
397 # Where AM_INIT_AUTOMAKE is called;
398 my $seen_init_automake = 0;
399
400 # TRUE if we've seen AM_AUTOMAKE_VERSION.
401 my $seen_automake_version = 0;
402
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 = ();
407
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 = ();
412
413 # TRUE if --cygnus seen.
414 my $cygnus_mode = 0;
415
416 # Files included by @configure.
417 my @configure_deps = ();
418
419 # Hash table of AM_CONDITIONAL variables seen in configure.
420 my %configure_cond = ();
421
422 # This maps extensions onto language names.
423 my %extension_map = ();
424
425 # List of the DIST_COMMON files we discovered while reading
426 # configure.in
427 my $configure_dist_common = '';
428
429 # This maps languages names onto objects.
430 my %languages = ();
431
432 # List of targets we must always output.
433 # FIXME: Complete, and remove falsely required targets.
434 my %required_targets =
435   (
436    'all'          => 1,
437    'dvi'          => 1,
438    'pdf'          => 1,
439    'ps'           => 1,
440    'info'         => 1,
441    'install-info' => 1,
442    'install'      => 1,
443    'install-data' => 1,
444    'install-exec' => 1,
445    'uninstall'    => 1,
446
447    # FIXME: Not required, temporary hacks.
448    # Well, actually they are sort of required: the -recursive
449    # targets will run them anyway...
450    'dvi-am'          => 1,
451    'pdf-am'          => 1,
452    'ps-am'           => 1,
453    'info-am'         => 1,
454    'install-data-am' => 1,
455    'install-exec-am' => 1,
456    'installcheck-am' => 1,
457    'uninstall-am' => 1,
458
459    'install-man' => 1,
460   );
461
462 # This is set to 1 when Automake needs to be run again.
463 # (For instance, this happens when an auxiliary file such as
464 # depcomp is added after the toplevel Makefile.in -- which
465 # should distribute depcomp -- has been generated.)
466 my $automake_needs_to_reprocess_all_files = 0;
467
468 # Options set via AM_INIT_AUTOMAKE.
469 my $global_options = '';
470
471 # Same as $suffix_rules (declared below), but records only the
472 # default rules supplied by the languages Automake supports.
473 my $suffix_rules_default;
474
475 # If a file name appears as a key in this hash, then it has already
476 # been checked for.  This variable is local to the "require file"
477 # functions.
478 my %require_file_found = ();
479 \f
480
481 ################################################################
482
483 ## ------------------------------------------ ##
484 ## Variables reset by &initialize_per_input.  ##
485 ## ------------------------------------------ ##
486
487 # Basename and relative dir of the input file.
488 my $am_file_name;
489 my $am_relative_dir;
490
491 # Same but wrt Makefile.in.
492 my $in_file_name;
493 my $relative_dir;
494
495 # These two variables are used when generating each Makefile.in.
496 # They hold the Makefile.in until it is ready to be printed.
497 my $output_rules;
498 my $output_vars;
499 my $output_trailer;
500 my $output_all;
501 my $output_header;
502
503 # Suffixes found during a run.
504 my @suffixes;
505
506 # Handling the variables.
507 #
508 # For a $VAR:
509 # - $var_value{$VAR}{$COND} is its value associated to $COND,
510 # - $var_location{$VAR}{$COND} is where it was defined,
511 # - $var_comment{$VAR}{$COND} are the comments associated to it.
512 # - $var_type{$VAR}{$COND} is how it has been defined (`', `+', or `:'),
513 # - $var_owner{$VAR}{$COND} tells who owns the variable (VAR_AUTOMAKE,
514 #     VAR_CONFIGURE, or VAR_MAKEFILE).
515 my %var_value;    tie %var_value, 'Tie::RefHash::Nestable';
516 my %var_location; tie %var_location, 'Tie::RefHash::Nestable';
517 my %var_comment;  tie %var_comment, 'Tie::RefHash::Nestable';
518 my %var_type;     tie %var_type, 'Tie::RefHash::Nestable';
519 my %var_owner;    tie %var_owner, 'Tie::RefHash::Nestable';
520 # Possible values for var_owner.  Defined so that the owner of
521 # a variable can only be increased (e.g Automake should not
522 # override a configure or Makefile variable).
523 use constant VAR_AUTOMAKE => 0; # Variable defined by Automake.
524 use constant VAR_CONFIGURE => 1;# Variable defined in configure.ac.
525 use constant VAR_MAKEFILE => 2; # Variable defined in Makefile.am.
526
527 # This holds a 1 if a particular variable was examined.
528 my %content_seen;
529
530 # This holds the names which are targets.  These also appear in
531 # %contents.  $targets{TARGET}{COND} is the location of the definition
532 # of TARGET for condition COND.  TARGETs should not include
533 # a trailing $(EXEEXT), we record this in %target_name.
534 my %targets;       tie %targets, 'Tie::RefHash::Nestable';
535
536 # $target_source{TARGET}{COND} is the filename where TARGET
537 # were defined for condition COND.  Note this must be a
538 # filename, *without* any line number.
539 my %target_source; tie %target_source, 'Tie::RefHash::Nestable';
540
541 # $target_name{TARGET}{COND} is the real name of TARGET (in condition COND).
542 # The real name is often TARGET or TARGET$(EXEEXT), and TARGET never
543 # contain $(EXEEXT)
544 my %target_name;   tie %target_name, 'Tie::RefHash::Nestable';
545
546 # $target_owner{TARGET}{COND} the owner of TARGET in condition COND.
547 my %target_owner;  tie %target_owner, 'Tie::RefHash::Nestable';
548 use constant TARGET_AUTOMAKE => 0; # Target defined by Automake.
549 use constant TARGET_USER => 1;  # Target defined in the user's Makefile.am.
550
551 # This is the conditional stack.
552 my @cond_stack;
553
554 # This holds the set of included files.
555 my @include_stack;
556
557 # This holds a list of directories which we must create at `dist'
558 # time.  This is used in some strange scenarios involving weird
559 # AC_OUTPUT commands.
560 my %dist_dirs;
561
562 # List of dependencies for the obvious targets.
563 my @all;
564 my @check;
565 my @check_tests;
566
567 # Holds the dependencies of targets which dependencies are factored.
568 # Typically, `.PHONY' will appear in plenty of *.am files, but must
569 # be output once.  Arguably all pure dependencies could be subject
570 # to this factorization, but it is not unpleasant to have paragraphs
571 # in Makefile: keeping related stuff altogether.
572 my %dependencies;
573
574 # Holds the factored actions.  Tied to %DEPENDENCIES, i.e., filled
575 # only when keys exists in %DEPENDENCIES.
576 my %actions;
577
578 # Keys in this hash table are files to delete.  The associated
579 # value tells when this should happen (MOSTLY_CLEAN, DIST_CLEAN, etc.)
580 my %clean_files;
581
582 # Keys in this hash table are object files or other files in
583 # subdirectories which need to be removed.  This only holds files
584 # which are created by compilations.  The value in the hash indicates
585 # when the file should be removed.
586 my %compile_clean_files;
587
588 # Keys in this hash table are directories where we expect to build a
589 # libtool object.  We use this information to decide what directories
590 # to delete.
591 my %libtool_clean_directories;
592
593 # Value of `$(SOURCES)', used by tags.am.
594 my @sources;
595 # Sources which go in the distribution.
596 my @dist_sources;
597
598 # This hash maps object file names onto their corresponding source
599 # file names.  This is used to ensure that each object is created
600 # by a single source file.
601 my %object_map;
602
603 # This hash maps object file names onto an integer value representing
604 # whether this object has been built via ordinary compilation or
605 # libtool compilation (the COMPILE_* constants).
606 my %object_compilation_map;
607
608
609 # This keeps track of the directories for which we've already
610 # created `.dirstamp' code.
611 my %directory_map;
612
613 # All .P files.
614 my %dep_files;
615
616 # Strictness levels.
617 my $strictness;
618 my $strictness_name;
619
620 # Options from AUTOMAKE_OPTIONS.
621 my %options;
622
623 # Whether or not dependencies are handled.  Can be further changed
624 # in handle_options.
625 my $use_dependencies;
626
627 # This is a list of all targets to run during "make dist".
628 my @dist_targets;
629
630 # Keys in this hash are the basenames of files which must depend on
631 # ansi2knr.  Values are either the empty string, or the directory in
632 # which the ANSI source file appears; the directory must have a
633 # trailing `/'.
634 my %de_ansi_files;
635
636 # This maps the source extension for all suffix rule seen to
637 # a \hash whose keys are the possible output extensions.
638 #
639 # Note that this is transitively closed by construction:
640 # if we have
641 #       exists $suffix_rules{$ext1}{$ext2}
642 #    && exists $suffix_rules{$ext2}{$ext3}
643 # then we also have
644 #       exists $suffix_rules{$ext1}{$ext3}
645 #
646 # So it's easy to check whether '.foo' can be transformed to '.$(OBJEXT)'
647 # by checking whether $suffix_rules{'.foo'}{'.$(OBJEXT)'} exist.  This
648 # will work even if transforming '.foo' to '.$(OBJEXT)' involves a chain
649 # of several suffix rules.
650 #
651 # The value of `$suffix_rules{$ext1}{$ext2}' is the a pair
652 # `[ $next_sfx, $dist ]' where `$next_sfx' is target suffix
653 # for the next rule to use to reach '$ext2', and `$dist' the
654 # distance to `$ext2'.
655 my $suffix_rules;
656
657 # This is the name of the redirect `all' target to use.
658 my $all_target;
659
660 # This keeps track of which extensions we've seen (that we care
661 # about).
662 my %extension_seen;
663
664 # This is random scratch space for the language finish functions.
665 # Don't randomly overwrite it; examine other uses of keys first.
666 my %language_scratch;
667
668 # We keep track of which objects need special (per-executable)
669 # handling on a per-language basis.
670 my %lang_specific_files;
671
672 # This is set when `handle_dist' has finished.  Once this happens,
673 # we should no longer push on dist_common.
674 my $handle_dist_run;
675
676 # Used to store a set of linkers needed to generate the sources currently
677 # under consideration.
678 my %linkers_used;
679
680 # True if we need `LINK' defined.  This is a hack.
681 my $need_link;
682
683 # This is the list of such variables to output.
684 # FIXME: Might be useless actually.
685 my @var_list;
686
687 # Was get_object_extension run?
688 # FIXME: This is a hack. a better switch should be found.
689 my $get_object_extension_was_run;
690
691 # Contains a stack of `from' parts of variable substitutions currently in
692 # force.
693 my @substfroms;
694
695 # Contains a stack of `to' parts of variable substitutions currently in
696 # force.
697 my @substtos;
698
699 # This keeps track of all variables defined by subobjname.
700 # The value stored is the variable names.
701 # The key has the form "(COND1)VAL1(COND2)VAL2..." where VAL1 and VAL2
702 # are the values of the variable for condition COND1 and COND2.
703 my %subobjvar = ();
704
705 # This hash records helper variables used to implement '+=' in conditionals.
706 # Keys have the form "VAR:CONDITIONS".  The value associated to a key is
707 # the named of the helper variable used to append to VAR in CONDITIONS.
708 my %appendvar = ();
709
710
711 ## --------------------------------- ##
712 ## Forward subroutine declarations.  ##
713 ## --------------------------------- ##
714 sub register_language (%);
715 sub file_contents_internal ($$$%);
716 sub define_objects_from_sources ($$$$$$$$);
717
718
719 # &initialize_per_input ()
720 # ------------------------
721 # (Re)-Initialize per-Makefile.am variables.
722 sub initialize_per_input ()
723 {
724     reset_local_duplicates ();
725
726     $am_file_name = '';
727     $am_relative_dir = '';
728
729     $in_file_name = '';
730     $relative_dir = '';
731
732     $output_rules = '';
733     $output_vars = '';
734     $output_trailer = '';
735     $output_all = '';
736     $output_header = '';
737
738     @suffixes = ();
739
740     %var_value = ();
741     %var_location = ();
742     %var_comment = ();
743     %var_type = ();
744     %var_owner = ();
745
746     %content_seen = ();
747
748     %targets = ();
749     %target_source = ();
750     %target_name = ();
751     %target_owner = ();
752
753     @cond_stack = ();
754
755     @include_stack = ();
756
757     %dist_dirs = ();
758
759     @all = ();
760     @check = ();
761     @check_tests = ();
762
763     %dependencies =
764       (
765        # Texinfoing.
766        'dvi'      => [],
767        'dvi-am'   => [],
768        'pdf'      => [],
769        'pdf-am'   => [],
770        'ps'       => [],
771        'ps-am'    => [],
772        'info'     => [],
773        'info-am'  => [],
774
775        # Installing/uninstalling.
776        'install-data-am'      => [],
777        'install-exec-am'      => [],
778        'uninstall-am'         => [],
779
780        'install-man'          => [],
781        'uninstall-man'        => [],
782
783        'install-info'         => [],
784        'install-info-am'      => [],
785        'uninstall-info'       => [],
786
787        'installcheck-am'      => [],
788
789        # Cleaning.
790        'clean-am'             => [],
791        'mostlyclean-am'       => [],
792        'maintainer-clean-am'  => [],
793        'distclean-am'         => [],
794        'clean'                => [],
795        'mostlyclean'          => [],
796        'maintainer-clean'     => [],
797        'distclean'            => [],
798
799        # Tarballing.
800        'dist-all'             => [],
801
802        # Phoning.
803        '.PHONY'               => []
804       );
805     %actions = ();
806
807     %clean_files = ();
808
809     @sources = ();
810     @dist_sources = ();
811
812     %object_map = ();
813     %object_compilation_map = ();
814
815     %directory_map = ();
816
817     %dep_files = ();
818
819     $strictness = $default_strictness;
820     $strictness_name = $default_strictness_name;
821
822     %options = ();
823
824     $use_dependencies = $cmdline_use_dependencies;
825
826     @dist_targets = ();
827
828     %de_ansi_files = ();
829
830
831     # The first time we initialize the variables,
832     # we save the value of $suffix_rules.
833     if (defined $suffix_rules_default)
834       {
835         $suffix_rules = $suffix_rules_default;
836       }
837     else
838       {
839         $suffix_rules_default = $suffix_rules;
840       }
841
842     $all_target = '';
843
844     %extension_seen = ();
845
846     %language_scratch = ();
847
848     %lang_specific_files = ();
849
850     $handle_dist_run = 0;
851
852     $need_link = 0;
853
854     @var_list = ();
855
856     $get_object_extension_was_run = 0;
857
858     %compile_clean_files = ();
859
860     # We always include `.'.  This isn't strictly correct.
861     %libtool_clean_directories = ('.' => 1);
862
863     %subobjvar = ();
864
865     %appendvar = ();
866 }
867
868
869 ################################################################
870
871 # Initialize our list of error/warning channels.
872 # Do not forget to update &usage and the manual
873 # if you add or change a warning channel.
874
875 # Fatal errors.
876 register_channel 'fatal', type => 'fatal';
877 # Common errors.
878 register_channel 'error', type => 'error';
879 # Errors related to GNU Standards.
880 register_channel 'error-gnu', type => 'error';
881 # Errors related to GNU Standards that should be warnings in `foreign' mode.
882 register_channel 'error-gnu/warn', type => 'error';
883 # Errors related to GNITS Standards (silent by default).
884 register_channel 'error-gnits', type => 'error', silent => 1;
885 # Internal errors.
886 register_channel 'automake', type => 'fatal', backtrace => 1,
887   header => ("####################\n" .
888              "## Internal Error ##\n" .
889              "####################\n"),
890   footer => "\nPlease contact <bug-automake\@gnu.org>.";
891
892 # Warnings related to GNU Coding Standards.
893 register_channel 'gnu', type => 'warning';
894 # Warnings about obsolete features (silent by default).
895 register_channel 'obsolete', type => 'warning', silent => 1;
896 # Warnings about non-portable constructs.
897 register_channel 'portability', type => 'warning', silent => 1;
898 # Weird syntax, unused variables, typos...
899 register_channel 'syntax', type => 'warning';
900 # Warnings about unsupported (or mis-supported) features.
901 register_channel 'unsupported', type => 'warning';
902
903 # For &verb.
904 register_channel 'verb', type => 'debug', silent => 1;
905 # Informative messages.
906 register_channel 'note', type => 'debug', silent => 0;
907
908
909 # Initialize our list of languages that are internally supported.
910
911 # C.
912 register_language ('name' => 'c',
913                    'Name' => 'C',
914                    'config_vars' => ['CC'],
915                    'ansi' => 1,
916                    'autodep' => '',
917                    'flags' => ['CFLAGS', 'CPPFLAGS'],
918                    'compiler' => 'COMPILE',
919                    'compile' => '$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS)',
920                    'lder' => 'CCLD',
921                    'ld' => '$(CC)',
922                    'linker' => 'LINK',
923                    'link' => '$(CCLD) $(AM_CFLAGS) $(CFLAGS) $(AM_LDFLAGS) $(LDFLAGS) -o $@',
924                    'compile_flag' => '-c',
925                    'extensions' => ['.c'],
926                    '_finish' => \&lang_c_finish);
927
928 # C++.
929 register_language ('name' => 'cxx',
930                    'Name' => 'C++',
931                    'config_vars' => ['CXX'],
932                    'linker' => 'CXXLINK',
933                    'link' => '$(CXXLD) $(AM_CXXFLAGS) $(CXXFLAGS) $(AM_LDFLAGS) $(LDFLAGS) -o $@',
934                    'autodep' => 'CXX',
935                    'flags' => ['CXXFLAGS', 'CPPFLAGS'],
936                    'compile' => '$(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS)',
937                    'compiler' => 'CXXCOMPILE',
938                    'compile_flag' => '-c',
939                    'output_flag' => '-o',
940                    'lder' => 'CXXLD',
941                    'ld' => '$(CXX)',
942                    'pure' => 1,
943                    'extensions' => ['.c++', '.cc', '.cpp', '.cxx', '.C']);
944
945 # Objective C.
946 register_language ('name' => 'objc',
947                    'Name' => 'Objective C',
948                    'config_vars' => ['OBJC'],
949                    'linker' => 'OBJCLINK',,
950                    'link' => '$(OBJCLD) $(AM_OBJCFLAGS) $(OBJCFLAGS) $(AM_LDFLAGS) $(LDFLAGS) -o $@',
951                    'autodep' => 'OBJC',
952                    'flags' => ['OBJCFLAGS', 'CPPFLAGS'],
953                    'compile' => '$(OBJC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_OBJCFLAGS) $(OBJCFLAGS)',
954                    'compiler' => 'OBJCCOMPILE',
955                    'compile_flag' => '-c',
956                    'output_flag' => '-o',
957                    'lder' => 'OBJCLD',
958                    'ld' => '$(OBJC)',
959                    'pure' => 1,
960                    'extensions' => ['.m']);
961
962 # Headers.
963 register_language ('name' => 'header',
964                    'Name' => 'Header',
965                    'extensions' => ['.h', '.H', '.hxx', '.h++', '.hh',
966                                     '.hpp', '.inc'],
967                    # No output.
968                    'output_extensions' => sub { return () },
969                    # Nothing to do.
970                    '_finish' => sub { });
971
972 # Yacc (C & C++).
973 register_language ('name' => 'yacc',
974                    'Name' => 'Yacc',
975                    'config_vars' => ['YACC'],
976                    'flags' => ['YFLAGS'],
977                    'compile' => '$(YACC) $(YFLAGS) $(AM_YFLAGS)',
978                    'compiler' => 'YACCCOMPILE',
979                    'extensions' => ['.y'],
980                    'output_extensions' => sub { (my $ext = $_[0]) =~ tr/y/c/;
981                                                 return ($ext,) },
982                    'rule_file' => 'yacc',
983                    '_finish' => \&lang_yacc_finish,
984                    '_target_hook' => \&lang_yacc_target_hook);
985 register_language ('name' => 'yaccxx',
986                    'Name' => 'Yacc (C++)',
987                    'config_vars' => ['YACC'],
988                    'rule_file' => 'yacc',
989                    'flags' => ['YFLAGS'],
990                    'compiler' => 'YACCCOMPILE',
991                    'compile' => '$(YACC) $(YFLAGS) $(AM_YFLAGS)',
992                    'extensions' => ['.y++', '.yy', '.yxx', '.ypp'],
993                    'output_extensions' => sub { (my $ext = $_[0]) =~ tr/y/c/;
994                                                 return ($ext,) },
995                    '_finish' => \&lang_yacc_finish,
996                    '_target_hook' => \&lang_yacc_target_hook);
997
998 # Lex (C & C++).
999 register_language ('name' => 'lex',
1000                    'Name' => 'Lex',
1001                    'config_vars' => ['LEX'],
1002                    'rule_file' => 'lex',
1003                    'flags' => ['LFLAGS'],
1004                    'compile' => '$(LEX) $(LFLAGS) $(AM_LFLAGS)',
1005                    'compiler' => 'LEXCOMPILE',
1006                    'extensions' => ['.l'],
1007                    'output_extensions' => sub { (my $ext = $_[0]) =~ tr/l/c/;
1008                                                 return ($ext,) },
1009                    '_finish' => \&lang_lex_finish,
1010                    '_target_hook' => \&lang_lex_target_hook);
1011 register_language ('name' => 'lexxx',
1012                    'Name' => 'Lex (C++)',
1013                    'config_vars' => ['LEX'],
1014                    'rule_file' => 'lex',
1015                    'flags' => ['LFLAGS'],
1016                    'compile' => '$(LEX) $(LFLAGS) $(AM_LFLAGS)',
1017                    'compiler' => 'LEXCOMPILE',
1018                    'extensions' => ['.l++', '.ll', '.lxx', '.lpp'],
1019                    'output_extensions' => sub { (my $ext = $_[0]) =~ tr/l/c/;
1020                                                 return ($ext,) },
1021                    '_finish' => \&lang_lex_finish,
1022                    '_target_hook' => \&lang_lex_target_hook);
1023
1024 # Assembler.
1025 register_language ('name' => 'asm',
1026                    'Name' => 'Assembler',
1027                    'config_vars' => ['CCAS', 'CCASFLAGS'],
1028
1029                    'flags' => ['CCASFLAGS'],
1030                    # Users can set AM_ASFLAGS to includes DEFS, INCLUDES,
1031                    # or anything else required.  They can also set AS.
1032                    'compile' => '$(CCAS) $(AM_CCASFLAGS) $(CCASFLAGS)',
1033                    'compiler' => 'CCASCOMPILE',
1034                    'compile_flag' => '-c',
1035                    'extensions' => ['.s', '.S'],
1036
1037                    # With assembly we still use the C linker.
1038                    '_finish' => \&lang_c_finish);
1039
1040 # Fortran 77
1041 register_language ('name' => 'f77',
1042                    'Name' => 'Fortran 77',
1043                    'linker' => 'F77LINK',
1044                    'link' => '$(F77LD) $(AM_FFLAGS) $(FFLAGS) $(AM_LDFLAGS) $(LDFLAGS) -o $@',
1045                    'flags' => ['FFLAGS'],
1046                    'compile' => '$(F77) $(AM_FFLAGS) $(FFLAGS)',
1047                    'compiler' => 'F77COMPILE',
1048                    'compile_flag' => '-c',
1049                    'output_flag' => '-o',
1050                    'lder' => 'F77LD',
1051                    'ld' => '$(F77)',
1052                    'pure' => 1,
1053                    'extensions' => ['.f', '.for', '.f90']);
1054
1055 # Preprocessed Fortran 77
1056 #
1057 # The current support for preprocessing Fortran 77 just involves
1058 # passing `$(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS)
1059 # $(CPPFLAGS)' as additional flags to the Fortran 77 compiler, since
1060 # this is how GNU Make does it; see the `GNU Make Manual, Edition 0.51
1061 # for `make' Version 3.76 Beta' (specifically, from info file
1062 # `(make)Catalogue of Rules').
1063 #
1064 # A better approach would be to write an Autoconf test
1065 # (i.e. AC_PROG_FPP) for a Fortran 77 preprocessor, because not all
1066 # Fortran 77 compilers know how to do preprocessing.  The Autoconf
1067 # macro AC_PROG_FPP should test the Fortran 77 compiler first for
1068 # preprocessing capabilities, and then fall back on cpp (if cpp were
1069 # available).
1070 register_language ('name' => 'ppf77',
1071                    'Name' => 'Preprocessed Fortran 77',
1072                    'config_vars' => ['F77'],
1073                    'linker' => 'F77LINK',
1074                    'link' => '$(F77LD) $(AM_FFLAGS) $(FFLAGS) $(AM_LDFLAGS) $(LDFLAGS) -o $@',
1075                    'lder' => 'F77LD',
1076                    'ld' => '$(F77)',
1077                    'flags' => ['FFLAGS', 'CPPFLAGS'],
1078                    'compiler' => 'PPF77COMPILE',
1079                    'compile' => '$(F77) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_FFLAGS) $(FFLAGS)',
1080                    'compile_flag' => '-c',
1081                    'output_flag' => '-o',
1082                    'pure' => 1,
1083                    'extensions' => ['.F']);
1084
1085 # Ratfor.
1086 register_language ('name' => 'ratfor',
1087                    'Name' => 'Ratfor',
1088                    'config_vars' => ['F77'],
1089                    'linker' => 'F77LINK',
1090                    'link' => '$(F77LD) $(AM_FFLAGS) $(FFLAGS) $(AM_LDFLAGS) $(LDFLAGS) -o $@',
1091                    'lder' => 'F77LD',
1092                    'ld' => '$(F77)',
1093                    'flags' => ['RFLAGS', 'FFLAGS'],
1094                    # FIXME also FFLAGS.
1095                    'compile' => '$(F77) $(AM_FFLAGS) $(FFLAGS) $(AM_RFLAGS) $(RFLAGS)',
1096                    'compiler' => 'RCOMPILE',
1097                    'compile_flag' => '-c',
1098                    'output_flag' => '-o',
1099                    'pure' => 1,
1100                    'extensions' => ['.r']);
1101
1102 # Java via gcj.
1103 register_language ('name' => 'java',
1104                    'Name' => 'Java',
1105                    'config_vars' => ['GCJ'],
1106                    'linker' => 'GCJLINK',
1107                    'link' => '$(GCJLD) $(AM_GCJFLAGS) $(GCJFLAGS) $(AM_LDFLAGS) $(LDFLAGS) -o $@',
1108                    'autodep' => 'GCJ',
1109                    'flags' => ['GCJFLAGS'],
1110                    'compile' => '$(GCJ) $(AM_GCJFLAGS) $(GCJFLAGS)',
1111                    'compiler' => 'GCJCOMPILE',
1112                    'compile_flag' => '-c',
1113                    'output_flag' => '-o',
1114                    'lder' => 'GCJLD',
1115                    'ld' => '$(GCJ)',
1116                    'pure' => 1,
1117                    'extensions' => ['.java', '.class', '.zip', '.jar']);
1118
1119 ################################################################
1120
1121 # Parse the WARNINGS environnent variable.
1122 &parse_WARNINGS;
1123
1124 # Parse command line.
1125 &parse_arguments;
1126
1127 # Do configure.ac scan only once.
1128 &scan_autoconf_files;
1129
1130 &fatal ("no `Makefile.am' found or specified\n")
1131   if ! @input_files;
1132
1133 my $automake_has_run = 0;
1134
1135 do
1136 {
1137   if ($automake_has_run)
1138     {
1139       &verb ('processing Makefiles another time to fix them up.');
1140       &prog_error ('running more than two times should never be needed.')
1141         if $automake_has_run >= 2;
1142     }
1143   $automake_needs_to_reprocess_all_files = 0;
1144
1145   # Now do all the work on each file.
1146   # This guy must be local otherwise it's private to the loop.
1147   use vars '$am_file';
1148   local $am_file;
1149   foreach $am_file (@input_files)
1150     {
1151       if (! -f ($am_file . '.am'))
1152         {
1153           &err ("`$am_file.am' does not exist");
1154         }
1155       else
1156         {
1157           &generate_makefile ($output_files{$am_file}, $am_file);
1158         }
1159     }
1160   ++$automake_has_run;
1161 }
1162 while ($automake_needs_to_reprocess_all_files);
1163
1164 exit $exit_code;
1165
1166 ################################################################
1167
1168 # Error reporting functions.
1169
1170 # prog_error ($MESSAGE, [%OPTIONS])
1171 # -------------------------------
1172 # Signal a programming error, display $MESSAGE, and exit 1.
1173 sub prog_error ($;%)
1174 {
1175   my ($msg, %opts) = @_;
1176   msg 'automake', '', $msg, %opts;
1177 }
1178
1179 # err ($WHERE, $MESSAGE, [%OPTIONS])
1180 # err ($MESSAGE)
1181 # ----------------------------------
1182 # Uncategorized errors.
1183 sub err ($;$%)
1184 {
1185   my ($where, $msg, %opts) = @_;
1186   msg ('error', $where, $msg, %opts);
1187 }
1188
1189 # fatal ($WHERE, $MESSAGE, [%OPTIONS])
1190 # fatal ($MESSAGE)
1191 # ----------------------------------
1192 # Fatal errors.
1193 sub fatal ($;$%)
1194 {
1195   my ($where, $msg, %opts) = @_;
1196   msg ('fatal', $where, $msg, %opts);
1197 }
1198
1199 # err_var ($VARNAME, $MESSAGE, [%OPTIONS])
1200 # ----------------------------------------
1201 # Uncategorized errors about variables.
1202 sub err_var ($$;%)
1203 {
1204   msg_var ('error', @_);
1205 }
1206
1207 # err_target ($TARGETNAME, $MESSAGE, [%OPTIONS])
1208 # ----------------------------------------------
1209 # Uncategorized errors about targets.
1210 sub err_target ($$;%)
1211 {
1212   msg_target ('error', @_);
1213 }
1214
1215 # err_cond_target ($COND, $TARGETNAME, $MESSAGE, [%OPTIONS])
1216 # ----------------------------------------------------------
1217 # Uncategorized errors about conditional targets.
1218 sub err_cond_target ($$$;%)
1219 {
1220   msg_cond_target ('error', @_);
1221 }
1222
1223 # err_am ($MESSAGE, [%OPTIONS])
1224 # -----------------------------
1225 # Uncategorized errors about the current Makefile.am.
1226 sub err_am ($;%)
1227 {
1228   msg_am ('error', @_);
1229 }
1230
1231 # err_ac ($MESSAGE, [%OPTIONS])
1232 # -----------------------------
1233 # Uncategorized errors about configure.ac.
1234 sub err_ac ($;%)
1235 {
1236   msg_ac ('error', @_);
1237 }
1238
1239 # msg_cond_var ($CHANNEL, $COND, $VARNAME, $MESSAGE, [%OPTIONS])
1240 # --------------------------------------------------------------
1241 # Messages about conditional variable.
1242 sub msg_cond_var ($$$$;%)
1243 {
1244   my ($channel, $cond, $var, $msg, %opts) = @_;
1245   msg $channel, $var_location{$var}{$cond}, $msg, %opts;
1246 }
1247
1248 # msg_var ($CHANNEL, $VARNAME, $MESSAGE, [%OPTIONS])
1249 # --------------------------------------------------
1250 # Messages about variables.
1251 sub msg_var ($$$;%)
1252 {
1253   my ($channel, $var, $msg, %opts) = @_;
1254   # Don't know which condition is concerned.  Pick any.
1255   my $cond = (keys %{$var_value{$var}})[0];
1256   msg_cond_var $channel, $cond, $var, $msg, %opts;
1257 }
1258
1259 # msg_cond_target ($CHANNEL, $COND, $TARGETNAME, $MESSAGE, [%OPTIONS])
1260 # --------------------------------------------------------------------
1261 # Messages about conditional targets.
1262 sub msg_cond_target ($$$$;%)
1263 {
1264   my ($channel, $cond, $target, $msg, %opts) = @_;
1265   msg $channel, $targets{$target}{$cond}, $msg, %opts;
1266 }
1267
1268 # msg_target ($CHANNEL, $TARGETNAME, $MESSAGE, [%OPTIONS])
1269 # --------------------------------------------------------
1270 # Messages about targets.
1271 sub msg_target ($$$;%)
1272 {
1273   my ($channel, $target, $msg, %opts) = @_;
1274   # Don't know which condition is concerned.  Pick any.
1275   my $cond = (keys %{$targets{$target}})[0];
1276   msg_cond_target ($channel, $cond, $target, $msg, %opts);
1277 }
1278
1279 # msg_am ($CHANNEL, $MESSAGE, [%OPTIONS])
1280 # ---------------------------------------
1281 # Messages about about the current Makefile.am.
1282 sub msg_am ($$;%)
1283 {
1284   my ($channel, $msg, %opts) = @_;
1285   msg $channel, "${am_file}.am", $msg, %opts;
1286 }
1287
1288 # msg_ac ($CHANNEL, $MESSAGE, [%OPTIONS])
1289 # ---------------------------------------
1290 # Messages about about configure.ac.
1291 sub msg_ac ($$;%)
1292 {
1293   my ($channel, $msg, %opts) = @_;
1294   msg $channel, $configure_ac, $msg, %opts;
1295 }
1296
1297 # $BOOL
1298 # reject_var ($VAR, $ERROR_MSG)
1299 # -----------------------------
1300 sub reject_var ($$)
1301 {
1302   my ($var, $msg) = @_;
1303   if (variable_defined ($var))
1304     {
1305       err_var $var, $msg;
1306       return 1;
1307     }
1308   return 0;
1309 }
1310
1311 # $BOOL
1312 # reject_target ($VAR, $ERROR_MSG)
1313 # --------------------------------
1314 sub reject_target ($$)
1315 {
1316   my ($target, $msg) = @_;
1317   if (target_defined ($target))
1318     {
1319       err_target $target, $msg;
1320       return 1;
1321     }
1322   return 0;
1323 }
1324
1325 # verb ($MESSAGE, [%OPTIONS])
1326 # ---------------------------
1327 sub verb ($;%)
1328 {
1329   my ($msg, %opts) = @_;
1330   msg 'verb', '', $msg, %opts;
1331 }
1332
1333 ################################################################
1334
1335 # subst ($TEXT)
1336 # -------------
1337 # Return a configure-style substitution using the indicated text.
1338 # We do this to avoid having the substitutions directly in automake.in;
1339 # when we do that they are sometimes removed and this causes confusion
1340 # and bugs.
1341 sub subst ($)
1342 {
1343     my ($text) = @_;
1344     return '@' . $text . '@';
1345 }
1346
1347 ################################################################
1348
1349
1350 # $BACKPATH
1351 # &backname ($REL-DIR)
1352 # --------------------
1353 # If I `cd $REL-DIR', then to come back, I should `cd $BACKPATH'.
1354 # For instance `src/foo' => `../..'.
1355 # Works with non strictly increasing paths, i.e., `src/../lib' => `..'.
1356 sub backname ($)
1357 {
1358     my ($file) = @_;
1359     my @res;
1360     foreach (split (/\//, $file))
1361     {
1362         next if $_ eq '.' || $_ eq '';
1363         if ($_ eq '..')
1364         {
1365             pop @res;
1366         }
1367         else
1368         {
1369             push (@res, '..');
1370         }
1371     }
1372     return join ('/', @res) || '.';
1373 }
1374
1375 ################################################################
1376
1377 # Pattern that matches all know input extensions (i.e. extensions used
1378 # by the languages supported by Automake).  Using this pattern
1379 # (instead of `\..*$') to match extensions allows Automake to support
1380 # dot-less extensions.
1381 my $KNOWN_EXTENSIONS_PATTERN = "";
1382 my @known_extensions_list = ();
1383
1384 # accept_extensions (@EXTS)
1385 # -------------------------
1386 # Update $KNOWN_EXTENSIONS_PATTERN to recognize the extensions
1387 # listed @EXTS.  Extensions should contain a dot if needed.
1388 sub accept_extensions (@)
1389 {
1390     push @known_extensions_list, @_;
1391     $KNOWN_EXTENSIONS_PATTERN =
1392         '(?:' . join ('|', map (quotemeta, @known_extensions_list)) . ')';
1393 }
1394
1395 # var_SUFFIXES_trigger ($TYPE, $VALUE)
1396 # ------------------------------------
1397 # This is called automagically by macro_define() when SUFFIXES
1398 # is defined ($TYPE eq '') or appended ($TYPE eq '+').
1399 # The work here needs to be performed as a side-effect of the
1400 # macro_define() call because SUFFIXES definitions impact
1401 # on $KNOWN_EXTENSIONS_PATTERN, and $KNOWN_EXTENSIONS_PATTERN
1402 # are used when parsing the input am file.
1403 sub var_SUFFIXES_trigger ($$)
1404 {
1405     my ($type, $value) = @_;
1406     accept_extensions (split (' ', $value));
1407 }
1408
1409 ################################################################
1410
1411
1412 # switch_warning ($CATEGORY)
1413 # --------------------------
1414 # If $CATEGORY is mumble, turn on the mumble channel.
1415 # If it's no-mumble, turn mumble off.
1416 # Alse handle `all' and `none' for completeness.
1417 sub switch_warning ($)
1418 {
1419   my ($cat) = @_;
1420   my $has_no = 0;
1421
1422   if ($cat =~ /^no-(.*)$/)
1423     {
1424       $cat = $1;
1425       $has_no = 1;
1426     }
1427
1428   if ($cat eq 'all')
1429     {
1430       setup_channel_type 'warning', silent => $has_no;
1431     }
1432   elsif ($cat eq 'none')
1433     {
1434       setup_channel_type 'warning', silent => 1 - $has_no;
1435     }
1436   elsif ($cat eq 'error')
1437     {
1438       $warnings_are_errors = 1 - $has_no;
1439     }
1440   elsif (channel_type ($cat) eq 'warning')
1441     {
1442       setup_channel $cat, silent => $has_no;
1443     }
1444   else
1445     {
1446       return 1;
1447     }
1448   return 0;
1449 }
1450
1451 # parse_WARNINGS
1452 # --------------
1453 # Honor the WARNINGS environment variable.
1454 sub parse_WARNINGS ($$)
1455 {
1456   if (exists $ENV{'WARNINGS'})
1457     {
1458       # Ignore unknown categories.  This is required because WARNINGS
1459       # should be honored by many tools.
1460       switch_warning $_ foreach (split (',', $ENV{'WARNINGS'}));
1461     }
1462 }
1463
1464 # parse_warning ($OPTION, $ARGUMENT)
1465 # ----------------------------------
1466 # Parse the argument of --warning=CATEGORY or -WCATEGORY.
1467 sub parse_warnings ($$)
1468 {
1469   my ($opt, $categories) = @_;
1470
1471   foreach my $cat (split (',', $categories))
1472     {
1473       msg 'unsupported', "unknown warning category `$cat'"
1474         if switch_warning $cat;
1475     }
1476 }
1477
1478 # Parse command line.
1479 sub parse_arguments ()
1480 {
1481   # Start off as gnu.
1482   &set_strictness ('gnu');
1483
1484   my %options =
1485     (
1486      'libdir:s'         => \$libdir,
1487      'gnu'              => sub { &set_strictness ('gnu'); },
1488      'gnits'            => sub { &set_strictness ('gnits'); },
1489      'cygnus'           => \$cygnus_mode,
1490      'foreign'          => sub { &set_strictness ('foreign'); },
1491      'include-deps'     => sub { $cmdline_use_dependencies = 1; },
1492      'i|ignore-deps'    => sub { $cmdline_use_dependencies = 0; },
1493      'no-force'         => sub { $force_generation = 0; },
1494      'f|force-missing'  => \$force_missing,
1495      'o|output-dir:s'   => \$output_directory,
1496      'a|add-missing'    => \$add_missing,
1497      'c|copy'           => \$copy_missing,
1498      'v|verbose'        => sub { setup_channel 'verb', silent => 0; },
1499      'W|warnings:s'     => \&parse_warnings,
1500      # These long options (--Werror and --Wno-error) for backward
1501      # compatibility.  Use -Werror and -Wno-error today.
1502      'Werror'           => sub { parse_warnings 'W', 'error'; },
1503      'Wno-error'        => sub { parse_warnings 'W', 'no-error'; },
1504      );
1505
1506   use Getopt::Long;
1507   Getopt::Long::config ("bundling", "pass_through");
1508
1509   # See if --version or --help is used.  We want to process these before
1510   # anything else because the GNU Coding Standards require us to
1511   # `exit 0' after processing these options, and we can't garanty this
1512   # if we treat other options first.  (Handling other options first
1513   # could produce error diagnostics, and in this condition it is
1514   # confusing if Automake `exit 0'.)
1515   my %options_1st_pass =
1516     (
1517      'version' => \&version,
1518      'help'    => \&usage,
1519      # Recognize all other options (and their arguments) but do nothing.
1520      map { $_ => sub {} } (keys %options)
1521      );
1522   my @ARGV_backup = @ARGV;
1523   Getopt::Long::GetOptions %options_1st_pass
1524     or exit 1;
1525   @ARGV = @ARGV_backup;
1526
1527   # Now *really* process the options.  This time we know
1528   # that --help and --version are not present.
1529   Getopt::Long::GetOptions %options
1530     or exit 1;
1531
1532   if (defined $output_directory)
1533     {
1534       msg 'obsolete', "`--output-dir' is deprecated\n";
1535     }
1536   else
1537     {
1538       # In the next release we'll remove this entirely.
1539       $output_directory = '.';
1540     }
1541
1542   foreach my $arg (@ARGV)
1543     {
1544       if ($arg =~ /^-./)
1545         {
1546           fatal ("unrecognized option `$arg'\n"
1547                  . "Try `$0 --help' for more information.");
1548         }
1549
1550       # Handle $local:$input syntax.  Note that we only examine the
1551       # first ":" file to see if it is automake input; the rest are
1552       # just taken verbatim.  We still keep all the files around for
1553       # dependency checking, however.
1554       my ($local, $input, @rest) = split (/:/, $arg);
1555       if (! $input)
1556         {
1557           $input = $local;
1558         }
1559       else
1560         {
1561           # Strip .in; later on .am is tacked on.  That is how the
1562           # automake input file is found.  Maybe not the best way, but
1563           # it is easy to explain.
1564           $input =~ s/\.in$//
1565             or fatal "invalid input file name `$arg'\n.";
1566         }
1567       push (@input_files, $input);
1568       $output_files{$input} = join (':', ($local, @rest));
1569     }
1570
1571   # Take global strictness from whatever we currently have set.
1572   $default_strictness = $strictness;
1573   $default_strictness_name = $strictness_name;
1574 }
1575
1576 ################################################################
1577
1578 # Generate a Makefile.in given the name of the corresponding Makefile and
1579 # the name of the file output by config.status.
1580 sub generate_makefile
1581 {
1582     my ($output, $makefile) = @_;
1583
1584     # Reset all the Makefile.am related variables.
1585     &initialize_per_input;
1586
1587     # Any warning setting now local to this Makefile.am.
1588     &dup_channel_setup;
1589     # AUTOMAKE_OPTIONS can contains -W flags to disable or enable
1590     # warnings for this file.  So hold any warning issued before
1591     # we have processed AUTOMAKE_OPTIONS.
1592     &buffer_messages ('warning');
1593
1594     # Name of input file ("Makefile.am") and output file
1595     # ("Makefile.in").  These have no directory components.
1596     $am_file_name = basename ($makefile) . '.am';
1597     $in_file_name = basename ($makefile) . '.in';
1598
1599     # $OUTPUT is encoded.  If it contains a ":" then the first element
1600     # is the real output file, and all remaining elements are input
1601     # files.  We don't scan or otherwise deal with these input file,
1602     # other than to mark them as dependencies.  See
1603     # &scan_autoconf_files for details.
1604     my (@secondary_inputs);
1605     ($output, @secondary_inputs) = split (/:/, $output);
1606
1607     $relative_dir = dirname ($output);
1608     $am_relative_dir = dirname ($makefile);
1609
1610     &read_main_am_file ($makefile . '.am');
1611     if (&handle_options)
1612     {
1613       # Process buffered warnings.
1614       &flush_messages;
1615       # Fatal error.  Just return, so we can continue with next file.
1616       return;
1617     }
1618     # Process buffered warnings.
1619     &flush_messages;
1620
1621     # There are a few install-related variables that you should not define.
1622     foreach my $var ('PRE_INSTALL', 'POST_INSTALL', 'NORMAL_INSTALL')
1623       {
1624         if (exists $var_owner{$var})
1625           {
1626             prog_error "\$var_owner{$var}{TRUE} doesn't exist"
1627               unless exists $var_owner{$var}{&TRUE};
1628             reject_var $var, "`$var' should not be defined"
1629               if $var_owner{$var}{&TRUE} != VAR_AUTOMAKE;
1630           }
1631       }
1632
1633     # Catch some obsolete variables.
1634     msg_var ('obsolete', 'INCLUDES',
1635              "`INCLUDES' is the old name for `AM_CPPFLAGS'")
1636       if variable_defined ('INCLUDES');
1637
1638     # At the toplevel directory, we might need config.guess, config.sub
1639     # or libtool scripts (ltconfig and ltmain.sh).
1640     if ($relative_dir eq '.')
1641     {
1642         # AC_CANONICAL_HOST and AC_CANONICAL_SYSTEM need config.guess and
1643         # config.sub.
1644         require_conf_file ($canonical_location, FOREIGN,
1645                            'config.guess', 'config.sub')
1646           if $seen_canonical;
1647     }
1648
1649     # We still need Makefile.in here, because sometimes the `dist'
1650     # target doesn't re-run automake.
1651     if ($am_relative_dir eq $relative_dir)
1652     {
1653         # Only distribute the files if they are in the same subdir as
1654         # the generated makefile.
1655         &push_dist_common ($in_file_name, $am_file_name);
1656     }
1657
1658     push (@sources, '$(SOURCES)')
1659         if variable_defined ('SOURCES');
1660
1661     # Must do this after reading .am file.  See read_main_am_file to
1662     # understand weird tricks we play there with variables.
1663     &define_variable ('subdir', $relative_dir, INTERNAL);
1664
1665     # Check first, because we might modify some state.
1666     &check_cygnus;
1667     &check_gnu_standards;
1668     &check_gnits_standards;
1669
1670     &handle_configure ($output, $makefile, @secondary_inputs);
1671     &handle_gettext;
1672     &handle_libraries;
1673     &handle_ltlibraries;
1674     &handle_programs;
1675     &handle_scripts;
1676
1677     # This must run first so that the ANSI2KNR definition is generated
1678     # before it is used by the _.c rules.  We have to do this because
1679     # a variable which is used in a dependency must be defined before
1680     # the target, or else make won't properly see it.
1681     &handle_compile;
1682     # This must be run after all the sources are scanned.
1683     &handle_languages;
1684
1685     # We have to run this after dealing with all the programs.
1686     &handle_libtool;
1687
1688     # Re-init SOURCES.  FIXME: other code shouldn't depend on this
1689     # (but currently does).
1690     macro_define ('SOURCES', VAR_AUTOMAKE, '', TRUE, "@sources", INTERNAL);
1691     define_pretty_variable ('DIST_SOURCES', TRUE, INTERNAL, @dist_sources);
1692
1693     &handle_multilib;
1694     &handle_texinfo;
1695     &handle_emacs_lisp;
1696     &handle_python;
1697     &handle_java;
1698     &handle_man_pages;
1699     &handle_data;
1700     &handle_headers;
1701     &handle_subdirs;
1702     &handle_tags;
1703     &handle_minor_options;
1704     &handle_tests;
1705
1706     # This must come after most other rules.
1707     &handle_dist ($makefile);
1708
1709     &handle_footer;
1710     &do_check_merge_target;
1711     &handle_all ($output);
1712
1713     # FIXME: Gross!
1714     if (variable_defined ('lib_LTLIBRARIES') &&
1715         variable_defined ('bin_PROGRAMS'))
1716     {
1717         $output_rules .= "install-binPROGRAMS: install-libLTLIBRARIES\n\n";
1718     }
1719
1720     &handle_installdirs;
1721     &handle_clean;
1722     &handle_factored_dependencies;
1723
1724     check_typos ();
1725
1726     if (! -d ($output_directory . '/' . $am_relative_dir))
1727     {
1728         mkdir ($output_directory . '/' . $am_relative_dir, 0755);
1729     }
1730
1731     my ($out_file) = $output_directory . '/' . $makefile . ".in";
1732     if (! $force_generation && -e $out_file)
1733     {
1734         my ($am_time) = (stat ($makefile . '.am'))[9];
1735         my ($in_time) = (stat ($out_file))[9];
1736         # FIXME: should cache these times.
1737         my ($conf_time) = (stat ($configure_ac))[9];
1738         # FIXME: how to do unsigned comparison?
1739         if ($am_time < $in_time || $am_time < $conf_time)
1740         {
1741             # No need to update.
1742             return;
1743         }
1744         if (-f 'aclocal.m4')
1745         {
1746             my ($acl_time) = (stat _)[9];
1747             return if ($am_time < $acl_time);
1748         }
1749     }
1750
1751     if (-e "$out_file")
1752     {
1753         unlink ($out_file)
1754             or fatal "cannot remove $out_file: $!\n";
1755     }
1756     my $gm_file = new Automake::XFile "> $out_file";
1757     verb "creating $makefile.in";
1758
1759     print $gm_file $output_vars;
1760     # We make sure that `all:' is the first target.
1761     print $gm_file $output_all;
1762     print $gm_file $output_header;
1763     print $gm_file $output_rules;
1764     print $gm_file $output_trailer;
1765
1766     # Back out any warning setting.
1767     &drop_channel_setup;
1768 }
1769
1770 ################################################################
1771
1772 # A version is a string that looks like
1773 #   MAJOR.MINOR[.MICRO][ALPHA][-FORK]
1774 # where
1775 #   MAJOR, MINOR, and MICRO are digits, ALPHA is a character, and
1776 # FORK any alphanumeric word.
1777 # Usually, ALPHA is used to label alpha releases or intermediate snapshots,
1778 # FORK is used for CVS branches or patched releases, and MICRO is used
1779 # for bug fixes releases on the MAJOR.MINOR branch.
1780 #
1781 # For the purpose of ordering, 1.4 is the same as 1.4.0, but 1.4g is
1782 # the same as 1.4.99g.  The FORK identifier is ignored in the
1783 # ordering, except when it looks like -pMINOR[ALPHA]: some versions
1784 # were labelled like 1.4-p3a, this is the same as an alpha release
1785 # labelled 1.4.3a.  Yes it's horrible, but Automake did not support
1786 # two-dot versions in the past.
1787
1788 # version_split (VERSION)
1789 # -----------------------
1790 # Split a version string into the corresponding (MAJOR, MINOR, MICRO,
1791 # ALPHA, FORK) tuple.  For instance "1.4g" would be split into
1792 # (1, 4, 99, 'g', '').
1793 # Return () on error.
1794 sub version_split ($)
1795 {
1796     my ($ver) = @_;
1797
1798     # Special case for versions like 1.4-p2a.
1799     if ($ver =~ /^(\d+)\.(\d+)(?:-p(\d+)([a-z]+)?)$/)
1800     {
1801         return ($1, $2, $3, $4 || '', '');
1802     }
1803     # Common case.
1804     elsif ($ver =~ /^(\d+)\.(\d+)(?:\.(\d+))?([a-z])?(?:-([A-Za-z0-9]+))?$/)
1805     {
1806         return ($1, $2, $3 || (defined $4 ? 99 : 0), $4 || '', $5 || '');
1807     }
1808     return ();
1809 }
1810
1811 # version_compare (\@LVERSION, \@RVERSION)
1812 # ----------------------------------------
1813 # Return 1 if LVERSION > RVERSION,
1814 #       -1 if LVERSION < RVERSION,
1815 #        0 if LVERSION = RVERSION.
1816 sub version_compare (\@\@)
1817 {
1818     my @l = @{$_[0]};
1819     my @r = @{$_[1]};
1820
1821     for my $i (0, 1, 2)
1822     {
1823         return 1  if ($l[$i] > $r[$i]);
1824         return -1 if ($l[$i] < $r[$i]);
1825     }
1826     for my $i (3, 4)
1827     {
1828         return 1  if ($l[$i] gt $r[$i]);
1829         return -1 if ($l[$i] lt $r[$i]);
1830     }
1831     return 0;
1832 }
1833
1834 # Handles the logic of requiring a version number in AUTOMAKE_OPTIONS.
1835 # Return 0 if the required version is satisfied, 1 otherwise.
1836 sub version_check ($)
1837 {
1838   my ($required) = @_;
1839   my @version = version_split $VERSION;
1840   my @required = version_split $required;
1841
1842   prog_error "version is incorrect: $VERSION"
1843     if $#version == -1;
1844
1845   # This should not happen, because process_option_list and split_version
1846   # use similar regexes.
1847   prog_error "required version is incorrect: $required"
1848     if $#required == -1;
1849
1850   # If we require 3.4n-foo then we require something
1851   # >= 3.4n, with the `foo' fork identifier.
1852   return 1
1853     if ($required[4] ne '' && $required[4] ne $version[4]);
1854
1855   return 0 > version_compare @version, @required;
1856 }
1857
1858 # $BOOL
1859 # process_option_list ($CONFIG, @OPTIONS)
1860 # ------------------------------
1861 # Process a list of options.  Return 1 on error, 0 otherwise.
1862 # This is a helper for handle_options.  CONFIG is true if we're
1863 # handling global options.
1864 sub process_option_list
1865 {
1866   my ($config, @list) = @_;
1867
1868   # FIXME: We should disallow conditional deffinitions of AUTOMAKE_OPTIONS.
1869   my $where = ($config ?
1870                $seen_init_automake :
1871                $var_location{'AUTOMAKE_OPTIONS'}{&TRUE});
1872
1873   foreach (@list)
1874     {
1875       $options{$_} = 1;
1876       if ($_ eq 'gnits' || $_ eq 'gnu' || $_ eq 'foreign')
1877         {
1878           &set_strictness ($_);
1879         }
1880       elsif ($_ eq 'cygnus')
1881         {
1882           $cygnus_mode = 1;
1883         }
1884       elsif (/^(.*\/)?ansi2knr$/)
1885         {
1886           # An option like "../lib/ansi2knr" is allowed.  With no
1887           # path prefix, we assume the required programs are in this
1888           # directory.  We save the actual option for later.
1889           $options{'ansi2knr'} = $_;
1890         }
1891       elsif ($_ eq 'no-installman' || $_ eq 'no-installinfo'
1892              || $_ eq 'dist-shar' || $_ eq 'dist-zip'
1893              || $_ eq 'dist-tarZ' || $_ eq 'dist-bzip2'
1894              || $_ eq 'dejagnu' || $_ eq 'no-texinfo.tex'
1895              || $_ eq 'readme-alpha' || $_ eq 'check-news'
1896              || $_ eq 'subdir-objects' || $_ eq 'nostdinc'
1897              || $_ eq 'no-exeext' || $_ eq 'no-define'
1898              || $_ eq 'std-options')
1899         {
1900           # Explicitly recognize these.
1901         }
1902       elsif ($_ eq 'no-dependencies')
1903         {
1904           $use_dependencies = 0;
1905         }
1906       elsif (/^\d+\.\d+(?:\.\d+)?[a-z]?(?:-[A-Za-z0-9]+)?$/)
1907         {
1908           # Got a version number.
1909           if (version_check $&)
1910             {
1911               err ($where, "require Automake $_, but have $VERSION",
1912                    uniq_scope => US_GLOBAL);
1913                 return 1;
1914             }
1915         }
1916       elsif (/^(?:--warnings=|-W)(.*)$/)
1917         {
1918           foreach my $cat (split (',', $1))
1919             {
1920               msg 'unsupported', $where, "unknown warning category `$cat'"
1921                 if switch_warning $cat;
1922             }
1923         }
1924       else
1925         {
1926           err ($where, "option `$_' not recognized",
1927                uniq_scope => US_GLOBAL);
1928           return 1;
1929         }
1930     }
1931 }
1932
1933 # Handle AUTOMAKE_OPTIONS variable.  Return 1 on error, 0 otherwise.
1934 sub handle_options
1935 {
1936     # Process global options first so that more specific options can
1937     # override.
1938     if (&process_option_list (1, split (' ', $global_options)))
1939     {
1940         return 1;
1941     }
1942
1943     if (variable_defined ('AUTOMAKE_OPTIONS'))
1944     {
1945         if (&process_option_list (0, &variable_value_as_list_recursive ('AUTOMAKE_OPTIONS', TRUE)))
1946         {
1947             return 1;
1948         }
1949     }
1950
1951     if ($strictness == GNITS)
1952     {
1953         $options{'readme-alpha'} = 1;
1954         $options{'std-options'} = 1;
1955         $options{'check-news'} = 1;
1956     }
1957
1958     return 0;
1959 }
1960
1961
1962 # get_object_extension ($OUT)
1963 # ---------------------------
1964 # Return object extension.  Just once, put some code into the output.
1965 # OUT is the name of the output file
1966 sub get_object_extension
1967 {
1968     my ($out) = @_;
1969
1970     # Maybe require libtool library object files.
1971     my $extension = '.$(OBJEXT)';
1972     $extension = '.lo' if ($out =~ /\.la$/);
1973
1974     # Check for automatic de-ANSI-fication.
1975     $extension = '$U' . $extension
1976       if defined $options{'ansi2knr'};
1977
1978     $get_object_extension_was_run = 1;
1979
1980     return $extension;
1981 }
1982
1983
1984 # Call finish function for each language that was used.
1985 sub handle_languages
1986 {
1987     if ($use_dependencies)
1988     {
1989         # Include auto-dep code.  Don't include it if DEP_FILES would
1990         # be empty.
1991         if (&saw_sources_p (0) && keys %dep_files)
1992         {
1993             # Set location of depcomp.
1994             &define_variable ('depcomp', "\$(SHELL) $config_aux_dir/depcomp",
1995                               INTERNAL);
1996             &define_variable ('am__depfiles_maybe', 'depfiles', INTERNAL);
1997
1998             require_conf_file ("$am_file.am", FOREIGN, 'depcomp');
1999
2000             my @deplist = sort keys %dep_files;
2001
2002             # We define this as a conditional variable because BSD
2003             # make can't handle backslashes for continuing comments on
2004             # the following line.
2005             define_pretty_variable ('DEP_FILES',
2006                                     new Automake::Conditional ('AMDEP_TRUE'),
2007                                     INTERNAL, @deplist);
2008
2009             # Generate each `include' individually.  Irix 6 make will
2010             # not properly include several files resulting from a
2011             # variable expansion; generating many separate includes
2012             # seems safest.
2013             $output_rules .= "\n";
2014             foreach my $iter (@deplist)
2015             {
2016                 $output_rules .= (subst ('AMDEP_TRUE')
2017                                   . subst ('am__include')
2018                                   . ' '
2019                                   . subst ('am__quote')
2020                                   . $iter
2021                                   . subst ('am__quote')
2022                                   . "\n");
2023             }
2024
2025             # Compute the set of directories to remove in distclean-depend.
2026             my @depdirs = uniq (map { dirname ($_) } @deplist);
2027             $output_rules .= &file_contents ('depend',
2028                                              new Automake::Location,
2029                                              DEPDIRS => "@depdirs");
2030         }
2031     }
2032     else
2033     {
2034         &define_variable ('depcomp', '', INTERNAL);
2035         &define_variable ('am__depfiles_maybe', '', INTERNAL);
2036     }
2037
2038     my %done;
2039
2040     # Is the c linker needed?
2041     my $needs_c = 0;
2042     foreach my $ext (sort keys %extension_seen)
2043     {
2044         next unless $extension_map{$ext};
2045
2046         my $lang = $languages{$extension_map{$ext}};
2047
2048         my $rule_file = $lang->rule_file || 'depend2';
2049
2050         # Get information on $LANG.
2051         my $pfx = $lang->autodep;
2052         my $fpfx = ($pfx eq '') ? 'CC' : $pfx;
2053
2054         my $AMDEP = (($use_dependencies && $lang->autodep ne 'no')
2055                      ? 'AMDEP' : 'FALSE');
2056         my $FASTDEP = (($use_dependencies && $lang->autodep ne 'no')
2057                        ? ('am__fastdep' . $fpfx) : 'FALSE');
2058
2059         my %transform = ('EXT'     => $ext,
2060                          'PFX'     => $pfx,
2061                          'FPFX'    => $fpfx,
2062                          'AMDEP'   => $AMDEP,
2063                          'FASTDEP' => $FASTDEP,
2064                          '-c'      => $lang->compile_flag || '',
2065                          'MORE-THAN-ONE'
2066                                    => (count_files_for_language ($lang->name) > 1));
2067
2068         # Generate the appropriate rules for this extension.
2069         if (($use_dependencies && $lang->autodep ne 'no')
2070             || defined $lang->compile)
2071         {
2072             # Some C compilers don't support -c -o.  Use it only if really
2073             # needed.
2074             my $output_flag = $lang->output_flag || '';
2075             $output_flag = '-o'
2076               if (! $output_flag
2077                   && $lang->name eq 'c'
2078                   && defined $options{'subdir-objects'});
2079
2080             # Compute a possible derived extension.
2081             # This is not used by depend2.am.
2082             my $der_ext = (&{$lang->output_extensions} ($ext))[0];
2083
2084             $output_rules .=
2085               file_contents ($rule_file,
2086                              new Automake::Location,
2087                              %transform,
2088                              GENERIC   => 1,
2089
2090                              'DERIVED-EXT' => $der_ext,
2091
2092                              # In this situation we know that the
2093                              # object is in this directory, so
2094                              # $(DEPDIR) is the correct location for
2095                              # dependencies.
2096                              DEPBASE   => '$(DEPDIR)/$*',
2097                              BASE      => '$*',
2098                              SOURCE    => '$<',
2099                              OBJ       => '$@',
2100                              OBJOBJ    => '$@',
2101                              LTOBJ     => '$@',
2102
2103                              COMPILE   => '$(' . $lang->compiler . ')',
2104                              LTCOMPILE => '$(LT' . $lang->compiler . ')',
2105                              -o        => $output_flag);
2106         }
2107
2108         # Now include code for each specially handled object with this
2109         # language.
2110         my %seen_files = ();
2111         foreach my $file (@{$lang_specific_files{$lang->name}})
2112         {
2113             my ($derived, $source, $obj, $myext) = split (' ', $file);
2114
2115             # For any specially-generated object, we must respect the
2116             # ansi2knr setting so that we don't inadvertently try to
2117             # use the default rule.
2118             if ($lang->ansi && defined $options{'ansi2knr'})
2119             {
2120                 $myext = '$U' . $myext;
2121             }
2122
2123             # We might see a given object twice, for instance if it is
2124             # used under different conditions.
2125             next if defined $seen_files{$obj};
2126             $seen_files{$obj} = 1;
2127
2128             prog_error ("found " . $lang->name .
2129                         " in handle_languages, but compiler not defined")
2130               unless defined $lang->compile;
2131
2132             my $obj_compile = $lang->compile;
2133
2134             # Rewrite each occurence of `AM_$flag' in the compile
2135             # rule into `${derived}_$flag' if it exists.
2136             for my $flag (@{$lang->flags})
2137               {
2138                 my $val = "${derived}_$flag";
2139                 $obj_compile =~ s/\(AM_$flag\)/\($val\)/
2140                   if variable_defined ($val);
2141               }
2142
2143             my $obj_ltcompile = '$(LIBTOOL) --mode=compile ' . $obj_compile;
2144
2145             # We _need_ `-o' for per object rules.
2146             my $output_flag = $lang->output_flag || '-o';
2147
2148             my $depbase = dirname ($obj);
2149             $depbase = ''
2150                 if $depbase eq '.';
2151             $depbase .= '/'
2152                 unless $depbase eq '';
2153             $depbase .= '$(DEPDIR)/' . basename ($obj);
2154
2155             # Generate a transform which will turn suffix targets in
2156             # depend2.am into real targets for the particular objects we
2157             # are building.
2158             $output_rules .=
2159               file_contents ($rule_file,
2160                              new Automake::Location,
2161                              %transform,
2162                              GENERIC   => 0,
2163
2164                              DEPBASE   => $depbase,
2165                              BASE      => $obj,
2166                              SOURCE    => $source,
2167                              # Use $myext and not `.o' here, in case
2168                              # we are actually building a new source
2169                              # file -- e.g. via yacc.
2170                              OBJ       => "$obj$myext",
2171                              OBJOBJ    => "$obj.obj",
2172                              LTOBJ     => "$obj.lo",
2173
2174                              COMPILE   => $obj_compile,
2175                              LTCOMPILE => $obj_ltcompile,
2176                              -o        => $output_flag);
2177         }
2178
2179         # The rest of the loop is done once per language.
2180         next if defined $done{$lang};
2181         $done{$lang} = 1;
2182
2183         # Load the language dependent Makefile chunks.
2184         my %lang = map { uc ($_) => 0 } keys %languages;
2185         $lang{uc ($lang->name)} = 1;
2186         $output_rules .= file_contents ('lang-compile',
2187                                         new Automake::Location,
2188                                         %transform, %lang);
2189
2190         # If the source to a program consists entirely of code from a
2191         # `pure' language, for instance C++ for Fortran 77, then we
2192         # don't need the C compiler code.  However if we run into
2193         # something unusual then we do generate the C code.  There are
2194         # probably corner cases here that do not work properly.
2195         # People linking Java code to Fortran code deserve pain.
2196         $needs_c ||= ! $lang->pure;
2197
2198         define_compiler_variable ($lang)
2199           if ($lang->compile);
2200
2201         define_linker_variable ($lang)
2202           if ($lang->link);
2203
2204         require_variables ("$am_file.am", $lang->Name . " source seen",
2205                            TRUE, @{$lang->config_vars});
2206
2207         # Call the finisher.
2208         $lang->finish;
2209
2210         # Flags listed in `->flags' are user variables (per GNU Standards),
2211         # they should not be overriden in the Makefile...
2212         my @dont_override = @{$lang->flags};
2213         # ... and so is LDFLAGS.
2214         push @dont_override, 'LDFLAGS' if $lang->link;
2215
2216         foreach my $flag (@dont_override)
2217           {
2218             if (exists $var_owner{$flag})
2219               {
2220                 for my $cond (keys %{$var_owner{$flag}})
2221                   {
2222                     if ($var_owner{$flag}{$cond} == VAR_MAKEFILE)
2223                       {
2224                         msg_cond_var ('gnu', $cond, $flag,
2225                                       "`$flag' is a user variable, "
2226                                       . "you should not override it;\n"
2227                                       . "use `AM_$flag' instead.");
2228                       }
2229                   }
2230               }
2231           }
2232     }
2233
2234     # If the project is entirely C++ or entirely Fortran 77 (i.e., 1
2235     # suffix rule was learned), don't bother with the C stuff.  But if
2236     # anything else creeps in, then use it.
2237     $needs_c = 1
2238       if $need_link || ((scalar keys %$suffix_rules)
2239                         - (scalar keys %$suffix_rules_default)) > 1;
2240
2241     if ($needs_c)
2242       {
2243         &define_compiler_variable ($languages{'c'})
2244           unless defined $done{$languages{'c'}};
2245         define_linker_variable ($languages{'c'});
2246       }
2247 }
2248
2249 # Check to make sure a source defined in LIBOBJS is not explicitly
2250 # mentioned.  This is a separate function (as opposed to being inlined
2251 # in handle_source_transform) because it isn't always appropriate to
2252 # do this check.
2253 sub check_libobjs_sources
2254 {
2255   my ($one_file, $unxformed) = @_;
2256
2257   foreach my $prefix ('', 'EXTRA_', 'dist_', 'nodist_',
2258                       'dist_EXTRA_', 'nodist_EXTRA_')
2259     {
2260         my @files;
2261         if (variable_defined ($prefix . $one_file . '_SOURCES'))
2262         {
2263             @files = &variable_value_as_list_recursive (
2264                                 ($prefix . $one_file . '_SOURCES'),
2265                                 'all');
2266         }
2267         elsif ($prefix eq '')
2268         {
2269             @files = ($unxformed . '.c');
2270         }
2271         else
2272         {
2273             next;
2274         }
2275
2276         foreach my $file (@files)
2277         {
2278           err_var ($prefix . $one_file . '_SOURCES',
2279                    "automatically discovered file `$file' should not" .
2280                    " be explicitly mentioned")
2281             if defined $libsources{$file};
2282         }
2283     }
2284 }
2285
2286
2287 # @OBJECTS
2288 # handle_single_transform_list ($VAR, $TOPPARENT, $DERIVED, $OBJ, @FILES)
2289 # -----------------------------------------------------------------------
2290 # Does much of the actual work for handle_source_transform.
2291 # Arguments are:
2292 #   $VAR is the name of the variable that the source filenames come from
2293 #   $TOPPARENT is the name of the _SOURCES variable which is being processed
2294 #   $DERIVED is the name of resulting executable or library
2295 #   $OBJ is the object extension (e.g., `$U.lo')
2296 #   @FILES is the list of source files to transform
2297 # Result is a list of the names of objects
2298 # %linkers_used will be updated with any linkers needed
2299 sub handle_single_transform_list ($$$$@)
2300 {
2301     my ($var, $topparent, $derived, $obj, @files) = @_;
2302     my @result = ();
2303     my $nonansi_obj = $obj;
2304     $nonansi_obj =~ s/\$U//g;
2305
2306     # Turn sources into objects.  We use a while loop like this
2307     # because we might add to @files in the loop.
2308     while (scalar @files > 0)
2309     {
2310         $_ = shift @files;
2311
2312         # Configure substitutions in _SOURCES variables are errors.
2313         if (/^\@.*\@$/)
2314         {
2315             err_var ($var,
2316                      "`$var' includes configure substitution `$_', and is " .
2317                      "referred to\nfrom `$topparent': configure " .
2318                      "substitutions are not allowed\nin _SOURCES variables");
2319             next;
2320         }
2321
2322         # If the source file is in a subdirectory then the `.o' is put
2323         # into the current directory, unless the subdir-objects option
2324         # is in effect.
2325
2326         # Split file name into base and extension.
2327         next if ! /^(?:(.*)\/)?([^\/]*)($KNOWN_EXTENSIONS_PATTERN)$/;
2328         my $full = $_;
2329         my $directory = $1 || '';
2330         my $base = $2;
2331         my $extension = $3;
2332
2333         # We must generate a rule for the object if it requires its own flags.
2334         my $renamed = 0;
2335         my ($linker, $object);
2336
2337         # This records whether we've seen a derived source file (eg,
2338         # yacc output).
2339         my $derived_source = 0;
2340
2341         # This holds the `aggregate context' of the file we are
2342         # currently examining.  If the file is compiled with
2343         # per-object flags, then it will be the name of the object.
2344         # Otherwise it will be `AM'.  This is used by the target hook
2345         # language function.
2346         my $aggregate = 'AM';
2347
2348         $extension = &derive_suffix ($extension, $nonansi_obj);
2349         my $lang;
2350         if ($extension_map{$extension} &&
2351             ($lang = $languages{$extension_map{$extension}}))
2352         {
2353             # Found the language, so see what it says.
2354             &saw_extension ($extension);
2355
2356             # Note: computed subr call.  The language rewrite function
2357             # should return one of the LANG_* constants.  It could
2358             # also return a list whose first value is such a constant
2359             # and whose second value is a new source extension which
2360             # should be applied.  This means this particular language
2361             # generates another source file which we must then process
2362             # further.
2363             my $subr = 'lang_' . $lang->name . '_rewrite';
2364             my ($r, $source_extension)
2365                 = & $subr ($directory, $base, $extension);
2366             # Skip this entry if we were asked not to process it.
2367             next if $r == LANG_IGNORE;
2368
2369             # Now extract linker and other info.
2370             $linker = $lang->linker;
2371
2372             my $this_obj_ext;
2373             if (defined $source_extension)
2374             {
2375                 $this_obj_ext = $source_extension;
2376                 $derived_source = 1;
2377             }
2378             elsif ($lang->ansi)
2379             {
2380                 $this_obj_ext = $obj;
2381             }
2382             else
2383             {
2384                 $this_obj_ext = $nonansi_obj;
2385             }
2386             $object = $base . $this_obj_ext;
2387
2388             # Do we have per-executable flags for this executable?
2389             my $have_per_exec_flags = 0;
2390             foreach my $flag (@{$lang->flags})
2391               {
2392                 if (variable_defined ("${derived}_$flag"))
2393                   {
2394                     $have_per_exec_flags = 1;
2395                     last;
2396                   }
2397               }
2398
2399             if ($have_per_exec_flags)
2400             {
2401                 # We have a per-executable flag in effect for this
2402                 # object.  In this case we rewrite the object's
2403                 # name to ensure it is unique.  We also require
2404                 # the `compile' program to deal with compilers
2405                 # where `-c -o' does not work.
2406
2407                 # We choose the name `DERIVED_OBJECT' to ensure
2408                 # (1) uniqueness, and (2) continuity between
2409                 # invocations.  However, this will result in a
2410                 # name that is too long for losing systems, in
2411                 # some situations.  So we provide _SHORTNAME to
2412                 # override.
2413
2414                 my $dname = $derived;
2415                 if (variable_defined ($derived . '_SHORTNAME'))
2416                 {
2417                     # FIXME: should use the same conditional as
2418                     # the _SOURCES variable.  But this is really
2419                     # silly overkill -- nobody should have
2420                     # conditional shortnames.
2421                     $dname = &variable_value ($derived . '_SHORTNAME');
2422                 }
2423                 $object = $dname . '-' . $object;
2424
2425                 require_conf_file ("$am_file.am", FOREIGN, 'compile')
2426                     if $lang->name eq 'c';
2427
2428                 prog_error ($lang->name . " flags defined without compiler")
2429                   if ! defined $lang->compile;
2430
2431                 $renamed = 1;
2432             }
2433
2434             # If rewrite said it was ok, put the object into a
2435             # subdir.
2436             if ($r == LANG_SUBDIR && $directory ne '')
2437             {
2438                 $object = $directory . '/' . $object;
2439             }
2440
2441             # If doing dependency tracking, then we can't print
2442             # the rule.  If we have a subdir object, we need to
2443             # generate an explicit rule.  Actually, in any case
2444             # where the object is not in `.' we need a special
2445             # rule.  The per-object rules in this case are
2446             # generated later, by handle_languages.
2447             if ($renamed || $directory ne '')
2448             {
2449                 my $obj_sans_ext = substr ($object, 0,
2450                                            - length ($this_obj_ext));
2451                 my $val = ("$full $obj_sans_ext "
2452                            # Only use $this_obj_ext in the derived
2453                            # source case because in the other case we
2454                            # *don't* want $(OBJEXT) to appear here.
2455                            . ($derived_source ? $this_obj_ext : '.o'));
2456
2457                 # If we renamed the object then we want to use the
2458                 # per-executable flag name.  But if this is simply a
2459                 # subdir build then we still want to use the AM_ flag
2460                 # name.
2461                 if ($renamed)
2462                 {
2463                     $val = "$derived $val";
2464                     $aggregate = $derived;
2465                 }
2466                 else
2467                 {
2468                     $val = "AM $val";
2469                 }
2470
2471                 # Each item on this list is a string consisting of
2472                 # four space-separated values: the derived flag prefix
2473                 # (eg, for `foo_CFLAGS', it is `foo'), the name of the
2474                 # source file, the base name of the output file, and
2475                 # the extension for the object file.
2476                 push (@{$lang_specific_files{$lang->name}}, $val);
2477             }
2478         }
2479         elsif ($extension eq $nonansi_obj)
2480         {
2481             # This is probably the result of a direct suffix rule.
2482             # In this case we just accept the rewrite.
2483             $object = "$base$extension";
2484             $linker = '';
2485         }
2486         else
2487         {
2488             # No error message here.  Used to have one, but it was
2489             # very unpopular.
2490             # FIXME: we could potentially do more processing here,
2491             # perhaps treating the new extension as though it were a
2492             # new source extension (as above).  This would require
2493             # more restructuring than is appropriate right now.
2494             next;
2495         }
2496
2497         err_am "object `$object' created by `$full' and `$object_map{$object}'"
2498           if (defined $object_map{$object}
2499               && $object_map{$object} ne $full);
2500
2501         my $comp_val = (($object =~ /\.lo$/)
2502                         ? COMPILE_LIBTOOL : COMPILE_ORDINARY);
2503         (my $comp_obj = $object) =~ s/\.lo$/.\$(OBJEXT)/;
2504         if (defined $object_compilation_map{$comp_obj}
2505             && $object_compilation_map{$comp_obj} != 0
2506             # Only see the error once.
2507             && ($object_compilation_map{$comp_obj}
2508                 != (COMPILE_LIBTOOL | COMPILE_ORDINARY))
2509             && $object_compilation_map{$comp_obj} != $comp_val)
2510           {
2511             err_am "object `$object' created both with libtool and without";
2512           }
2513         $object_compilation_map{$comp_obj} |= $comp_val;
2514
2515         if (defined $lang)
2516         {
2517             # Let the language do some special magic if required.
2518             $lang->target_hook ($aggregate, $object, $full);
2519         }
2520
2521         if ($derived_source)
2522           {
2523             prog_error ($lang->name . " has automatic dependency tracking")
2524               if $lang->autodep ne 'no';
2525             # Make sure this new source file is handled next.  That will
2526             # make it appear to be at the right place in the list.
2527             unshift (@files, $object);
2528             # Distribute derived sources unless the source they are
2529             # derived from is not.
2530             &push_dist_common ($object)
2531               unless ($topparent =~ /^(?:nobase_)?nodist_/);
2532             next;
2533           }
2534
2535         $linkers_used{$linker} = 1;
2536
2537         push (@result, $object);
2538
2539         if (! defined $object_map{$object})
2540         {
2541             my @dep_list = ();
2542             $object_map{$object} = $full;
2543
2544             # If file is in subdirectory, we need explicit
2545             # dependency.
2546             if ($directory ne '' || $renamed)
2547             {
2548                 push (@dep_list, $full);
2549             }
2550
2551             # If resulting object is in subdir, we need to make
2552             # sure the subdir exists at build time.
2553             if ($object =~ /\//)
2554             {
2555                 # FIXME: check that $DIRECTORY is somewhere in the
2556                 # project
2557
2558                 # For Java, the way we're handling it right now, a
2559                 # `..' component doesn't make sense.
2560                 if ($lang->name eq 'java' && $object =~ /(\/|^)\.\.\//)
2561                   {
2562                     err_am "`$full' should not contain a `..' component";
2563                   }
2564
2565                 # Make sure object is removed by `make mostlyclean'.
2566                 $compile_clean_files{$object} = MOSTLY_CLEAN;
2567                 # If we have a libtool object then we also must remove
2568                 # the ordinary .o.
2569                 if ($object =~ /\.lo$/)
2570                 {
2571                     (my $xobj = $object) =~ s,lo$,\$(OBJEXT),;
2572                     $compile_clean_files{$xobj} = MOSTLY_CLEAN;
2573
2574                     # Remove any libtool object in this directory.
2575                     $libtool_clean_directories{$directory} = 1;
2576                 }
2577
2578                 push (@dep_list, require_build_directory ($directory));
2579
2580                 # If we're generating dependencies, we also want
2581                 # to make sure that the appropriate subdir of the
2582                 # .deps directory is created.
2583                 push (@dep_list,
2584                       require_build_directory ($directory . '/$(DEPDIR)'))
2585                     if $use_dependencies;
2586             }
2587
2588             &pretty_print_rule ($object . ':', "\t", @dep_list)
2589                 if scalar @dep_list > 0;
2590         }
2591
2592         # Transform .o or $o file into .P file (for automatic
2593         # dependency code).
2594         if ($lang && $lang->autodep ne 'no')
2595         {
2596             my $depfile = $object;
2597             $depfile =~ s/\.([^.]*)$/.P$1/;
2598             $depfile =~ s/\$\(OBJEXT\)$/o/;
2599             $dep_files{dirname ($depfile) . '/$(DEPDIR)/'
2600                            . basename ($depfile)} = 1;
2601         }
2602     }
2603
2604     return @result;
2605 }
2606
2607 # ($LINKER, $OBJVAR)
2608 # define_objects_from_sources ($VAR, $OBJVAR, $NODEFINE, $ONE_FILE,
2609 #                              $OBJ, $PARENT, $TOPPARENT, $WHERE)
2610 # ---------------------------------------------------------------------
2611 # Define an _OBJECTS variable for a _SOURCES variable (or subvariable)
2612 #
2613 # Arguments are:
2614 #   $VAR is the name of the _SOURCES variable
2615 #   $OBJVAR is the name of the _OBJECTS variable if known (otherwise
2616 #     it will be generated and returned).
2617 #   $NODEFINE is a boolean: if true, $OBJVAR will not be defined (but
2618 #     work done to determine the linker will be).
2619 #   $ONE_FILE is the canonical (transformed) name of object to build
2620 #   $OBJ is the object extension (ie either `.o' or `.lo').
2621 #   $PARENT is the variable in which $VAR is used, or $VAR if not applicable.
2622 #   $TOPPARENT is the _SOURCES variable being processed.
2623 #   $WHERE context into which this definition is done
2624 #
2625 # Result is a pair ($LINKER, $OBJVAR):
2626 #    $LINKER is a boolean, true if a linker is needed to deal with the objects,
2627 #    $OBJVAR is the name of the variable defined to hold the objects.
2628 #
2629 # %linkers_used, %vars_scanned, @substfroms and @substtos should be cleared
2630 # before use:
2631 #   %linkers_used variable will be set to contain the linkers desired.
2632 #   %vars_scanned will be used to check for recursive definitions.
2633 #   @substfroms and @substtos will be used to keep a stack of variable
2634 #   substitutions to be applied.
2635 #
2636 sub define_objects_from_sources ($$$$$$$$)
2637 {
2638     my ($var, $objvar, $nodefine, $one_file, $obj,
2639         $parent, $topparent, $where) = @_;
2640
2641     if (defined $vars_scanned{$var})
2642     {
2643         err_var $var, "variable `$var' recursively defined";
2644         return ("", $objvar || "ERROR");
2645     }
2646     $vars_scanned{$var} = 1;
2647
2648     my $needlinker = "";
2649     my @allresults = ();
2650     foreach my $cond (variable_conditions ($var))
2651     {
2652         my @result;
2653         foreach my $val (&variable_value_as_list ($var, $cond, $parent))
2654         {
2655             # If $val is a variable (i.e. ${foo} or $(bar), not a filename),
2656             # handle the sub variable recursively.
2657             if ($val =~ /^\$\{([^}]*)\}$/ || $val =~ /^\$\(([^)]*)\)$/)
2658             {
2659                 my $subvar = $1;
2660
2661                 # If the user uses a losing variable name, just ignore it.
2662                 # This isn't ideal, but people have requested it.
2663                 next if ($subvar =~ /\@.*\@/);
2664
2665                 # See if the variable is actually a substitution reference
2666                 my ($from, $to);
2667                 my @temp_list;
2668                 if ($subvar =~ /$SUBST_REF_PATTERN/o)
2669                 {
2670                     $subvar = $1;
2671                     $to = $3;
2672                     $from = quotemeta $2;
2673                 }
2674                 push @substfroms, $from;
2675                 push @substtos, $to;
2676
2677                 my ($temp, $varname)
2678                     = define_objects_from_sources ($subvar, undef,
2679                                                    $nodefine, $one_file,
2680                                                    $obj, $var, $topparent,
2681                                                    $where);
2682
2683                 push (@result, '$('. $varname . ')');
2684                 $needlinker ||= $temp;
2685
2686                 pop @substfroms;
2687                 pop @substtos;
2688             }
2689             else # $var is a filename
2690             {
2691                 my $substnum=$#substfroms;
2692                 while ($substnum >= 0)
2693                 {
2694                     $val =~ s/$substfroms[$substnum]$/$substtos[$substnum]/
2695                         if defined $substfroms[$substnum];
2696                     $substnum -= 1;
2697                 }
2698
2699                 my (@transformed) =
2700                       &handle_single_transform_list ($var, $topparent, $one_file, $obj, $val);
2701                 push (@result, @transformed);
2702                 $needlinker = "true" if @transformed;
2703             }
2704         }
2705         push (@allresults, [$cond, @result]);
2706     }
2707     # Find a name for the variable, unless imposed.
2708     $objvar = subobjname (@allresults) unless defined $objvar;
2709     # Define _OBJECTS conditionally
2710     unless ($nodefine)
2711     {
2712         foreach my $pair (@allresults)
2713         {
2714             my ($cond, @result) = @$pair;
2715             define_pretty_variable ($objvar, $cond, $where, @result);
2716         }
2717     }
2718
2719     delete $vars_scanned{$var};
2720     return ($needlinker, $objvar);
2721 }
2722
2723
2724 # $VARNAME
2725 # subobjname (@DEFINITIONS)
2726 # -------------------------
2727 # Return a name for an object variable that with definitions @DEFINITIONS.
2728 # @DEFINITIONS is a list of pair [$COND, @OBJECTS].
2729 #
2730 # If we already have an object variable containing @DEFINITIONS, reuse it.
2731 # This way, we avoid combinatorial explosion of the generated
2732 # variables.  Especially, in a Makefile such as:
2733 #
2734 # | if FOO1
2735 # | A1=1
2736 # | endif
2737 # |
2738 # | if FOO2
2739 # | A2=2
2740 # | endif
2741 # |
2742 # | ...
2743 # |
2744 # | if FOON
2745 # | AN=N
2746 # | endif
2747 # |
2748 # | B=$(A1) $(A2) ... $(AN)
2749 # |
2750 # | c_SOURCES=$(B)
2751 # | d_SOURCES=$(B)
2752 #
2753 # The generated c_OBJECTS and d_OBJECTS will share the same variable
2754 # definitions.
2755 #
2756 # This setup can be the case of a testsuite containing lots (>100) of
2757 # small C programs, all testing the same set of source files.
2758 sub subobjname (@)
2759 {
2760     my $key = '';
2761     foreach my $pair (@_)
2762     {
2763         my ($cond, @values) = @$pair;
2764         $key .= "($cond)@values";
2765     }
2766
2767     return $subobjvar{$key} if exists $subobjvar{$key};
2768
2769     my $num = 1 + keys (%subobjvar);
2770     my $name = "am__objects_${num}";
2771     $subobjvar{$key} = $name;
2772     return $name;
2773 }
2774
2775
2776 # Handle SOURCE->OBJECT transform for one program or library.
2777 # Arguments are:
2778 #   canonical (transformed) name of object to build
2779 #   actual name of object to build
2780 #   object extension (ie either `.o' or `$o'.
2781 # Return result is name of linker variable that must be used.
2782 # Empty return means just use `LINK'.
2783 sub handle_source_transform
2784 {
2785     # one_file is canonical name.  unxformed is given name.  obj is
2786     # object extension.
2787     my ($one_file, $unxformed, $obj, $where) = @_;
2788
2789     my ($linker) = '';
2790
2791     # No point in continuing if _OBJECTS is defined.
2792     return if reject_var ($one_file . '_OBJECTS',
2793                           $one_file . '_OBJECTS should not be defined');
2794
2795     my %used_pfx = ();
2796     my $needlinker;
2797     %linkers_used = ();
2798     foreach my $prefix ('', 'EXTRA_', 'dist_', 'nodist_',
2799                         'dist_EXTRA_', 'nodist_EXTRA_')
2800     {
2801         my $var = $prefix . $one_file . "_SOURCES";
2802         next
2803           if !variable_defined ($var);
2804
2805         # We are going to define _OBJECTS variables using the prefix.
2806         # Then we glom them all together.  So we can't use the null
2807         # prefix here as we need it later.
2808         my $xpfx = ($prefix eq '') ? 'am_' : $prefix;
2809
2810         # Keep track of which prefixes we saw.
2811         $used_pfx{$xpfx} = 1
2812           unless $prefix =~ /EXTRA_/;
2813
2814         push @sources, "\$($var)";
2815         if ($prefix !~ /^nodist_/)
2816           {
2817             # If the VAR wasn't definined conditionally, we add
2818             # it to DIST_SOURCES as is.  Otherwise we create a
2819             # am__VAR_DIST variable which contains all possible values,
2820             # and add this variable to DIST_SOURCES.
2821             my $distvar = "$var";
2822             my @conds = variable_conditions_recursive ($var);
2823             if (@conds && $conds[0] != TRUE)
2824               {
2825                 $distvar = "am__${var}_DIST";
2826                 my @files =
2827                   uniq (variable_value_as_list_recursive ($var, 'all'));
2828                 define_pretty_variable ($distvar, TRUE, $where, @files);
2829               }
2830             push @dist_sources, "\$($distvar)"
2831           }
2832
2833         @substfroms = ();
2834         @substtos = ();
2835         %vars_scanned = ();
2836         my ($temp, $objvar) =
2837             define_objects_from_sources ($var,
2838                                          $xpfx . $one_file . '_OBJECTS',
2839                                          $prefix =~ /EXTRA_/,
2840                                          $one_file, $obj, $var, $var, $where);
2841         $needlinker ||= $temp;
2842     }
2843     if ($needlinker)
2844     {
2845         $linker ||= &resolve_linker (%linkers_used);
2846     }
2847
2848     my @keys = sort keys %used_pfx;
2849     if (scalar @keys == 0)
2850     {
2851         &define_variable ($one_file . "_SOURCES", $unxformed . ".c", $where);
2852         push (@sources, $unxformed . '.c');
2853         push (@dist_sources, $unxformed . '.c');
2854
2855         %linkers_used = ();
2856         my (@result) =
2857           &handle_single_transform_list ($one_file . '_SOURCES',
2858                                          $one_file . '_SOURCES',
2859                                          $one_file, $obj,
2860                                          "$unxformed.c");
2861         $linker ||= &resolve_linker (%linkers_used);
2862         define_pretty_variable ($one_file . '_OBJECTS', TRUE, $where, @result);
2863     }
2864     else
2865     {
2866         grep ($_ = '$(' . $_ . $one_file . '_OBJECTS)', @keys);
2867         define_pretty_variable ($one_file . '_OBJECTS', TRUE, $where, @keys);
2868     }
2869
2870     # If we want to use `LINK' we must make sure it is defined.
2871     if ($linker eq '')
2872     {
2873         $need_link = 1;
2874     }
2875
2876     return $linker;
2877 }
2878
2879
2880 # handle_lib_objects ($XNAME, $VAR)
2881 # ---------------------------------
2882 # Special-case ALLOCA and LIBOBJS substitutions in _LDADD or _LIBADD variables.
2883 # Also, generate _DEPENDENCIES variable if appropriate.
2884 # Arguments are:
2885 #   transformed name of object being built, or empty string if no object
2886 #   name of _LDADD/_LIBADD-type variable to examine
2887 # Returns 1 if LIBOBJS seen, 0 otherwise.
2888 sub handle_lib_objects
2889 {
2890     my ($xname, $var) = @_;
2891
2892     prog_error "handle_lib_objects: $var undefined"
2893       if ! variable_defined ($var);
2894
2895     my $ret = 0;
2896     foreach my $cond (variable_conditions_recursive ($var))
2897       {
2898         if (&handle_lib_objects_cond ($xname, $var, $cond))
2899           {
2900             $ret = 1;
2901           }
2902       }
2903     return $ret;
2904 }
2905
2906 # Subroutine of handle_lib_objects: handle a particular condition.
2907 sub handle_lib_objects_cond
2908 {
2909     my ($xname, $var, $cond) = @_;
2910
2911     # We recognize certain things that are commonly put in LIBADD or
2912     # LDADD.
2913     my @dep_list = ();
2914
2915     my $seen_libobjs = 0;
2916     my $flagvar = 0;
2917
2918     foreach my $lsearch (&variable_value_as_list_recursive ($var, $cond))
2919     {
2920         # Skip -lfoo and -Ldir; these are explicitly allowed.
2921         next if $lsearch =~ /^-[lL]/;
2922         if (! $flagvar && $lsearch =~ /^-/)
2923         {
2924             if ($var =~ /^(.*)LDADD$/)
2925             {
2926                 # Skip -dlopen and -dlpreopen; these are explicitly allowed.
2927                 next if $lsearch =~ /^-dl(pre)?open$/;
2928                 my $prefix = $1 || 'AM_';
2929                 err_var ($var, "linker flags such as `$lsearch' belong in "
2930                          . "`${prefix}LDFLAGS");
2931             }
2932             else
2933             {
2934                 $var =~ /^(.*)LIBADD$/;
2935                 # Only get this error once.
2936                 $flagvar = 1;
2937                 err_var ($var, "linker flags such as `$lsearch' belong in "
2938                          . "`${1}LDFLAGS");
2939             }
2940         }
2941
2942         # Assume we have a file of some sort, and push it onto the
2943         # dependency list.  Autoconf substitutions are not pushed;
2944         # rarely is a new dependency substituted into (eg) foo_LDADD
2945         # -- but "bad things (eg -lX11) are routinely substituted.
2946         # Note that LIBOBJS and ALLOCA are exceptions to this rule,
2947         # and handled specially below.
2948         push (@dep_list, $lsearch)
2949             unless $lsearch =~ /^\@.*\@$/;
2950
2951         # Automatically handle LIBOBJS and ALLOCA substitutions.
2952         # Basically this means adding entries to dep_files.
2953         if ($lsearch =~ /^\@(LT)?LIBOBJS\@$/)
2954         {
2955             my $lt = $1 ? $1 : '';
2956             my $myobjext = ($1 ? 'l' : '') . 'o';
2957
2958             push (@dep_list, $lsearch);
2959             $seen_libobjs = 1;
2960             if (! keys %libsources
2961                 && ! variable_defined ($lt . 'LIBOBJS'))
2962             {
2963                 err_var ($var, "\@${lt}LIBOBJS\@ seen but never set in "
2964                          . "`$configure_ac'");
2965             }
2966
2967             foreach my $iter (keys %libsources)
2968             {
2969                 if ($iter =~ /\.[cly]$/)
2970                 {
2971                     &saw_extension ($&);
2972                     &saw_extension ('.c');
2973                 }
2974
2975                 if ($iter =~ /\.h$/)
2976                 {
2977                     require_file_with_macro ($cond, $var, FOREIGN, $iter);
2978                 }
2979                 elsif ($iter ne 'alloca.c')
2980                 {
2981                     my $rewrite = $iter;
2982                     $rewrite =~ s/\.c$/.P$myobjext/;
2983                     $dep_files{'$(DEPDIR)/' . $rewrite} = 1;
2984                     $rewrite = "^" . quotemeta ($iter) . "\$";
2985                     # Only require the file if it is not a built source.
2986                     if (! variable_defined ('BUILT_SOURCES')
2987                         || ! grep (/$rewrite/,
2988                                    &variable_value_as_list_recursive (
2989                                         'BUILT_SOURCES', 'all')))
2990                     {
2991                         require_file_with_macro ($cond, $var, FOREIGN, $iter);
2992                     }
2993                 }
2994             }
2995         }
2996         elsif ($lsearch =~ /^\@(LT)?ALLOCA\@$/)
2997         {
2998             my $lt = $1 ? $1 : '';
2999             my $myobjext = ($1 ? 'l' : '') . 'o';
3000
3001             push (@dep_list, $lsearch);
3002             err_var ($var, "\@${lt}ALLOCA\@ seen but `AC_FUNC_ALLOCA' not in "
3003                      . "`$configure_ac'")
3004               if ! defined $libsources{'alloca.c'};
3005             $dep_files{'$(DEPDIR)/alloca.P' . $myobjext} = 1;
3006             require_file_with_macro ($cond, $var, FOREIGN, 'alloca.c');
3007             &saw_extension ('c');
3008         }
3009     }
3010
3011   if ($xname ne '')
3012     {
3013       my $depvar = $xname . '_DEPENDENCIES';
3014       if ((conditional_ambiguous_p ($depvar, $cond,
3015                                     keys %{$var_value{$depvar}}))[0] ne '')
3016         {
3017           # Note that we've examined this.
3018           &examine_variable ($depvar);
3019         }
3020       else
3021         {
3022           define_pretty_variable ($depvar, $cond, INTERNAL, @dep_list);
3023         }
3024     }
3025
3026   return $seen_libobjs;
3027 }
3028
3029 # Canonicalize the input parameter
3030 sub canonicalize
3031 {
3032     my ($string) = @_;
3033     $string =~ tr/A-Za-z0-9_\@/_/c;
3034     return $string;
3035 }
3036
3037 # Canonicalize a name, and check to make sure the non-canonical name
3038 # is never used.  Returns canonical name.  Arguments are name and a
3039 # list of suffixes to check for.
3040 sub check_canonical_spelling
3041 {
3042   my ($name, @suffixes) = @_;
3043
3044   my $xname = &canonicalize ($name);
3045   if ($xname ne $name)
3046     {
3047       foreach my $xt (@suffixes)
3048         {
3049           reject_var ("$name$xt", "use `$xname$xt', not `$name$xt'");
3050         }
3051     }
3052
3053   return $xname;
3054 }
3055
3056
3057 # handle_compile ()
3058 # -----------------
3059 # Set up the compile suite.
3060 sub handle_compile ()
3061 {
3062     return
3063       unless $get_object_extension_was_run;
3064
3065     # Boilerplate.
3066     my $default_includes = '';
3067     if (! defined $options{'nostdinc'})
3068       {
3069         $default_includes = ' -I. -I$(srcdir)';
3070
3071         if (variable_defined ('CONFIG_HEADER'))
3072           {
3073             foreach my $hdr (split (' ', &variable_value ('CONFIG_HEADER')))
3074               {
3075                 $default_includes .= ' -I' . dirname ($hdr);
3076               }
3077           }
3078       }
3079
3080     my (@mostly_rms, @dist_rms);
3081     foreach my $item (sort keys %compile_clean_files)
3082     {
3083         if ($compile_clean_files{$item} == MOSTLY_CLEAN)
3084         {
3085             push (@mostly_rms, "\t-rm -f $item");
3086         }
3087         elsif ($compile_clean_files{$item} == DIST_CLEAN)
3088         {
3089             push (@dist_rms, "\t-rm -f $item");
3090         }
3091         else
3092         {
3093           prog_error 'invalid entry in %compile_clean_files';
3094         }
3095     }
3096
3097     my ($coms, $vars, $rules) =
3098       &file_contents_internal (1, "$libdir/am/compile.am",
3099                                new Automake::Location,
3100                                ('DEFAULT_INCLUDES' => $default_includes,
3101                                 'MOSTLYRMS' => join ("\n", @mostly_rms),
3102                                 'DISTRMS' => join ("\n", @dist_rms)));
3103     $output_vars .= $vars;
3104     $output_rules .= "$coms$rules";
3105
3106     # Check for automatic de-ANSI-fication.
3107     if (defined $options{'ansi2knr'})
3108       {
3109         require_variables_for_macro ('AUTOMAKE_OPTIONS',
3110                                      "option `ansi2knr' is used",
3111                                      "ANSI2KNR", "U");
3112
3113         # topdir is where ansi2knr should be.
3114         if ($options{'ansi2knr'} eq 'ansi2knr')
3115           {
3116             # Only require ansi2knr files if they should appear in
3117             # this directory.
3118             require_file_with_macro (TRUE, 'AUTOMAKE_OPTIONS', FOREIGN,
3119                                      'ansi2knr.c', 'ansi2knr.1');
3120
3121             # ansi2knr needs to be built before subdirs, so unshift it.
3122             unshift (@all, '$(ANSI2KNR)');
3123           }
3124
3125         my $ansi2knr_dir = '';
3126         $ansi2knr_dir = dirname ($options{'ansi2knr'})
3127           if $options{'ansi2knr'} ne 'ansi2knr';
3128
3129         $output_rules .= &file_contents ('ansi2knr',
3130                                          new Automake::Location,
3131                                          'ANSI2KNR-DIR' => $ansi2knr_dir);
3132
3133     }
3134 }
3135
3136 # handle_libtool ()
3137 # -----------------
3138 # Handle libtool rules.
3139 sub handle_libtool
3140 {
3141   return unless variable_defined ('LIBTOOL');
3142
3143   # Libtool requires some files, but only at top level.
3144   require_conf_file_with_macro (TRUE, 'LIBTOOL', FOREIGN, @libtool_files)
3145     if $relative_dir eq '.';
3146
3147   my @libtool_rms;
3148   foreach my $item (sort keys %libtool_clean_directories)
3149     {
3150       my $dir = ($item eq '.') ? '' : "$item/";
3151       # .libs is for Unix, _libs for DOS.
3152       push (@libtool_rms, "\t-rm -rf ${dir}.libs ${dir}_libs");
3153     }
3154
3155   # Output the libtool compilation rules.
3156   $output_rules .= &file_contents ('libtool',
3157                                    new Automake::Location,
3158                                    LTRMS => join ("\n", @libtool_rms));
3159 }
3160
3161 # handle_programs ()
3162 # ------------------
3163 # Handle C programs.
3164 sub handle_programs
3165 {
3166   my @proglist = &am_install_var ('progs', 'PROGRAMS',
3167                                   'bin', 'sbin', 'libexec', 'pkglib',
3168                                   'noinst', 'check');
3169   return if ! @proglist;
3170
3171   my $seen_global_libobjs =
3172     variable_defined ('LDADD') && &handle_lib_objects ('', 'LDADD');
3173
3174   foreach my $pair (@proglist)
3175     {
3176       my ($where, $one_file) = @$pair;
3177
3178       my $seen_libobjs = 0;
3179       my $obj = &get_object_extension ($one_file);
3180
3181       # Canonicalize names and check for misspellings.
3182       my $xname = &check_canonical_spelling ($one_file, '_LDADD', '_LDFLAGS',
3183                                              '_SOURCES', '_OBJECTS',
3184                                              '_DEPENDENCIES');
3185
3186       $where->push_context ("while processing program `$one_file'");
3187       $where->set (INTERNAL->get);
3188
3189       my $linker = &handle_source_transform ($xname, $one_file, $obj, $where);
3190
3191       my $xt = '';
3192       if (variable_defined ($xname . "_LDADD"))
3193         {
3194           $seen_libobjs = &handle_lib_objects ($xname, $xname . '_LDADD');
3195           $xt = '_LDADD';
3196         }
3197       else
3198         {
3199           # User didn't define prog_LDADD override.  So do it.
3200           &define_variable ($xname . '_LDADD', '$(LDADD)', $where);
3201
3202           # This does a bit too much work.  But we need it to
3203           # generate _DEPENDENCIES when appropriate.
3204           if (variable_defined ('LDADD'))
3205             {
3206               $seen_libobjs = &handle_lib_objects ($xname, 'LDADD');
3207             }
3208           elsif (! variable_defined ($xname . '_DEPENDENCIES'))
3209             {
3210               &define_variable ($xname . '_DEPENDENCIES', '', $where);
3211             }
3212           $xt = '_SOURCES';
3213         }
3214
3215       reject_var ($xname . '_LIBADD',
3216                   "use `${xname}_LDADD', not `${xname}_LIBADD'");
3217
3218       if (! variable_defined ($xname . '_LDFLAGS'))
3219         {
3220           # Define the prog_LDFLAGS variable.
3221           &define_variable ($xname . '_LDFLAGS', '', $where);
3222         }
3223
3224       # Determine program to use for link.
3225       my $xlink;
3226       if (variable_defined ($xname . '_LINK'))
3227         {
3228           $xlink = $xname . '_LINK';
3229         }
3230       else
3231         {
3232           $xlink = $linker ? $linker : 'LINK';
3233         }
3234
3235       # If the resulting program lies into a subdirectory,
3236       # make sure this directory will exist.
3237       my $dirstamp = require_build_directory_maybe ($one_file);
3238
3239       # Don't add $(EXEEXT) if user already did.
3240       my $extension = ($one_file !~ /\$\(EXEEXT\)$/
3241                        ? "\$(EXEEXT)"
3242                        : '');
3243
3244       $output_rules .= &file_contents ('program',
3245                                        $where,
3246                                        PROGRAM  => $one_file,
3247                                        XPROGRAM => $xname,
3248                                        XLINK    => $xlink,
3249                                        DIRSTAMP => $dirstamp,
3250                                        EXEEXT   => $extension);
3251
3252       if ($seen_libobjs || $seen_global_libobjs)
3253         {
3254           if (variable_defined ($xname . '_LDADD'))
3255             {
3256               &check_libobjs_sources ($xname, $xname . '_LDADD');
3257             }
3258           elsif (variable_defined ('LDADD'))
3259             {
3260               &check_libobjs_sources ($xname, 'LDADD');
3261             }
3262         }
3263     }
3264 }
3265
3266
3267 # handle_libraries ()
3268 # -------------------
3269 # Handle libraries.
3270 sub handle_libraries
3271 {
3272   my @liblist = &am_install_var ('libs', 'LIBRARIES',
3273                                  'lib', 'pkglib', 'noinst', 'check');
3274   return if ! @liblist;
3275
3276   my @prefix = am_primary_prefixes ('LIBRARIES', 0, 'lib', 'pkglib',
3277                                     'noinst', 'check');
3278
3279   require_variables_for_macro ($prefix[0] . '_LIBRARIES',
3280                                'library used', 'RANLIB')
3281     if (@prefix);
3282
3283   foreach my $pair (@liblist)
3284     {
3285       my ($where, $onelib) = @$pair;
3286
3287       my $seen_libobjs = 0;
3288       # Check that the library fits the standard naming convention.
3289       if (basename ($onelib) !~ /^lib.*\.a/)
3290         {
3291           err $where, "`$onelib' is not a standard library name";
3292         }
3293
3294       $where->push_context ("while processing library `$onelib'");
3295       $where->set (INTERNAL->get);
3296
3297       my $obj = &get_object_extension ($onelib);
3298
3299       # Canonicalize names and check for misspellings.
3300       my $xlib = &check_canonical_spelling ($onelib, '_LIBADD', '_SOURCES',
3301                                             '_OBJECTS', '_DEPENDENCIES',
3302                                             '_AR');
3303
3304       if (! variable_defined ($xlib . '_AR'))
3305         {
3306           &define_variable ($xlib . '_AR', '$(AR) cru', $where);
3307         }
3308
3309       if (variable_defined ($xlib . '_LIBADD'))
3310         {
3311           if (&handle_lib_objects ($xlib, $xlib . '_LIBADD'))
3312             {
3313               $seen_libobjs = 1;
3314             }
3315         }
3316       else
3317         {
3318           # Generate support for conditional object inclusion in
3319           # libraries.
3320           &define_variable ($xlib . "_LIBADD", '', $where);
3321         }
3322
3323       reject_var ($xlib . '_LDADD',
3324                   "use `${xlib}_LIBADD', not `${xlib}_LDADD'");
3325
3326       # Make sure we at look at this.
3327       &examine_variable ($xlib . '_DEPENDENCIES');
3328
3329       &handle_source_transform ($xlib, $onelib, $obj, $where);
3330
3331       # If the resulting library lies into a subdirectory,
3332       # make sure this directory will exist.
3333       my $dirstamp = require_build_directory_maybe ($onelib);
3334
3335       $output_rules .= &file_contents ('library',
3336                                        $where,
3337                                        LIBRARY  => $onelib,
3338                                        XLIBRARY => $xlib,
3339                                        DIRSTAMP => $dirstamp);
3340
3341       if ($seen_libobjs)
3342         {
3343           if (variable_defined ($xlib . '_LIBADD'))
3344             {
3345               &check_libobjs_sources ($xlib, $xlib . '_LIBADD');
3346             }
3347         }
3348     }
3349 }
3350
3351
3352 # handle_ltlibraries ()
3353 # ---------------------
3354 # Handle shared libraries.
3355 sub handle_ltlibraries
3356 {
3357   my @liblist = &am_install_var ('ltlib', 'LTLIBRARIES',
3358                                  'noinst', 'lib', 'pkglib', 'check');
3359   return if ! @liblist;
3360
3361   my %instdirs;
3362   my @prefix = am_primary_prefixes ('LTLIBRARIES', 0, 'lib', 'pkglib',
3363                                     'noinst', 'check');
3364
3365   require_variables_for_macro ($prefix[0] . '_LTLIBRARIES',
3366                                'Libtool library used', 'LIBTOOL')
3367     if (@prefix);
3368
3369   my %liblocations = ();        # Location (in Makefile.am) of each library.
3370
3371   foreach my $key (@prefix)
3372     {
3373       # Get the installation directory of each library.
3374       (my $dir = $key) =~ s/^nobase_//;
3375       for my $pair (variable_loc_and_value_as_list_recursive
3376                     ($key . '_LTLIBRARIES', 'all'))
3377         {
3378           my ($where, $lib) = @$pair;
3379           # We reject libraries which are installed in several places,
3380           # because we don't handle this in the rules (think `-rpath').
3381           #
3382           # However, we allow the same library to be listed many times
3383           # for the same directory.  This is for users who need setups
3384           # like
3385           #   if COND1
3386           #     lib_LTLIBRARIES = libfoo.la
3387           #   endif
3388           #   if COND2
3389           #     lib_LTLIBRARIES = libfoo.la
3390           #   endif
3391           #
3392           # Actually this will also allow
3393           #   lib_LTLIBRARIES = libfoo.la libfoo.la
3394           # Diagnosing this case doesn't seem worth the plain (we'd
3395           # have to fill $instdirs on a per-condition basis, check
3396           # implied conditions, etc.)
3397           if (defined $instdirs{$lib} && $instdirs{$lib} ne $dir)
3398             {
3399               err ($where, "`$lib' is already going to be installed in "
3400                    . "`$instdirs{$lib}'", partial => 1);
3401               err ($liblocations{$lib}, "`$lib' previously declared here");
3402             }
3403           else
3404             {
3405               $instdirs{$lib} = $dir;
3406               $liblocations{$lib} = $where->clone;
3407             }
3408         }
3409     }
3410
3411   foreach my $pair (@liblist)
3412     {
3413       my ($where, $onelib) = @$pair;
3414
3415       my $seen_libobjs = 0;
3416       my $obj = &get_object_extension ($onelib);
3417
3418       # Canonicalize names and check for misspellings.
3419       my $xlib = &check_canonical_spelling ($onelib, '_LIBADD', '_LDFLAGS',
3420                                             '_SOURCES', '_OBJECTS',
3421                                             '_DEPENDENCIES');
3422
3423       # Check that the library fits the standard naming convention.
3424       my $libname_rx = "^lib.*\.la";
3425       if ((variable_defined ($xlib . '_LDFLAGS')
3426            && grep (/-module/,
3427                     &variable_value_as_list_recursive ($xlib . '_LDFLAGS',
3428                                                        'all')))
3429           || (variable_defined ('LDFLAGS')
3430               && grep (/-module/,
3431                        &variable_value_as_list_recursive ('LDFLAGS', 'all'))))
3432         {
3433           # Relax name checking for libtool modules.
3434           $libname_rx = "\.la";
3435         }
3436       if (basename ($onelib) !~ /$libname_rx$/)
3437         {
3438           msg ($where, 'error-gnu/warn',
3439                "`$onelib' is not a standard libtool library name");
3440         }
3441
3442       $where->push_context ("while processing Libtool library `$onelib'");
3443       $where->set (INTERNAL->get);
3444
3445       if (! variable_defined ($xlib . '_LDFLAGS'))
3446         {
3447           # Define the lib_LDFLAGS variable.
3448           &define_variable ($xlib . '_LDFLAGS', '', $where);
3449         }
3450
3451       if (variable_defined ($xlib . '_LIBADD'))
3452         {
3453           if (&handle_lib_objects ($xlib, $xlib . '_LIBADD'))
3454             {
3455               $seen_libobjs = 1;
3456             }
3457         }
3458       else
3459         {
3460           # Generate support for conditional object inclusion in
3461           # libraries.
3462           &define_variable ($xlib . "_LIBADD", '', $where);
3463         }
3464
3465       reject_var ("${xlib}_LDADD",
3466                   "use `${xlib}_LIBADD', not `${xlib}_LDADD'");
3467
3468       # Make sure we at look at this.
3469       &examine_variable ($xlib . '_DEPENDENCIES');
3470
3471       my $linker = &handle_source_transform ($xlib, $onelib, $obj, $where);
3472
3473       # Determine program to use for link.
3474       my $xlink;
3475       if (variable_defined ($xlib . '_LINK'))
3476         {
3477           $xlink = $xlib . '_LINK';
3478         }
3479       else
3480         {
3481           $xlink = $linker ? $linker : 'LINK';
3482         }
3483
3484       my $rpath;
3485       if ($instdirs{$onelib} eq 'EXTRA'
3486           || $instdirs{$onelib} eq 'noinst'
3487           || $instdirs{$onelib} eq 'check')
3488         {
3489           # It's an EXTRA_ library, so we can't specify -rpath,
3490           # because we don't know where the library will end up.
3491           # The user probably knows, but generally speaking automake
3492           # doesn't -- and in fact configure could decide
3493           # dynamically between two different locations.
3494           $rpath = '';
3495         }
3496       else
3497         {
3498           $rpath = ('-rpath $(' . $instdirs{$onelib} . 'dir)');
3499         }
3500
3501       # If the resulting library lies into a subdirectory,
3502       # make sure this directory will exist.
3503       my $dirstamp = require_build_directory_maybe ($onelib);
3504
3505       # Remember to cleanup .libs/ in this directory.
3506       my $dirname = dirname $onelib;
3507       $libtool_clean_directories{$dirname} = 1;
3508
3509       $output_rules .= &file_contents ('ltlibrary',
3510                                        $where,
3511                                        LTLIBRARY  => $onelib,
3512                                        XLTLIBRARY => $xlib,
3513                                        RPATH      => $rpath,
3514                                        XLINK      => $xlink,
3515                                        DIRSTAMP   => $dirstamp);
3516       if ($seen_libobjs)
3517         {
3518           if (variable_defined ($xlib . '_LIBADD'))
3519             {
3520               &check_libobjs_sources ($xlib, $xlib . '_LIBADD');
3521             }
3522         }
3523     }
3524 }
3525
3526 # See if any _SOURCES variable were misspelled.
3527 sub check_typos ()
3528 {
3529   # It is ok if the user sets this particular variable.
3530   &examine_variable ('AM_LDFLAGS');
3531
3532   foreach my $varname (keys %var_value)
3533     {
3534       foreach my $primary ('_SOURCES', '_LIBADD', '_LDADD', '_LDFLAGS',
3535                            '_DEPENDENCIES')
3536         {
3537           msg_var 'syntax', $varname, "unused variable: `$varname'"
3538             # Note that a configure variable is always legitimate.
3539             if ($varname =~ /$primary$/ && ! $content_seen{$varname}
3540                 && ! exists $configure_vars{$varname});
3541         }
3542     }
3543 }
3544
3545
3546 # Handle scripts.
3547 sub handle_scripts
3548 {
3549     # NOTE we no longer automatically clean SCRIPTS, because it is
3550     # useful to sometimes distribute scripts verbatim.  This happens
3551     # eg in Automake itself.
3552     &am_install_var ('-candist', 'scripts', 'SCRIPTS',
3553                      'bin', 'sbin', 'libexec', 'pkgdata',
3554                      'noinst', 'check');
3555 }
3556
3557
3558 # ($OUTFILE, $VFILE, @CLEAN_FILES)
3559 # &scan_texinfo_file ($FILENAME)
3560 # ------------------------------
3561 # $OUTFILE is the name of the info file produced by $FILENAME.
3562 # $VFILE is the name of the version.texi file used (empty if none).
3563 # @CLEAN_FILES is the list of by products (indexes etc.)
3564 sub scan_texinfo_file
3565 {
3566     my ($filename) = @_;
3567
3568     # These are always created, no matter whether indexes are used or not.
3569     # (Actually tmp is only created if an @macro is used and a certain e-TeX
3570     # feature is not available.)
3571     my @clean_suffixes = qw(aux log toc tmp
3572                             cp fn ky vr tp pg); # grep new.*index texinfo.tex
3573
3574     # There are predefined indexes which don't follow the regular rules.
3575     my %predefined_index = qw(c cps
3576                               f fns
3577                               k kys
3578                               v vrs
3579                               t tps
3580                               p pgs);
3581
3582     # There are commands which include a hidden index command.
3583     my %hidden_index = (tp => 'tps');
3584     $hidden_index{$_} = 'fns' foreach qw(fn un typefn typefun max spec
3585                                          op typeop method typemethod);
3586     $hidden_index{$_} = 'vrs' foreach qw(vr var typevr typevar opt cv
3587                                          ivar typeivar);
3588
3589     # Indexes stored into another one.  In this case, the *.??s file
3590     # is not created.
3591     my @syncodeindexes = ();
3592
3593     my $texi = new Automake::XFile "< $filename";
3594     verb "reading $filename";
3595
3596     my ($outfile, $vfile);
3597     while ($_ = $texi->getline)
3598     {
3599       if (/^\@setfilename +(\S+)/)
3600       {
3601         $outfile = $1;
3602         if ($outfile =~ /\.(.+)$/ && $1 ne 'info')
3603           {
3604             err "$filename:$.", "output `$outfile' has unrecognized extension";
3605             return;
3606           }
3607       }
3608       # A "version.texi" file is actually any file whose name
3609       # matches "vers*.texi".
3610       elsif (/^\@include\s+(vers[^.]*\.texi)\s*$/)
3611       {
3612         $vfile = $1;
3613       }
3614
3615       # Try to find what are the indexes which are used.
3616
3617       # Creating a new category of index.
3618       elsif (/^\@def(code)?index (\w+)/)
3619       {
3620         push @clean_suffixes, $2;
3621       }
3622
3623       # Storing in a predefined index.
3624       elsif (/^\@([cfkvtp])index /)
3625       {
3626         push @clean_suffixes, $predefined_index{$1};
3627       }
3628       elsif (/^\@def(\w+) /)
3629       {
3630         push @clean_suffixes, $hidden_index{$1}
3631           if defined $hidden_index{$1};
3632       }
3633
3634       # Merging an index into an another.
3635       elsif (/^\@syn(code)?index (\w+) (\w+)/)
3636       {
3637         push @syncodeindexes, "$2s";
3638         push @clean_suffixes, "$3s";
3639       }
3640
3641     }
3642
3643     if ($outfile eq '')
3644       {
3645         err_am "`$filename' missing \@setfilename";
3646         return;
3647       }
3648
3649     my $infobase = basename ($filename);
3650     $infobase =~ s/\.te?xi(nfo)?$//;
3651     my %clean_files = map { +"$infobase.$_" => 1 } @clean_suffixes;
3652     grep { delete $clean_files{"$infobase.$_"} } @syncodeindexes;
3653     return ($outfile, $vfile, (sort keys %clean_files));
3654 }
3655
3656 # ($DIRSTAMP, @CLEAN_FILES)
3657 # output_texinfo_build_rules ($SOURCE, $DEST, @DEPENDENCIES)
3658 # ----------------------------------------------------------
3659 # SOURCE - the source Texinfo file
3660 # DEST - the destination Info file
3661 # DEPENDENCIES - known dependencies
3662 sub output_texinfo_build_rules ($$@)
3663 {
3664   my ($source, $dest, @deps) = @_;
3665
3666   # Split `a.texi' into `a' and `.texi'.
3667   my ($spfx, $ssfx) = ($source =~ /^(.*?)(\.[^.]*)?$/);
3668   my ($dpfx, $dsfx) = ($dest =~ /^(.*?)(\.[^.]*)?$/);
3669
3670   $ssfx ||= "";
3671   $dsfx ||= "";
3672
3673   # We can output two kinds of rules: the "generic" rules
3674   # use Make suffix rules and are appropritate when
3675   # $source and $dest lie in the current directory; the "specifix"
3676   # rules is needed in the other case.
3677   #
3678   # The former are output only once (this is not really apparent
3679   # here, but just remember that some logic deeper in Automake will
3680   # not output the same rule twice); while the later need to be output
3681   # for each Texinfo source.
3682   my $generic;
3683   my $makeinfoflags;
3684   my $sdir = dirname $source;
3685   if ($sdir eq '.' && dirname ($dest) eq '.')
3686     {
3687       $generic = 1;
3688       $makeinfoflags = '-I $(srcdir)';
3689     }
3690   else
3691     {
3692       $generic = 0;
3693       $makeinfoflags = "-I $sdir -I \$(srcdir)/$sdir";
3694     }
3695
3696   # If the resulting file lie into a subdirectory,
3697   # make sure this directory will exist.
3698   my $dirstamp = require_build_directory_maybe ($dest);
3699
3700   $output_rules .= &file_contents ('texibuild',
3701                                    new Automake::Location,
3702                                    GENERIC       => $generic,
3703                                    SOURCE_SUFFIX => $ssfx,
3704                                    SOURCE => ($generic ? '$<' : $source),
3705                                    SOURCE_REAL   => $source,
3706                                    DEST_PREFIX   => $dpfx,
3707                                    DEST_SUFFIX   => $dsfx,
3708                                    MAKEINFOFLAGS => $makeinfoflags,
3709                                    DEPS          => "@deps",
3710                                    DIRSTAMP      => $dirstamp);
3711   return ($dirstamp, "$dpfx.dvi", "$dpfx.pdf", "$dpfx.ps");
3712 }
3713
3714
3715 # ($DO-SOMETHING, $TEXICLEANS)
3716 # handle_texinfo_helper ()
3717 # ------------------------
3718 # Handle all Texinfo source; helper for handle_texinfo
3719 sub handle_texinfo_helper
3720 {
3721     reject_var 'TEXINFOS', "`TEXINFOS' is an anachronism; use `info_TEXINFOS'";
3722     reject_var 'html_TEXINFOS', "HTML generation not yet supported";
3723
3724     return (0, '') if ! variable_defined ('info_TEXINFOS');
3725
3726     my @texis = &variable_value_as_list_recursive ('info_TEXINFOS', 'all');
3727
3728     my (@info_deps_list, @dvis_list, @pdfs_list, @pss_list, @texi_deps);
3729     my %versions;
3730     my $done = 0;
3731     my @texi_cleans;
3732     my $canonical;
3733
3734     foreach my $info_cursor (@texis)
3735     {
3736         my $infobase = $info_cursor;
3737         $infobase =~ s/\.(txi|texinfo|texi)$//;
3738
3739         if ($infobase eq $info_cursor)
3740           {
3741             # FIXME: report line number.
3742             err_am "texinfo file `$info_cursor' has unrecognized extension";
3743             next;
3744           }
3745
3746         # If 'version.texi' is referenced by input file, then include
3747         # automatic versioning capability.
3748         my ($out_file, $vtexi, @clean_files) =
3749           &scan_texinfo_file ("$relative_dir/$info_cursor")
3750             or next;
3751         push (@texi_cleans, @clean_files);
3752
3753         # If the Texinfo source is in a subdirectory, create the
3754         # resulting info in this subdirectory.  If it is in the
3755         # current directory, try hard to not prefix "./" because
3756         # it breaks the generic rules.
3757         my $outdir = dirname ($info_cursor) . '/';
3758         $outdir = "" if $outdir eq './';
3759         $out_file =  $outdir . $out_file;
3760
3761         # If user specified file_TEXINFOS, then use that as explicit
3762         # dependency list.
3763         @texi_deps = ();
3764         push (@texi_deps, "$outdir$vtexi") if $vtexi;
3765
3766         my $canonical = &canonicalize ($infobase);
3767         if (variable_defined ($canonical . "_TEXINFOS"))
3768         {
3769             push (@texi_deps, '$(' . $canonical . '_TEXINFOS)');
3770             &push_dist_common ('$(' . $canonical . '_TEXINFOS)');
3771         }
3772
3773         my ($dirstamp, @cfiles) =
3774           output_texinfo_build_rules ($info_cursor, $out_file, @texi_deps);
3775         push (@texi_cleans, @cfiles);
3776
3777         push (@info_deps_list, $out_file);
3778         push (@dvis_list, $infobase . '.dvi');
3779         push (@pdfs_list, $infobase . '.pdf');
3780         push (@pss_list, $infobase . '.ps');
3781
3782         # If a vers*.texi file is needed, emit the rule.
3783         if ($vtexi)
3784         {
3785             err_am ("`$vtexi', included in `$info_cursor', "
3786                     . "also included in `$versions{$vtexi}'")
3787               if defined $versions{$vtexi};
3788             $versions{$vtexi} = $info_cursor;
3789
3790             # We number the stamp-vti files.  This is doable since the
3791             # actual names don't matter much.  We only number starting
3792             # with the second one, so that the common case looks nice.
3793             my $vti = ($done ? $done : 'vti');
3794             ++$done;
3795
3796             # This is ugly, but it is our historical practice.
3797             if ($config_aux_dir_set_in_configure_in)
3798             {
3799                 require_conf_file_with_macro (TRUE, 'info_TEXINFOS', FOREIGN,
3800                                               'mdate-sh');
3801             }
3802             else
3803             {
3804                 require_file_with_macro (TRUE, 'info_TEXINFOS',
3805                                          FOREIGN, 'mdate-sh');
3806             }
3807
3808             my $conf_dir;
3809             if ($config_aux_dir_set_in_configure_in)
3810             {
3811                 $conf_dir = $config_aux_dir;
3812                 $conf_dir .= '/' unless $conf_dir =~ /\/$/;
3813             }
3814             else
3815             {
3816                 $conf_dir = '$(srcdir)/';
3817             }
3818             $output_rules .= &file_contents ('texi-vers',
3819                                              new Automake::Location,
3820                                              TEXI     => $info_cursor,
3821                                              VTI      => $vti,
3822                                              STAMPVTI => "${outdir}stamp-$vti",
3823                                              VTEXI    => "$outdir$vtexi",
3824                                              MDDIR    => $conf_dir,
3825                                              DIRSTAMP => $dirstamp);
3826         }
3827     }
3828
3829     # Handle location of texinfo.tex.
3830     my $need_texi_file = 0;
3831     my $texinfodir;
3832     if ($cygnus_mode)
3833     {
3834         $texinfodir = '$(top_srcdir)/../texinfo';
3835         &define_variable ('TEXINFO_TEX', "$texinfodir/texinfo.tex", INTERNAL);
3836     }
3837     elsif ($config_aux_dir_set_in_configure_in)
3838     {
3839         $texinfodir = $config_aux_dir;
3840         &define_variable ('TEXINFO_TEX', "$texinfodir/texinfo.tex", INTERNAL);
3841         $need_texi_file = 2; # so that we require_conf_file later
3842     }
3843     elsif (variable_defined ('TEXINFO_TEX'))
3844     {
3845         # The user defined TEXINFO_TEX so assume he knows what he is
3846         # doing.
3847         $texinfodir = ('$(srcdir)/'
3848                        . dirname (&variable_value ('TEXINFO_TEX')));
3849     }
3850     else
3851     {
3852         $texinfodir = '$(srcdir)';
3853         $need_texi_file = 1;
3854     }
3855     &define_variable ('am__TEXINFO_TEX_DIR', $texinfodir, INTERNAL);
3856
3857     # The return value.
3858     my $texiclean = &pretty_print_internal ("", "\t  ", @texi_cleans);
3859
3860     push (@dist_targets, 'dist-info');
3861
3862     if (! defined $options{'no-installinfo'})
3863     {
3864         # Make sure documentation is made and installed first.  Use
3865         # $(INFO_DEPS), not 'info', because otherwise recursive makes
3866         # get run twice during "make all".
3867         unshift (@all, '$(INFO_DEPS)');
3868     }
3869
3870     &define_variable ("INFO_DEPS", "@info_deps_list", INTERNAL);
3871     &define_variable ("DVIS", "@dvis_list", INTERNAL);
3872     &define_variable ("PDFS", "@pdfs_list", INTERNAL);
3873     &define_variable ("PSS", "@pss_list", INTERNAL);
3874     # This next isn't strictly needed now -- the places that look here
3875     # could easily be changed to look in info_TEXINFOS.  But this is
3876     # probably better, in case noinst_TEXINFOS is ever supported.
3877     &define_variable ("TEXINFOS", &variable_value ('info_TEXINFOS'), INTERNAL);
3878
3879     # Do some error checking.  Note that this file is not required
3880     # when in Cygnus mode; instead we defined TEXINFO_TEX explicitly
3881     # up above.
3882     if ($need_texi_file && ! defined $options{'no-texinfo.tex'})
3883     {
3884         if ($need_texi_file > 1)
3885         {
3886             require_conf_file_with_macro (TRUE, 'info_TEXINFOS', FOREIGN,
3887                                           'texinfo.tex');
3888         }
3889         else
3890         {
3891             require_file_with_macro (TRUE, 'info_TEXINFOS', FOREIGN,
3892                                      'texinfo.tex');
3893         }
3894     }
3895
3896     return (1, $texiclean);
3897 }
3898
3899 # handle_texinfo ()
3900 # -----------------
3901 # Handle all Texinfo source.
3902 sub handle_texinfo
3903 {
3904     my ($do_something, $texiclean) = handle_texinfo_helper ();
3905     $output_rules .=  &file_contents ('texinfos',
3906                                       new Automake::Location,
3907                                       TEXICLEAN => $texiclean,
3908                                       'LOCAL-TEXIS' => $do_something);
3909 }
3910
3911 # Handle any man pages.
3912 sub handle_man_pages
3913 {
3914     reject_var 'MANS', "`MANS' is an anachronism; use `man_MANS'";
3915
3916     # Find all the sections in use.  We do this by first looking for
3917     # "standard" sections, and then looking for any additional
3918     # sections used in man_MANS.
3919     my (%sections, %vlist);
3920     # We handle nodist_ for uniformity.  man pages aren't distributed
3921     # by default so it isn't actually very important.
3922     foreach my $pfx ('', 'dist_', 'nodist_')
3923     {
3924         # Add more sections as needed.
3925         foreach my $section ('0'..'9', 'n', 'l')
3926         {
3927             if (variable_defined ($pfx . 'man' . $section . '_MANS'))
3928             {
3929                 $sections{$section} = 1;
3930                 $vlist{'$(' . $pfx . 'man' . $section . '_MANS)'} = 1;
3931
3932                 &push_dist_common ('$(' . $pfx . 'man' . $section . '_MANS)')
3933                     if $pfx eq 'dist_';
3934             }
3935         }
3936
3937         if (variable_defined ($pfx . 'man_MANS'))
3938         {
3939             $vlist{'$(' . $pfx . 'man_MANS)'} = 1;
3940             foreach (&variable_value_as_list_recursive ($pfx . 'man_MANS', 'all'))
3941             {
3942                 # A page like `foo.1c' goes into man1dir.
3943                 if (/\.([0-9a-z])([a-z]*)$/)
3944                 {
3945                     $sections{$1} = 1;
3946                 }
3947             }
3948
3949             &push_dist_common ('$(' . $pfx . 'man_MANS)')
3950                 if $pfx eq 'dist_';
3951         }
3952     }
3953
3954     return unless %sections;
3955
3956     # Now for each section, generate an install and unintall rule.
3957     # Sort sections so output is deterministic.
3958     foreach my $section (sort keys %sections)
3959     {
3960         $output_rules .= &file_contents ('mans',
3961                                          new Automake::Location,
3962                                          SECTION => $section);
3963     }
3964
3965     my @mans = sort keys %vlist;
3966     $output_vars .= file_contents ('mans-vars',
3967                                    new Automake::Location,
3968                                    MANS => "@mans");
3969
3970     if (! defined $options{'no-installman'})
3971     {
3972         push (@all, '$(MANS)');
3973     }
3974 }
3975
3976 # Handle DATA variables.
3977 sub handle_data
3978 {
3979     &am_install_var ('-noextra', '-candist', 'data', 'DATA',
3980                      'data', 'sysconf', 'sharedstate', 'localstate',
3981                      'pkgdata', 'noinst', 'check');
3982 }
3983
3984 # Handle TAGS.
3985 sub handle_tags
3986 {
3987     my @tag_deps = ();
3988     my @ctag_deps = ();
3989     if (variable_defined ('SUBDIRS'))
3990     {
3991         $output_rules .= ("tags-recursive:\n"
3992                           . "\tlist=\'\$(SUBDIRS)\'; for subdir in \$\$list; do \\\n"
3993                           # Never fail here if a subdir fails; it
3994                           # isn't important.
3995                           . "\t  test \"\$\$subdir\" = . || (cd \$\$subdir"
3996                           . " && \$(MAKE) \$(AM_MAKEFLAGS) tags); \\\n"
3997                           . "\tdone\n");
3998         push (@tag_deps, 'tags-recursive');
3999         &depend ('.PHONY', 'tags-recursive');
4000
4001         $output_rules .= ("ctags-recursive:\n"
4002                           . "\tlist=\'\$(SUBDIRS)\'; for subdir in \$\$list; do \\\n"
4003                           # Never fail here if a subdir fails; it
4004                           # isn't important.
4005                           . "\t  test \"\$\$subdir\" = . || (cd \$\$subdir"
4006                           . " && \$(MAKE) \$(AM_MAKEFLAGS) ctags); \\\n"
4007                           . "\tdone\n");
4008         push (@ctag_deps, 'ctags-recursive');
4009         &depend ('.PHONY', 'ctags-recursive');
4010     }
4011
4012     if (&saw_sources_p (1)
4013         || variable_defined ('ETAGS_ARGS')
4014         || @tag_deps)
4015     {
4016         my @config;
4017         foreach my $spec (@config_headers)
4018         {
4019             my ($out, @ins) = split_config_file_spec ($spec);
4020             foreach my $in (@ins)
4021               {
4022                 # If the config header source is in this directory,
4023                 # require it.
4024                 push @config, basename ($in)
4025                   if $relative_dir eq dirname ($in);
4026               }
4027         }
4028         $output_rules .= &file_contents ('tags',
4029                                          new Automake::Location,
4030                                          CONFIG    => "@config",
4031                                          TAGSDIRS  => "@tag_deps",
4032                                          CTAGSDIRS => "@ctag_deps");
4033         &examine_variable ('TAGS_DEPENDENCIES');
4034     }
4035     elsif (reject_var ('TAGS_DEPENDENCIES',
4036                        "doesn't make sense to define `TAGS_DEPENDENCIES'"
4037                        . "without\nsources or `ETAGS_ARGS'"))
4038     {
4039     }
4040     else
4041     {
4042         # Every Makefile must define some sort of TAGS rule.
4043         # Otherwise, it would be possible for a top-level "make TAGS"
4044         # to fail because some subdirectory failed.
4045         $output_rules .= "tags: TAGS\nTAGS:\n\n";
4046         # Ditto ctags.
4047         $output_rules .= "ctags: CTAGS\nCTAGS:\n\n";
4048     }
4049 }
4050
4051 # Handle multilib support.
4052 sub handle_multilib
4053 {
4054     if ($seen_multilib && $relative_dir eq '.')
4055     {
4056         $output_rules .= &file_contents ('multilib', new Automake::Location);
4057     }
4058 }
4059
4060
4061 # $BOOLEAN
4062 # &for_dist_common ($A, $B)
4063 # -------------------------
4064 # Subroutine for &handle_dist: sort files to dist.
4065 #
4066 # We put README first because it then becomes easier to make a
4067 # Usenet-compliant shar file (in these, README must be first).
4068 #
4069 # FIXME: do more ordering of files here.
4070 sub for_dist_common
4071 {
4072     return 0
4073         if $a eq $b;
4074     return -1
4075         if $a eq 'README';
4076     return 1
4077         if $b eq 'README';
4078     return $a cmp $b;
4079 }
4080
4081
4082 # handle_dist ($MAKEFILE)
4083 # -----------------------
4084 # Handle 'dist' target.
4085 sub handle_dist
4086 {
4087     my ($makefile) = @_;
4088
4089     # `make dist' isn't used in a Cygnus-style tree.
4090     # Omit the rules so that people don't try to use them.
4091     return if $cygnus_mode;
4092
4093     # Look for common files that should be included in distribution.
4094     # If the aux dir is set, and it does not have a Makefile.am, then
4095     # we check for these files there as well.
4096     my $check_aux = 0;
4097     my $auxdir = '';
4098     if ($relative_dir eq '.'
4099         && $config_aux_dir_set_in_configure_in)
4100     {
4101         ($auxdir = $config_aux_dir) =~ s,^\$\(top_srcdir\)/,,;
4102         if (! &is_make_dir ($auxdir))
4103         {
4104             $check_aux = 1;
4105         }
4106     }
4107     foreach my $cfile (@common_files)
4108     {
4109         if (-f ($relative_dir . "/" . $cfile)
4110             # The file might be absent, but if it can be built it's ok.
4111             || exists $targets{$cfile})
4112         {
4113             &push_dist_common ($cfile);
4114         }
4115
4116         # Don't use `elsif' here because a file might meaningfully
4117         # appear in both directories.
4118         if ($check_aux && -f ($auxdir . '/' . $cfile))
4119         {
4120             &push_dist_common ($auxdir . '/' . $cfile);
4121         }
4122     }
4123
4124     # We might copy elements from $configure_dist_common to
4125     # %dist_common if we think we need to.  If the file appears in our
4126     # directory, we would have discovered it already, so we don't
4127     # check that.  But if the file is in a subdir without a Makefile,
4128     # we want to distribute it here if we are doing `.'.  Ugly!
4129     if ($relative_dir eq '.')
4130     {
4131        foreach my $file (split (' ' , $configure_dist_common))
4132        {
4133            push_dist_common ($file)
4134              unless is_make_dir (dirname ($file));
4135        }
4136     }
4137
4138
4139
4140     # Files to distributed.  Don't use &variable_value_as_list_recursive
4141     # as it recursively expands `$(dist_pkgdata_DATA)' etc.
4142     check_variable_defined_unconditionally ('DIST_COMMON');
4143     my @dist_common = split (' ', variable_value ('DIST_COMMON', TRUE));
4144     @dist_common = uniq (sort for_dist_common (@dist_common));
4145     pretty_print ('DIST_COMMON = ', "\t", @dist_common);
4146
4147     # Now that we've processed DIST_COMMON, disallow further attempts
4148     # to set it.
4149     $handle_dist_run = 1;
4150
4151     # Scan EXTRA_DIST to see if we need to distribute anything from a
4152     # subdir.  If so, add it to the list.  I didn't want to do this
4153     # originally, but there were so many requests that I finally
4154     # relented.
4155     if (variable_defined ('EXTRA_DIST'))
4156     {
4157         # FIXME: This should be fixed to work with conditionals.  That
4158         # will require only making the entries in %dist_dirs under the
4159         # appropriate condition.  This is meaningful if the nature of
4160         # the distribution should depend upon the configure options
4161         # used.
4162         foreach (&variable_value_as_list_recursive ('EXTRA_DIST', 'all'))
4163         {
4164             next if /^\@.*\@$/;
4165             next unless s,/+[^/]+$,,;
4166             $dist_dirs{$_} = 1
4167                 unless $_ eq '.';
4168         }
4169     }
4170
4171     # We have to check DIST_COMMON for extra directories in case the
4172     # user put a source used in AC_OUTPUT into a subdir.
4173     my $topsrcdir = backname ($relative_dir);
4174     foreach (&variable_value_as_list_recursive ('DIST_COMMON', 'all'))
4175     {
4176         next if /^\@.*\@$/;
4177         s/\$\(top_srcdir\)/$topsrcdir/;
4178         s/\$\(srcdir\)/./;
4179         next unless s,/+[^/]+$,,;
4180         $dist_dirs{$_} = 1
4181             unless $_ eq '.';
4182     }
4183
4184     # Rule to check whether a distribution is viable.
4185     my %transform = ('DISTCHECK-HOOK' => &target_defined ('distcheck-hook'),
4186                      'GETTEXT'        => $seen_gettext);
4187
4188     # Prepend $(distdir) to each directory given.
4189     my %rewritten = map { '$(distdir)/' . "$_" => 1 } keys %dist_dirs;
4190     $transform{'DISTDIRS'} = join (' ', sort keys %rewritten);
4191
4192     # If we have SUBDIRS, create all dist subdirectories and do
4193     # recursive build.
4194     if (variable_defined ('SUBDIRS'))
4195     {
4196         # If SUBDIRS is conditionally defined, then set DIST_SUBDIRS
4197         # to all possible directories, and use it.  If DIST_SUBDIRS is
4198         # defined, just use it.
4199         my $dist_subdir_name;
4200         # Note that we check DIST_SUBDIRS first on purpose.  At least
4201         # one project uses so many conditional subdirectories that
4202         # calling variable_conditionally_defined on SUBDIRS will cause
4203         # automake to grow to 150Mb.  Sigh.
4204         if (variable_defined ('DIST_SUBDIRS')
4205             || variable_conditionally_defined ('SUBDIRS'))
4206         {
4207             $dist_subdir_name = 'DIST_SUBDIRS';
4208             if (! variable_defined ('DIST_SUBDIRS'))
4209             {
4210                 define_pretty_variable
4211                   ('DIST_SUBDIRS', TRUE, INTERNAL,
4212                    uniq (&variable_value_as_list_recursive ('SUBDIRS', 'all')));
4213             }
4214         }
4215         else
4216         {
4217             $dist_subdir_name = 'SUBDIRS';
4218             # We always define this because that is what `distclean'
4219             # wants.
4220             define_pretty_variable ('DIST_SUBDIRS', TRUE, INTERNAL,
4221                                     '$(SUBDIRS)');
4222         }
4223
4224         $transform{'DIST_SUBDIR_NAME'} = $dist_subdir_name;
4225     }
4226
4227     # If the target `dist-hook' exists, make sure it is run.  This
4228     # allows users to do random weird things to the distribution
4229     # before it is packaged up.
4230     push (@dist_targets, 'dist-hook')
4231       if &target_defined ('dist-hook');
4232     $transform{'DIST-TARGETS'} = join(' ', @dist_targets);
4233
4234     # Defining $(DISTDIR).
4235     $transform{'DISTDIR'} = !variable_defined('distdir');
4236     $transform{'TOP_DISTDIR'} = backname ($relative_dir);
4237
4238     $output_rules .= &file_contents ('distdir',
4239                                      new Automake::Location,
4240                                      %transform);
4241 }
4242
4243
4244 # Handle subdirectories.
4245 sub handle_subdirs
4246 {
4247     return
4248       unless variable_defined ('SUBDIRS');
4249
4250     my @subdirs = &variable_value_as_list_recursive ('SUBDIRS', 'all');
4251     my @dsubdirs = ();
4252     @dsubdirs = &variable_value_as_list_recursive ('DIST_SUBDIRS', 'all')
4253       if variable_defined ('DIST_SUBDIRS');
4254
4255     # If an `obj/' directory exists, BSD make will enter it before
4256     # reading `Makefile'.  Hence the `Makefile' in the current directory
4257     # will not be read.
4258     #
4259     #  % cat Makefile
4260     #  all:
4261     #          echo Hello
4262     #  % cat obj/Makefile
4263     #  all:
4264     #          echo World
4265     #  % make      # GNU make
4266     #  echo Hello
4267     #  Hello
4268     #  % pmake     # BSD make
4269     #  echo World
4270     #  World
4271     msg_var ('portability', 'SUBDIRS',
4272              "naming a subdirectory `obj' causes troubles with BSD make")
4273       if grep ($_ eq 'obj', @subdirs);
4274     msg_var ('portability', 'DIST_SUBDIRS',
4275              "naming a subdirectory `obj' causes troubles with BSD make")
4276       if grep ($_ eq 'obj', @dsubdirs);
4277
4278     # Make sure each directory mentioned in SUBDIRS actually exists.
4279     foreach my $dir (@subdirs)
4280     {
4281         # Skip directories substituted by configure.
4282         next if $dir =~ /^\@.*\@$/;
4283
4284         if (! -d $am_relative_dir . '/' . $dir)
4285         {
4286             err_var ('SUBDIRS', "required directory $am_relative_dir/$dir "
4287                      . "does not exist");
4288             next;
4289         }
4290
4291         err_var 'SUBDIRS', "directory should not contain `/'"
4292           if $dir =~ /\//;
4293     }
4294
4295     $output_rules .= &file_contents ('subdirs', new Automake::Location);
4296     variable_pretty_output ('RECURSIVE_TARGETS', TRUE);
4297 }
4298
4299
4300 # ($REGEN, @DEPENDENCIES)
4301 # &scan_aclocal_m4
4302 # ----------------
4303 # If aclocal.m4 creation is automated, return the list of its dependencies.
4304 sub scan_aclocal_m4
4305 {
4306     my $regen_aclocal = 0;
4307
4308     return (0, ())
4309       unless $relative_dir eq '.';
4310
4311     &examine_variable ('CONFIG_STATUS_DEPENDENCIES');
4312     &examine_variable ('CONFIGURE_DEPENDENCIES');
4313
4314     if (-f 'aclocal.m4')
4315     {
4316         &define_variable ("ACLOCAL_M4", '$(top_srcdir)/aclocal.m4', INTERNAL);
4317         &push_dist_common ('aclocal.m4');
4318
4319         my $aclocal = new Automake::XFile "< aclocal.m4";
4320         my $line = $aclocal->getline;
4321         $regen_aclocal = $line =~ 'generated automatically by aclocal';
4322     }
4323
4324     my @ac_deps = ();
4325
4326     if (-f 'acinclude.m4')
4327     {
4328         $regen_aclocal = 1;
4329         push @ac_deps, 'acinclude.m4';
4330     }
4331
4332     if (variable_defined ('ACLOCAL_M4_SOURCES'))
4333     {
4334         push (@ac_deps, '$(ACLOCAL_M4_SOURCES)');
4335     }
4336     elsif (variable_defined ('ACLOCAL_AMFLAGS'))
4337     {
4338         # Scan all -I directories for m4 files.  These are our
4339         # dependencies.
4340         my $examine_next = 0;
4341         foreach my $amdir (&variable_value_as_list_recursive ('ACLOCAL_AMFLAGS', TRUE))
4342         {
4343             if ($examine_next)
4344             {
4345                 $examine_next = 0;
4346                 if ($amdir !~ /^\// && -d $amdir)
4347                 {
4348                     foreach my $ac_dep (&my_glob ($amdir . '/*.m4'))
4349                     {
4350                         $ac_dep =~ s/^\.\/+//;
4351                         push (@ac_deps, $ac_dep)
4352                           unless $ac_dep eq "aclocal.m4"
4353                             || $ac_dep eq "acinclude.m4";
4354                     }
4355                 }
4356             }
4357             elsif ($amdir eq '-I')
4358             {
4359                 $examine_next = 1;
4360             }
4361         }
4362     }
4363
4364     # Note that it might be possible that aclocal.m4 doesn't exist but
4365     # should be auto-generated.  This case probably isn't very
4366     # important.
4367
4368     return ($regen_aclocal, @ac_deps);
4369 }
4370
4371
4372 # @DEPENDENCY
4373 # &rewrite_inputs_into_dependencies ($ADD_SRCDIR, @INPUTS)
4374 # --------------------------------------------------------
4375 # Rewrite a list of input files into a form suitable to put on a
4376 # dependency list.  The idea is that if an input file has a directory
4377 # part the same as the current directory, then the directory part is
4378 # simply removed.  But if the directory part is different, then
4379 # $(top_srcdir) is prepended.  Among other things, this is used to
4380 # generate the dependency list for the output files generated by
4381 # AC_OUTPUT.  Consider what the dependencies should look like in this
4382 # case:
4383 #   AC_OUTPUT(src/out:src/in1:lib/in2)
4384 # The first argument, ADD_SRCDIR, is 1 if $(top_srcdir) should be added.
4385 # If 0 then files that require this addition will simply be ignored.
4386 sub rewrite_inputs_into_dependencies ($@)
4387 {
4388     my ($add_srcdir, @inputs) = @_;
4389     my @newinputs;
4390
4391     foreach my $single (@inputs)
4392     {
4393         if (dirname ($single) eq $relative_dir)
4394         {
4395             push (@newinputs, basename ($single));
4396         }
4397         elsif ($add_srcdir)
4398         {
4399             push (@newinputs, '$(top_srcdir)/' . $single);
4400         }
4401     }
4402
4403     return @newinputs;
4404 }
4405
4406 # Handle remaking and configure stuff.
4407 # We need the name of the input file, to do proper remaking rules.
4408 sub handle_configure
4409 {
4410     my ($local, $input, @secondary_inputs) = @_;
4411
4412     my $input_base = basename ($input);
4413     my $local_base = basename ($local);
4414
4415     my $amfile = $input_base . '.am';
4416     # We know we can always add '.in' because it really should be an
4417     # error if the .in was missing originally.
4418     my $infile = '$(srcdir)/' . $input_base . '.in';
4419     my $colon_infile = '';
4420     if ($local ne $input || @secondary_inputs)
4421     {
4422         $colon_infile = ':' . $input . '.in';
4423     }
4424     $colon_infile .= ':' . join (':', @secondary_inputs)
4425         if @secondary_inputs;
4426
4427     my @rewritten = rewrite_inputs_into_dependencies (1, @secondary_inputs);
4428
4429     my ($regen_aclocal_m4, @aclocal_m4_deps) = scan_aclocal_m4 ();
4430
4431     push_dist_common (@configure_deps)
4432       if $relative_dir eq '.';
4433
4434     $output_rules .=
4435       &file_contents ('configure',
4436                       new Automake::Location,
4437                       MAKEFILE              => $local_base,
4438                       'MAKEFILE-DEPS'       => "@rewritten",
4439                       'CONFIG-MAKEFILE'
4440                        => ((($relative_dir eq '.') ? '$@' : '$(subdir)/$@')
4441                            . $colon_infile),
4442                       'MAKEFILE-IN'         => $infile,
4443                       'MAKEFILE-IN-DEPS'    => "@include_stack",
4444                       'MAKEFILE-AM'         => $amfile,
4445                       STRICTNESS => $cygnus_mode ? 'cygnus' : $strictness_name,
4446                       'USE-DEPS'
4447                         => $cmdline_use_dependencies ? '' : ' --ignore-deps',
4448                       'MAKEFILE-AM-SOURCES' =>  "$input$colon_infile",
4449                       'REGEN-ACLOCAL-M4'    => $regen_aclocal_m4,
4450                       ACLOCAL_M4_DEPS       => "@aclocal_m4_deps",
4451                       CONFIGURE_DEPS        => "@configure_deps");
4452
4453     if ($relative_dir eq '.')
4454     {
4455         &push_dist_common ('acconfig.h')
4456             if -f 'acconfig.h';
4457     }
4458
4459     # If we have a configure header, require it.
4460     my $hdr_index = 0;
4461     my @distclean_config;
4462     foreach my $spec (@config_headers)
4463       {
4464         $hdr_index += 1;
4465         # $CONFIG_H_PATH: config.h from top level.
4466         my ($config_h_path, @ins) = split_config_file_spec ($spec);
4467         my $config_h_dir = dirname ($config_h_path);
4468
4469         # If the header is in the current directory we want to build
4470         # the header here.  Otherwise, if we're at the topmost
4471         # directory and the header's directory doesn't have a
4472         # Makefile, then we also want to build the header.
4473         if ($relative_dir eq $config_h_dir
4474             || ($relative_dir eq '.' && ! &is_make_dir ($config_h_dir)))
4475         {
4476             my ($cn_sans_dir, $stamp_dir);
4477             if ($relative_dir eq $config_h_dir)
4478             {
4479                 $cn_sans_dir = basename ($config_h_path);
4480                 $stamp_dir = '';
4481             }
4482             else
4483             {
4484                 $cn_sans_dir = $config_h_path;
4485                 if ($config_h_dir eq '.')
4486                 {
4487                     $stamp_dir = '';
4488                 }
4489                 else
4490                 {
4491                     $stamp_dir = $config_h_dir . '/';
4492                 }
4493             }
4494
4495             # Compute relative path from directory holding output
4496             # header to directory holding input header.  FIXME:
4497             # doesn't handle case where we have multiple inputs.
4498             my $in0_sans_dir;
4499             if (dirname ($ins[0]) eq $relative_dir)
4500             {
4501                 $in0_sans_dir = basename ($ins[0]);
4502             }
4503             else
4504             {
4505                 $in0_sans_dir = backname ($relative_dir) . '/' . $ins[0];
4506             }
4507
4508             require_file ($config_header_location, FOREIGN, $in0_sans_dir);
4509
4510             # Header defined and in this directory.
4511             my @files;
4512             if (-f $config_h_path . '.top')
4513             {
4514                 push (@files, "$cn_sans_dir.top");
4515             }
4516             if (-f $config_h_path . '.bot')
4517             {
4518                 push (@files, "$cn_sans_dir.bot");
4519             }
4520
4521             push_dist_common (@files);
4522
4523             # For now, acconfig.h can only appear in the top srcdir.
4524             if (-f 'acconfig.h')
4525             {
4526                 push (@files, '$(top_srcdir)/acconfig.h');
4527             }
4528
4529             my $stamp = "${stamp_dir}stamp-h${hdr_index}";
4530             $output_rules .=
4531               file_contents ('remake-hdr',
4532                              new Automake::Location,
4533                              FILES         => "@files",
4534                              CONFIG_H      => $cn_sans_dir,
4535                              CONFIG_HIN    => $in0_sans_dir,
4536                              CONFIG_H_PATH => $config_h_path,
4537                              STAMP         => "$stamp");
4538
4539             push @distclean_config, $cn_sans_dir, $stamp;
4540         }
4541     }
4542
4543     $output_rules .= file_contents ('clean-hdr',
4544                                     new Automake::Location,
4545                                     FILES => "@distclean_config")
4546       if @distclean_config;
4547
4548     # Set location of mkinstalldirs.
4549     define_variable ('mkinstalldirs',
4550                      '$(SHELL) ' . $config_aux_dir . '/mkinstalldirs',
4551                      INTERNAL);
4552
4553     reject_var ('CONFIG_HEADER',
4554                 "`CONFIG_HEADER' is an anachronism; now determined "
4555                 . "automatically\nfrom `$configure_ac'");
4556
4557     my @config_h;
4558     foreach my $spec (@config_headers)
4559       {
4560         my ($out, @ins) = split_config_file_spec ($spec);
4561         # Generate CONFIG_HEADER define.
4562         if ($relative_dir eq dirname ($out))
4563         {
4564             push @config_h, basename ($out);
4565         }
4566         else
4567         {
4568             push @config_h, "\$(top_builddir)/$out";
4569         }
4570     }
4571     define_variable ("CONFIG_HEADER", "@config_h", INTERNAL)
4572       if @config_h;
4573
4574     # Now look for other files in this directory which must be remade
4575     # by config.status, and generate rules for them.
4576     my @actual_other_files = ();
4577     foreach my $lfile (@other_input_files)
4578     {
4579         my $file;
4580         my @inputs;
4581         if ($lfile =~ /^([^:]*):(.*)$/)
4582         {
4583             # This is the ":" syntax of AC_OUTPUT.
4584             $file = $1;
4585             @inputs = split (':', $2);
4586         }
4587         else
4588         {
4589             # Normal usage.
4590             $file = $lfile;
4591             @inputs = $file . '.in';
4592         }
4593
4594         # Automake files should not be stored in here, but in %MAKE_LIST.
4595         prog_error "$lfile in \@other_input_files"
4596           if -f $file . '.am';
4597
4598         my $local = basename ($file);
4599
4600         # Make sure the dist directory for each input file is created.
4601         # We only have to do this at the topmost level though.  This
4602         # is a bit ugly but it easier than spreading out the logic,
4603         # especially in cases like AC_OUTPUT(foo/out:bar/in), where
4604         # there is no Makefile in bar/.
4605         if ($relative_dir eq '.')
4606         {
4607             foreach (@inputs)
4608             {
4609                 $dist_dirs{dirname ($_)} = 1;
4610             }
4611         }
4612
4613         # We skip files that aren't in this directory.  However, if
4614         # the file's directory does not have a Makefile, and we are
4615         # currently doing `.', then we create a rule to rebuild the
4616         # file in the subdir.
4617         my $fd = dirname ($file);
4618         if ($fd ne $relative_dir)
4619         {
4620             if ($relative_dir eq '.' && ! &is_make_dir ($fd))
4621             {
4622                 $local = $file;
4623             }
4624             else
4625             {
4626                 next;
4627             }
4628         }
4629
4630         my @rewritten_inputs = rewrite_inputs_into_dependencies (1, @inputs);
4631         $output_rules .= ($local . ': '
4632                           . '$(top_builddir)/config.status '
4633                           . "@rewritten_inputs\n"
4634                           . "\t"
4635                           . 'cd $(top_builddir) && '
4636                           . '$(SHELL) ./config.status '
4637                           . ($relative_dir eq '.' ? '' : '$(subdir)/')
4638                           . '$@'
4639                           . "\n");
4640         push (@actual_other_files, $local);
4641
4642         # Require all input files.
4643         require_file ($ac_config_files_location, FOREIGN,
4644                       rewrite_inputs_into_dependencies (0, @inputs));
4645     }
4646
4647     # These files get removed by "make clean".
4648     define_pretty_variable ('CONFIG_CLEAN_FILES', TRUE, INTERNAL,
4649                             @actual_other_files);
4650 }
4651
4652 # Handle C headers.
4653 sub handle_headers
4654 {
4655     my @r = &am_install_var ('-defaultdist', 'header', 'HEADERS', 'include',
4656                              'oldinclude', 'pkginclude',
4657                              'noinst', 'check');
4658     foreach (@r)
4659     {
4660       next unless $_->[1] =~ /\..*$/;
4661       &saw_extension ($&);
4662     }
4663 }
4664
4665 sub handle_gettext
4666 {
4667   return if ! $seen_gettext || $relative_dir ne '.';
4668
4669   if (! variable_defined ('SUBDIRS'))
4670     {
4671       err_ac "AM_GNU_GETTEXT used but SUBDIRS not defined";
4672       return;
4673     }
4674
4675   my @subdirs = &variable_value_as_list_recursive ('SUBDIRS', 'all');
4676   err_var 'SUBDIRS', "AM_GNU_GETTEXT used but `po' not in SUBDIRS"
4677     if ! grep ($_ eq 'po', @subdirs);
4678   # intl/ is not required when AM_GNU_GETTEXT is called with
4679   # the `external' option.
4680   err_var 'SUBDIRS', "AM_GNU_GETTEXT used but `intl' not in SUBDIRS"
4681     if (! $seen_gettext_external
4682         && ! grep ($_ eq 'intl', @subdirs));
4683
4684   require_file ($ac_gettext_location, GNU, 'ABOUT-NLS');
4685 }
4686
4687 # Handle footer elements.
4688 sub handle_footer
4689 {
4690     # NOTE don't use define_pretty_variable here, because
4691     # $contents{...} is already defined.
4692     $output_vars .= 'SOURCES = ' . variable_value ('SOURCES') . "\n\n"
4693       if variable_value ('SOURCES');
4694
4695     reject_target ('.SUFFIXES',
4696                    "use variable `SUFFIXES', not target `.SUFFIXES'");
4697
4698     # Note: AIX 4.1 /bin/make will fail if any suffix rule appears
4699     # before .SUFFIXES.  So we make sure that .SUFFIXES appears before
4700     # anything else, by sticking it right after the default: target.
4701     $output_header .= ".SUFFIXES:\n";
4702     if (@suffixes || variable_defined ('SUFFIXES'))
4703     {
4704         # Make sure suffixes has unique elements.  Sort them to ensure
4705         # the output remains consistent.  However, $(SUFFIXES) is
4706         # always at the start of the list, unsorted.  This is done
4707         # because make will choose rules depending on the ordering of
4708         # suffixes, and this lets the user have some control.  Push
4709         # actual suffixes, and not $(SUFFIXES).  Some versions of make
4710         # do not like variable substitutions on the .SUFFIXES line.
4711         my @user_suffixes = (variable_defined ('SUFFIXES')
4712                              ? &variable_value_as_list_recursive ('SUFFIXES',
4713                                                                   'all')
4714                              : ());
4715
4716         my %suffixes = map { $_ => 1 } @suffixes;
4717         delete @suffixes{@user_suffixes};
4718
4719         $output_header .= (".SUFFIXES: "
4720                            . join (' ', @user_suffixes, sort keys %suffixes)
4721                            . "\n");
4722     }
4723
4724     $output_trailer .= file_contents ('footer', new Automake::Location);
4725 }
4726
4727 # Deal with installdirs target.
4728 sub handle_installdirs ()
4729 {
4730     $output_rules .=
4731       &file_contents ('install',
4732                       new Automake::Location,
4733                       am__installdirs
4734                         => variable_value ('am__installdirs') || '',
4735                       'installdirs-local'
4736                         => (target_defined ('installdirs-local')
4737                             ? ' installdirs-local' : ''));
4738 }
4739
4740
4741 # Deal with all and all-am.
4742 sub handle_all ($)
4743 {
4744     my ($makefile) = @_;
4745
4746     # Output `all-am'.
4747
4748     # Put this at the beginning for the sake of non-GNU makes.  This
4749     # is still wrong if these makes can run parallel jobs.  But it is
4750     # right enough.
4751     unshift (@all, basename ($makefile));
4752
4753     foreach my $spec (@config_headers)
4754       {
4755         my ($out, @ins) = split_config_file_spec ($spec);
4756         push (@all, basename ($out))
4757           if dirname ($out) eq $relative_dir;
4758       }
4759
4760     # Install `all' hooks.
4761     if (&target_defined ("all-local"))
4762     {
4763       push (@all, "all-local");
4764       &depend ('.PHONY', "all-local");
4765     }
4766
4767     &pretty_print_rule ("all-am:", "\t\t", @all);
4768     &depend ('.PHONY', 'all-am', 'all');
4769
4770
4771     # Output `all'.
4772
4773     my @local_headers = ();
4774     push @local_headers, '$(BUILT_SOURCES)'
4775       if variable_defined ('BUILT_SOURCES');
4776     foreach my $spec (@config_headers)
4777       {
4778         my ($out, @ins) = split_config_file_spec ($spec);
4779         push @local_headers, basename ($out)
4780           if dirname ($out) eq $relative_dir;
4781       }
4782
4783     if (@local_headers)
4784       {
4785         # We need to make sure config.h is built before we recurse.
4786         # We also want to make sure that built sources are built
4787         # before any ordinary `all' targets are run.  We can't do this
4788         # by changing the order of dependencies to the "all" because
4789         # that breaks when using parallel makes.  Instead we handle
4790         # things explicitly.
4791         $output_all .= ("all: @local_headers"
4792                         . "\n\t"
4793                         . '$(MAKE) $(AM_MAKEFLAGS) '
4794                         . (variable_defined ('SUBDIRS')
4795                            ? 'all-recursive' : 'all-am')
4796                         . "\n\n");
4797       }
4798     else
4799       {
4800         $output_all .= "all: " . (variable_defined ('SUBDIRS')
4801                                   ? 'all-recursive' : 'all-am') . "\n\n";
4802       }
4803 }
4804
4805
4806 # Handle check merge target specially.
4807 sub do_check_merge_target
4808 {
4809     if (&target_defined ('check-local'))
4810     {
4811         # User defined local form of target.  So include it.
4812         push (@check_tests, 'check-local');
4813         &depend ('.PHONY', 'check-local');
4814     }
4815
4816     # In --cygnus mode, check doesn't depend on all.
4817     if ($cygnus_mode)
4818     {
4819         # Just run the local check rules.
4820         &pretty_print_rule ('check-am:', "\t\t", @check);
4821     }
4822     else
4823     {
4824         # The check target must depend on the local equivalent of
4825         # `all', to ensure all the primary targets are built.  Then it
4826         # must build the local check rules.
4827         $output_rules .= "check-am: all-am\n";
4828         &pretty_print_rule ("\t\$(MAKE) \$(AM_MAKEFLAGS)", "\t  ",
4829                             @check)
4830             if @check;
4831     }
4832     &pretty_print_rule ("\t\$(MAKE) \$(AM_MAKEFLAGS)", "\t  ",
4833                         @check_tests)
4834         if @check_tests;
4835
4836     &depend ('.PHONY', 'check', 'check-am');
4837     $output_rules .= ("check: "
4838                       . (variable_defined ('SUBDIRS')
4839                          ? 'check-recursive' : 'check-am')
4840                       . "\n");
4841 }
4842
4843 # Handle all 'clean' targets.
4844 sub handle_clean
4845 {
4846   # Clean the files listed in user variables if they exist.
4847   $clean_files{'$(MOSTLYCLEANFILES)'} = MOSTLY_CLEAN
4848     if variable_defined ('MOSTLYCLEANFILES');
4849   $clean_files{'$(CLEANFILES)'} = CLEAN
4850     if variable_defined ('CLEANFILES');
4851   $clean_files{'$(DISTCLEANFILES)'} = DIST_CLEAN
4852     if variable_defined ('DISTCLEANFILES');
4853   $clean_files{'$(MAINTAINERCLEANFILES)'} = MAINTAINER_CLEAN
4854     if variable_defined ('MAINTAINERCLEANFILES');
4855
4856   # Built sources are automatically removed by maintainer-clean.
4857   $clean_files{'$(BUILT_SOURCES)'} = MAINTAINER_CLEAN
4858     if variable_defined ('BUILT_SOURCES');
4859
4860   # Compute a list of "rm"s to run for each target.
4861   my %rms = (MOSTLY_CLEAN, [],
4862              CLEAN, [],
4863              DIST_CLEAN, [],
4864              MAINTAINER_CLEAN, []);
4865
4866   foreach my $file (keys %clean_files)
4867     {
4868       my $when = $clean_files{$file};
4869       prog_error 'invalid entry in %clean_files'
4870         unless exists $rms{$when};
4871
4872       my $rm = "rm -f $file";
4873       # If file is a variable, make sure when don't call `rm -f' without args.
4874       $rm ="test -z \"$file\" || $rm"
4875         if ($file =~ /^\s*\$(\(.*\)|\{.*\})\s*$/);
4876
4877       push @{$rms{$when}}, "\t-$rm\n";
4878     }
4879
4880   $output_rules .= &file_contents
4881     ('clean',
4882      new Automake::Location,
4883      MOSTLYCLEAN_RMS      => join ('', @{$rms{&MOSTLY_CLEAN}}),
4884      CLEAN_RMS            => join ('', @{$rms{&CLEAN}}),
4885      DISTCLEAN_RMS        => join ('', @{$rms{&DIST_CLEAN}}),
4886      MAINTAINER_CLEAN_RMS => join ('', @{$rms{&MAINTAINER_CLEAN}}));
4887 }
4888
4889
4890 # &depend ($CATEGORY, @DEPENDENDEES)
4891 # ----------------------------------
4892 # The target $CATEGORY depends on @DEPENDENDEES.
4893 sub depend
4894 {
4895     my ($category, @dependendees) = @_;
4896     {
4897       push (@{$dependencies{$category}}, @dependendees);
4898     }
4899 }
4900
4901
4902 # &target_cmp ($A, $B)
4903 # --------------------
4904 # Subroutine for &handle_factored_dependencies to let `.PHONY' be last.
4905 sub target_cmp
4906 {
4907     return 0
4908         if $a eq $b;
4909     return -1
4910         if $b eq '.PHONY';
4911     return 1
4912         if $a eq '.PHONY';
4913     return $a cmp $b;
4914 }
4915
4916
4917 # &handle_factored_dependencies ()
4918 # --------------------------------
4919 # Handle everything related to gathered targets.
4920 sub handle_factored_dependencies
4921 {
4922   # Reject bad hooks.
4923   foreach my $utarg ('uninstall-data-local', 'uninstall-data-hook',
4924                      'uninstall-exec-local', 'uninstall-exec-hook')
4925     {
4926       my $x = $utarg;
4927       $x =~ s/(data|exec)-//;
4928       reject_target ($utarg, "use `$x', not `$utarg'");
4929     }
4930
4931   reject_target ('install-local',
4932                  "use `install-data-local' or `install-exec-local', "
4933                  . "not `install-local'");
4934
4935   reject_target ('install-info-local',
4936                  "`install-info-local' target defined but "
4937                  . "`no-installinfo' option not in use")
4938     unless defined $options{'no-installinfo'};
4939
4940   # Install the -local hooks.
4941   foreach (keys %dependencies)
4942     {
4943       # Hooks are installed on the -am targets.
4944       s/-am$// or next;
4945       if (&target_defined ("$_-local"))
4946         {
4947           depend ("$_-am", "$_-local");
4948           &depend ('.PHONY', "$_-local");
4949         }
4950     }
4951
4952   # Install the -hook hooks.
4953   # FIXME: Why not be as liberal as we are with -local hooks?
4954   foreach ('install-exec', 'install-data', 'uninstall')
4955     {
4956       if (&target_defined ("$_-hook"))
4957         {
4958           $actions{"$_-am"} .=
4959             ("\t\@\$(NORMAL_INSTALL)\n"
4960              . "\t" . '$(MAKE) $(AM_MAKEFLAGS) ' . "$_-hook\n");
4961         }
4962     }
4963
4964   # All the required targets are phony.
4965   depend ('.PHONY', keys %required_targets);
4966
4967   # Actually output gathered targets.
4968   foreach (sort target_cmp keys %dependencies)
4969     {
4970       # If there is nothing about this guy, skip it.
4971       next
4972         unless (@{$dependencies{$_}}
4973                 || $actions{$_}
4974                 || $required_targets{$_});
4975       &pretty_print_rule ("$_:", "\t",
4976                           uniq (sort @{$dependencies{$_}}));
4977       $output_rules .= $actions{$_}
4978       if defined $actions{$_};
4979       $output_rules .= "\n";
4980     }
4981 }
4982
4983
4984 # &handle_tests_dejagnu ()
4985 # ------------------------
4986 sub handle_tests_dejagnu
4987 {
4988     push (@check_tests, 'check-DEJAGNU');
4989     $output_rules .= file_contents ('dejagnu', new Automake::Location);
4990 }
4991
4992
4993 # Handle TESTS variable and other checks.
4994 sub handle_tests
4995 {
4996   if (defined $options{'dejagnu'})
4997     {
4998       &handle_tests_dejagnu;
4999     }
5000   else
5001     {
5002       foreach my $c ('DEJATOOL', 'RUNTEST', 'RUNTESTFLAGS')
5003         {
5004           reject_var ($c, "`$c' defined but `dejagnu' not in "
5005                       . "`AUTOMAKE_OPTIONS'");
5006         }
5007     }
5008
5009   if (variable_defined ('TESTS'))
5010     {
5011       push (@check_tests, 'check-TESTS');
5012       $output_rules .= &file_contents ('check', new Automake::Location);
5013     }
5014 }
5015
5016 # Handle Emacs Lisp.
5017 sub handle_emacs_lisp
5018 {
5019   my @elfiles = &am_install_var ('-candist', 'lisp', 'LISP',
5020                                  'lisp', 'noinst');
5021
5022   return if ! @elfiles;
5023
5024   # Generate .elc files.
5025   my @elcfiles = map { $_->[1] . 'c' } @elfiles;
5026   define_pretty_variable ('ELCFILES', TRUE, INTERNAL, @elcfiles);
5027
5028   push (@all, '$(ELCFILES)');
5029
5030   require_variables ($elfiles[0][0], "Emacs Lisp sources seen", TRUE,
5031                      'EMACS', 'lispdir');
5032   require_conf_file ($elfiles[0][0], FOREIGN, 'elisp-comp');
5033   &define_variable ('elisp_comp', $config_aux_dir . '/elisp-comp', INTERNAL);
5034 }
5035
5036 # Handle Python
5037 sub handle_python
5038 {
5039   my @pyfiles = &am_install_var ('-defaultdist', 'python', 'PYTHON',
5040                                  'noinst');
5041   return if ! @pyfiles;
5042
5043   require_variables ($pyfiles[0][0], "Python sources seen", TRUE, 'PYTHON');
5044   require_conf_file ($pyfiles[0][0], FOREIGN, 'py-compile');
5045   &define_variable ('py_compile', $config_aux_dir . '/py-compile', INTERNAL);
5046 }
5047
5048 # Handle Java.
5049 sub handle_java
5050 {
5051     my @sourcelist = &am_install_var ('-candist',
5052                                       'java', 'JAVA',
5053                                       'java', 'noinst', 'check');
5054     return if ! @sourcelist;
5055
5056     my @prefix = am_primary_prefixes ('JAVA', 1,
5057                                       'java', 'noinst', 'check');
5058
5059     my $dir;
5060     foreach my $curs (@prefix)
5061       {
5062         next
5063           if $curs eq 'EXTRA';
5064
5065         err_var "${curs}_JAVA", "multiple _JAVA primaries in use"
5066           if defined $dir;
5067         $dir = $curs;
5068       }
5069
5070
5071     push (@all, 'class' . $dir . '.stamp');
5072 }
5073
5074
5075 # Handle some of the minor options.
5076 sub handle_minor_options
5077 {
5078   if (defined $options{'readme-alpha'})
5079     {
5080       if ($relative_dir eq '.')
5081         {
5082           if ($package_version !~ /^$GNITS_VERSION_PATTERN$/)
5083             {
5084               msg ('error-gnits', $package_version_location,
5085                    "version `$package_version' doesn't follow " .
5086                    "Gnits standards");
5087             }
5088           if (defined $1 && -f 'README-alpha')
5089             {
5090               # This means we have an alpha release.  See
5091               # GNITS_VERSION_PATTERN for details.
5092               require_file_with_macro (TRUE, 'AUTOMAKE_OPTIONS',
5093                                        FOREIGN, 'README-alpha');
5094             }
5095         }
5096     }
5097 }
5098
5099 ################################################################
5100
5101 # ($OUTPUT, @INPUTS)
5102 # &split_config_file_spec ($SPEC)
5103 # -------------------------------
5104 # Decode the Autoconf syntax for config files (files, headers, links
5105 # etc.).
5106 sub split_config_file_spec ($)
5107 {
5108   my ($spec) = @_;
5109   my ($output, @inputs) = split (/:/, $spec);
5110
5111   push @inputs, "$output.in"
5112     unless @inputs;
5113
5114   return ($output, @inputs);
5115 }
5116
5117
5118 my %make_list;
5119
5120 # &scan_autoconf_config_files ($CONFIG-FILES)
5121 # -------------------------------------------
5122 # Study $CONFIG-FILES which is the first argument to AC_CONFIG_FILES
5123 # (or AC_OUTPUT).
5124 sub scan_autoconf_config_files
5125 {
5126     my ($config_files) = @_;
5127     # Look at potential Makefile.am's.
5128     foreach (split ' ', $config_files)
5129     {
5130         # Must skip empty string for Perl 4.
5131         next if $_ eq "\\" || $_ eq '';
5132
5133         # Handle $local:$input syntax.  Note that we ignore
5134         # every input file past the first, though we keep
5135         # those around for later.
5136         my ($local, $input, @rest) = split (/:/);
5137         if (! $input)
5138         {
5139             $input = $local;
5140         }
5141         else
5142         {
5143             # FIXME: should be error if .in is missing.
5144             $input =~ s/\.in$//;
5145         }
5146
5147         if (-f $input . '.am')
5148         {
5149             # We have a file that automake should generate.
5150             $make_list{$input} = join (':', ($local, @rest));
5151         }
5152         else
5153         {
5154             # We have a file that automake should cause to be
5155             # rebuilt, but shouldn't generate itself.
5156             push (@other_input_files, $_);
5157         }
5158     }
5159 }
5160
5161
5162 # &scan_autoconf_traces ($FILENAME)
5163 # ---------------------------------
5164 sub scan_autoconf_traces ($)
5165 {
5166   my ($filename) = @_;
5167
5168   my @traced = qw(AC_CANONICAL_HOST
5169                   AC_CANONICAL_SYSTEM
5170                   AC_CONFIG_AUX_DIR
5171                   AC_CONFIG_FILES
5172                   AC_CONFIG_HEADERS
5173                   AC_INIT
5174                   AC_LIBSOURCE
5175                   AC_SUBST
5176                   AM_AUTOMAKE_VERSION
5177                   AM_CONDITIONAL
5178                   AM_GNU_GETTEXT
5179                   AM_INIT_AUTOMAKE
5180                   AM_MAINTAINER_MODE
5181                   AM_PROG_CC_C_O
5182                   m4_include
5183                   m4_sinclude);
5184
5185   my $traces = ($ENV{AUTOCONF} || 'autoconf') . " ";
5186
5187   # Use a separator unlikely to be used, not `:', the default, which
5188   # has a precise meaning for AC_CONFIG_FILES and so on.
5189   $traces .= join (' ',
5190                    map { "--trace=$_" . ':\$f:\$l::\$n::\${::}%' } @traced);
5191
5192   my $tracefh = new Automake::XFile ("$traces $filename |");
5193   verb "reading $traces";
5194
5195   while ($_ = $tracefh->getline)
5196     {
5197       chomp;
5198       my ($here, @args) = split /::/;
5199       my $where = new Automake::Location $here;
5200       my $macro = $args[0];
5201
5202       # Alphabetical ordering please.
5203       if ($macro eq 'AC_CANONICAL_HOST')
5204         {
5205           if (! $seen_canonical)
5206             {
5207               $seen_canonical = AC_CANONICAL_HOST;
5208               $canonical_location = $where;
5209             }
5210         }
5211       elsif ($macro eq 'AC_CANONICAL_SYSTEM')
5212         {
5213           $seen_canonical = AC_CANONICAL_SYSTEM;
5214           $canonical_location = $where;
5215         }
5216       elsif ($macro eq 'AC_CONFIG_AUX_DIR')
5217         {
5218           @config_aux_path = $args[1];
5219           $config_aux_dir_set_in_configure_in = 1;
5220         }
5221       elsif ($macro eq 'AC_CONFIG_FILES')
5222         {
5223           # Look at potential Makefile.am's.
5224           $ac_config_files_location = $where;
5225           &scan_autoconf_config_files ($args[1]);
5226         }
5227       elsif ($macro eq 'AC_CONFIG_HEADERS')
5228         {
5229           $config_header_location = $where;
5230           push @config_headers, split (' ', $args[1]);
5231         }
5232       elsif ($macro eq 'AC_INIT')
5233         {
5234           if (defined $args[2])
5235             {
5236               $package_version = $args[2];
5237               $package_version_location = $where;
5238             }
5239         }
5240       elsif ($macro eq 'AC_LIBSOURCE')
5241         {
5242           $libsources{$args[1]} = $here;
5243         }
5244       elsif ($macro eq 'AC_SUBST')
5245         {
5246           # Just check for alphanumeric in AC_SUBST.  If you do
5247           # AC_SUBST(5), then too bad.
5248           $configure_vars{$args[1]} = $where
5249             if $args[1] =~ /^\w+$/;
5250         }
5251       elsif ($macro eq 'AM_AUTOMAKE_VERSION')
5252         {
5253           err ($where,
5254                "version mismatch.  This is Automake $VERSION,\n" .
5255                "but the definition used by this AM_INIT_AUTOMAKE\n" .
5256                "comes from Automake $args[1].  You should recreate\n" .
5257                "aclocal.m4 with aclocal and run automake again.\n")
5258             if ($VERSION ne $args[1]);
5259
5260           $seen_automake_version = 1;
5261         }
5262       elsif ($macro eq 'AM_CONDITIONAL')
5263         {
5264           $configure_cond{$args[1]} = $where;
5265         }
5266       elsif ($macro eq 'AM_GNU_GETTEXT')
5267         {
5268           $seen_gettext = $where;
5269           $ac_gettext_location = $where;
5270           $seen_gettext_external = grep ($_ eq 'external', @args);
5271         }
5272       elsif ($macro eq 'AM_INIT_AUTOMAKE')
5273         {
5274           $seen_init_automake = $where;
5275           if (defined $args[2])
5276             {
5277               $package_version = $args[2];
5278               $package_version_location = $where;
5279             }
5280           elsif (defined $args[1])
5281             {
5282               $global_options = $args[1];
5283             }
5284         }
5285       elsif ($macro eq 'AM_MAINTAINER_MODE')
5286         {
5287           $seen_maint_mode = $where;
5288         }
5289       elsif ($macro eq 'AM_PROG_CC_C_O')
5290         {
5291           $seen_cc_c_o = $where;
5292         }
5293       elsif ($macro eq 'm4_include' || $macro eq 'm4_sinclude')
5294         {
5295           # Some modified versions of Autoconf don't use
5296           # forzen files.  Consequently it's possible that we see all
5297           # m4_include's performed during Autoconf's startup.
5298           # Obviously we don't want to distribute Autoconf's files
5299           # so we skip absolute filenames here.
5300           push @configure_deps, $args[1]
5301             unless $here =~ m,^(?:\w:)?[\\/],;
5302         }
5303    }
5304 }
5305
5306
5307 # &scan_autoconf_files ()
5308 # -----------------------
5309 # Check whether we use `configure.ac' or `configure.in'.
5310 # Scan it (and possibly `aclocal.m4') for interesting things.
5311 # We must scan aclocal.m4 because there might be AC_SUBSTs and such there.
5312 sub scan_autoconf_files
5313 {
5314     # Reinitialize libsources here.  This isn't really necessary,
5315     # since we currently assume there is only one configure.ac.  But
5316     # that won't always be the case.
5317     %libsources = ();
5318
5319     $configure_ac = find_configure_ac;
5320     fatal "`configure.ac' or `configure.in' is required\n"
5321         if !$configure_ac;
5322
5323     scan_autoconf_traces ($configure_ac);
5324
5325     # Set input and output files if not specified by user.
5326     if (! @input_files)
5327     {
5328         @input_files = sort keys %make_list;
5329         %output_files = %make_list;
5330     }
5331
5332     @configure_input_files = sort keys %make_list;
5333
5334     err_ac "`AM_INIT_AUTOMAKE' must be used"
5335       if ! $seen_init_automake;
5336
5337     if (! $seen_automake_version)
5338       {
5339         if (-f 'aclocal.m4')
5340           {
5341             err ($seen_init_automake || $me,
5342                  "your implementation of AM_INIT_AUTOMAKE comes from " .
5343                  "an\nold Automake version.  You should recreate " .
5344                  "aclocal.m4\nwith aclocal and run automake again.\n");
5345           }
5346         else
5347           {
5348             err ($seen_init_automake || $me,
5349                  "no proper implementation of AM_INIT_AUTOMAKE was " .
5350                  "found,\nprobably because aclocal.m4 is missing...\n" .
5351                  "You should run aclocal to create this file, then\n" .
5352                  "run automake again.\n");
5353           }
5354       }
5355
5356     # Look for some files we need.  Always check for these.  This
5357     # check must be done for every run, even those where we are only
5358     # looking at a subdir Makefile.  We must set relative_dir so that
5359     # the file-finding machinery works.
5360     # FIXME: Is this broken because it needs dynamic scopes.
5361     # My tests seems to show it's not the case.
5362     $relative_dir = '.';
5363     require_conf_file ($configure_ac, FOREIGN,
5364                        'install-sh', 'mkinstalldirs', 'missing');
5365     err_am "`install.sh' is an anachronism; use `install-sh' instead"
5366       if -f $config_aux_path[0] . '/install.sh';
5367
5368     # Preserve dist_common for later.
5369     $configure_dist_common = variable_value ('DIST_COMMON', TRUE) || '';
5370 }
5371
5372 ################################################################
5373
5374 # Set up for Cygnus mode.
5375 sub check_cygnus
5376 {
5377   return unless $cygnus_mode;
5378
5379   &set_strictness ('foreign');
5380   $options{'no-installinfo'} = 1;
5381   $options{'no-dependencies'} = 1;
5382   $use_dependencies = 0;
5383
5384   err_ac "`AM_MAINTAINER_MODE' required when --cygnus specified"
5385     if !$seen_maint_mode;
5386 }
5387
5388 # Do any extra checking for GNU standards.
5389 sub check_gnu_standards
5390 {
5391   if ($relative_dir eq '.')
5392     {
5393       # In top level (or only) directory.
5394
5395       # Accept one of these three licenses; default to COPYING.
5396       my $license = 'COPYING';
5397       foreach (qw /COPYING.LIB COPYING.LESSER/)
5398         {
5399           $license = $_ if -f $_;
5400         }
5401       require_file ("$am_file.am", GNU, $license,
5402                     qw/INSTALL NEWS README AUTHORS ChangeLog/);
5403     }
5404
5405   for my $opt ('no-installman', 'no-installinfo')
5406     {
5407       msg_var ('error-gnu', 'AUTOMAKE_OPTIONS',
5408                "option `$opt' disallowed by GNU standards")
5409         if (defined $options{$opt});
5410     }
5411 }
5412
5413 # Do any extra checking for GNITS standards.
5414 sub check_gnits_standards
5415 {
5416   if ($relative_dir eq '.')
5417     {
5418       # In top level (or only) directory.
5419       require_file ("$am_file.am", GNITS, 'THANKS');
5420     }
5421 }
5422
5423 ################################################################
5424 #
5425 # Functions to handle files of each language.
5426
5427 # Each `lang_X_rewrite($DIRECTORY, $BASE, $EXT)' function follows a
5428 # simple formula: Return value is LANG_SUBDIR if the resulting object
5429 # file should be in a subdir if the source file is, LANG_PROCESS if
5430 # file is to be dealt with, LANG_IGNORE otherwise.
5431
5432 # Much of the actual processing is handled in
5433 # handle_single_transform_list.  These functions exist so that
5434 # auxiliary information can be recorded for a later cleanup pass.
5435 # Note that the calls to these functions are computed, so don't bother
5436 # searching for their precise names in the source.
5437
5438 # This is just a convenience function that can be used to determine
5439 # when a subdir object should be used.
5440 sub lang_sub_obj
5441 {
5442     return defined $options{'subdir-objects'} ? LANG_SUBDIR : LANG_PROCESS;
5443 }
5444
5445 # Rewrite a single C source file.
5446 sub lang_c_rewrite
5447 {
5448   my ($directory, $base, $ext) = @_;
5449
5450   if (defined $options{'ansi2knr'} && $base =~ /_$/)
5451     {
5452       # FIXME: include line number in error.
5453       err_am "C source file `$base.c' would be deleted by ansi2knr rules";
5454     }
5455
5456   my $r = LANG_PROCESS;
5457   if (defined $options{'subdir-objects'})
5458     {
5459       $r = LANG_SUBDIR;
5460       $base = $directory . '/' . $base
5461         unless $directory eq '.' || $directory eq '';
5462
5463       err_am ("C objects in subdir but `AM_PROG_CC_C_O' "
5464               . "not in `$configure_ac'",
5465               uniq_scope => US_GLOBAL)
5466         unless $seen_cc_c_o;
5467
5468       require_conf_file ("$am_file.am", FOREIGN, 'compile');
5469
5470       # In this case we already have the directory information, so
5471       # don't add it again.
5472       $de_ansi_files{$base} = '';
5473     }
5474   else
5475     {
5476       $de_ansi_files{$base} = (($directory eq '.' || $directory eq '')
5477                                ? ''
5478                                : "$directory/");
5479     }
5480
5481     return $r;
5482 }
5483
5484 # Rewrite a single C++ source file.
5485 sub lang_cxx_rewrite
5486 {
5487     return &lang_sub_obj;
5488 }
5489
5490 # Rewrite a single header file.
5491 sub lang_header_rewrite
5492 {
5493     # Header files are simply ignored.
5494     return LANG_IGNORE;
5495 }
5496
5497 # Rewrite a single yacc file.
5498 sub lang_yacc_rewrite
5499 {
5500     my ($directory, $base, $ext) = @_;
5501
5502     my $r = &lang_sub_obj;
5503     (my $newext = $ext) =~ tr/y/c/;
5504     return ($r, $newext);
5505 }
5506
5507 # Rewrite a single yacc++ file.
5508 sub lang_yaccxx_rewrite
5509 {
5510     my ($directory, $base, $ext) = @_;
5511
5512     my $r = &lang_sub_obj;
5513     (my $newext = $ext) =~ tr/y/c/;
5514     return ($r, $newext);
5515 }
5516
5517 # Rewrite a single lex file.
5518 sub lang_lex_rewrite
5519 {
5520     my ($directory, $base, $ext) = @_;
5521
5522     my $r = &lang_sub_obj;
5523     (my $newext = $ext) =~ tr/l/c/;
5524     return ($r, $newext);
5525 }
5526
5527 # Rewrite a single lex++ file.
5528 sub lang_lexxx_rewrite
5529 {
5530     my ($directory, $base, $ext) = @_;
5531
5532     my $r = &lang_sub_obj;
5533     (my $newext = $ext) =~ tr/l/c/;
5534     return ($r, $newext);
5535 }
5536
5537 # Rewrite a single assembly file.
5538 sub lang_asm_rewrite
5539 {
5540     return &lang_sub_obj;
5541 }
5542
5543 # Rewrite a single Fortran 77 file.
5544 sub lang_f77_rewrite
5545 {
5546     return LANG_PROCESS;
5547 }
5548
5549 # Rewrite a single preprocessed Fortran 77 file.
5550 sub lang_ppf77_rewrite
5551 {
5552     return LANG_PROCESS;
5553 }
5554
5555 # Rewrite a single ratfor file.
5556 sub lang_ratfor_rewrite
5557 {
5558     return LANG_PROCESS;
5559 }
5560
5561 # Rewrite a single Objective C file.
5562 sub lang_objc_rewrite
5563 {
5564     return &lang_sub_obj;
5565 }
5566
5567 # Rewrite a single Java file.
5568 sub lang_java_rewrite
5569 {
5570     return LANG_SUBDIR;
5571 }
5572
5573 # The lang_X_finish functions are called after all source file
5574 # processing is done.  Each should handle defining rules for the
5575 # language, etc.  A finish function is only called if a source file of
5576 # the appropriate type has been seen.
5577
5578 sub lang_c_finish
5579 {
5580     # Push all libobjs files onto de_ansi_files.  We actually only
5581     # push files which exist in the current directory, and which are
5582     # genuine source files.
5583     foreach my $file (keys %libsources)
5584     {
5585         if ($file =~ /^(.*)\.[cly]$/ && -f "$relative_dir/$file")
5586         {
5587             $de_ansi_files{$1} = (($relative_dir eq '.' || $relative_dir eq '')
5588                                   ? ''
5589                                   : "$relative_dir/");
5590         }
5591     }
5592
5593     if (defined $options{'ansi2knr'} && keys %de_ansi_files)
5594     {
5595         # Make all _.c files depend on their corresponding .c files.
5596         my @objects;
5597         foreach my $base (sort keys %de_ansi_files)
5598         {
5599             # Each _.c file must depend on ansi2knr; otherwise it
5600             # might be used in a parallel build before it is built.
5601             # We need to support files in the srcdir and in the build
5602             # dir (because these files might be auto-generated.  But
5603             # we can't use $< -- some makes only define $< during a
5604             # suffix rule.
5605             my $ansfile = $de_ansi_files{$base} . $base . '.c';
5606             $output_rules .= ($base . "_.c: $ansfile \$(ANSI2KNR)\n\t"
5607                               . '$(CPP) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) '
5608                               . '`if test -f $(srcdir)/' . $ansfile
5609                               . '; then echo $(srcdir)/' . $ansfile
5610                               . '; else echo ' . $ansfile . '; fi` '
5611                               . "| sed 's/^# \\([0-9]\\)/#line \\1/' "
5612                               . '| $(ANSI2KNR) > ' . $base . "_.c"
5613                               # If ansi2knr fails then we shouldn't
5614                               # create the _.c file
5615                               . " || rm -f ${base}_.c\n");
5616             push (@objects, $base . '_.$(OBJEXT)');
5617             push (@objects, $base . '_.lo')
5618               if variable_defined ('LIBTOOL');
5619         }
5620
5621         # Make all _.o (and _.lo) files depend on ansi2knr.
5622         # Use a sneaky little hack to make it print nicely.
5623         &pretty_print_rule ('', '', @objects, ':', '$(ANSI2KNR)');
5624     }
5625 }
5626
5627 # This is a yacc helper which is called whenever we have decided to
5628 # compile a yacc file.
5629 sub lang_yacc_target_hook
5630 {
5631     my ($self, $aggregate, $output, $input) = @_;
5632
5633     my $flag = $aggregate . "_YFLAGS";
5634     if ((variable_defined ($flag)
5635          && &variable_value ($flag) =~ /$DASH_D_PATTERN/o)
5636         || (variable_defined ('YFLAGS')
5637             && &variable_value ('YFLAGS') =~ /$DASH_D_PATTERN/o))
5638     {
5639         (my $output_base = $output) =~ s/$KNOWN_EXTENSIONS_PATTERN$//;
5640         my $header = $output_base . '.h';
5641
5642         # Found a `-d' that applies to the compilation of this file.
5643         # Add a dependency for the generated header file, and arrange
5644         # for that file to be included in the distribution.
5645         # FIXME: this fails for `nodist_*_SOURCES'.
5646         $output_rules .= ("${header}: $output\n"
5647                           # Recover from removal of $header
5648                           . "\t\@if test ! -f \$@; then \\\n"
5649                           . "\t  rm -f $output; \\\n"
5650                           . "\t  \$(MAKE) $output; \\\n"
5651                           . "\telse :; fi\n");
5652         &push_dist_common ($header);
5653         # If the files are built in the build directory, then we want
5654         # to remove them with `make clean'.  If they are in srcdir
5655         # they shouldn't be touched.  However, we can't determine this
5656         # statically, and the GNU rules say that yacc/lex output files
5657         # should be removed by maintainer-clean.  So that's what we
5658         # do.
5659         $clean_files{$header} = MAINTAINER_CLEAN;
5660     }
5661     # Erase $OUTPUT on `make maintainer-clean' (by GNU standards).
5662     # See the comment above for $HEADER.
5663     $clean_files{$output} = MAINTAINER_CLEAN;
5664 }
5665
5666 # This is a lex helper which is called whenever we have decided to
5667 # compile a lex file.
5668 sub lang_lex_target_hook
5669 {
5670     my ($self, $aggregate, $output, $input) = @_;
5671     # If the files are built in the build directory, then we want to
5672     # remove them with `make clean'.  If they are in srcdir they
5673     # shouldn't be touched.  However, we can't determine this
5674     # statically, and the GNU rules say that yacc/lex output files
5675     # should be removed by maintainer-clean.  So that's what we do.
5676     $clean_files{$output} = MAINTAINER_CLEAN;
5677 }
5678
5679 # This is a helper for both lex and yacc.
5680 sub yacc_lex_finish_helper
5681 {
5682     return if defined $language_scratch{'lex-yacc-done'};
5683     $language_scratch{'lex-yacc-done'} = 1;
5684
5685     # If there is more than one distinct yacc (resp lex) source file
5686     # in a given directory, then the `ylwrap' program is required to
5687     # allow parallel builds to work correctly.  FIXME: for now, no
5688     # line number.
5689     require_conf_file ($configure_ac, FOREIGN, 'ylwrap');
5690     if ($config_aux_dir_set_in_configure_in)
5691     {
5692         &define_variable ('YLWRAP', $config_aux_dir . "/ylwrap", INTERNAL);
5693     }
5694     else
5695     {
5696         &define_variable ('YLWRAP', '$(top_srcdir)/ylwrap', INTERNAL);
5697     }
5698 }
5699
5700 sub lang_yacc_finish
5701 {
5702   return if defined $language_scratch{'yacc-done'};
5703   $language_scratch{'yacc-done'} = 1;
5704
5705   reject_var 'YACCFLAGS', "`YACCFLAGS' obsolete; use `YFLAGS' instead";
5706
5707   &yacc_lex_finish_helper
5708     if count_files_for_language ('yacc') > 1;
5709 }
5710
5711
5712 sub lang_lex_finish
5713 {
5714   return if defined $language_scratch{'lex-done'};
5715   $language_scratch{'lex-done'} = 1;
5716
5717   &yacc_lex_finish_helper
5718     if count_files_for_language ('lex') > 1;
5719 }
5720
5721
5722 # Given a hash table of linker names, pick the name that has the most
5723 # precedence.  This is lame, but something has to have global
5724 # knowledge in order to eliminate the conflict.  Add more linkers as
5725 # required.
5726 sub resolve_linker
5727 {
5728     my (%linkers) = @_;
5729
5730     foreach my $l (qw(GCJLINK CXXLINK F77LINK OBJCLINK))
5731     {
5732         return $l if defined $linkers{$l};
5733     }
5734     return 'LINK';
5735 }
5736
5737 # Called to indicate that an extension was used.
5738 sub saw_extension
5739 {
5740     my ($ext) = @_;
5741     if (! defined $extension_seen{$ext})
5742     {
5743         $extension_seen{$ext} = 1;
5744     }
5745     else
5746     {
5747         ++$extension_seen{$ext};
5748     }
5749 }
5750
5751 # Return the number of files seen for a given language.  Knows about
5752 # special cases we care about.  FIXME: this is hideous.  We need
5753 # something that involves real language objects.  For instance yacc
5754 # and yaccxx could both derive from a common yacc class which would
5755 # know about the strange ylwrap requirement.  (Or better yet we could
5756 # just not support legacy yacc!)
5757 sub count_files_for_language
5758 {
5759     my ($name) = @_;
5760
5761     my @names;
5762     if ($name eq 'yacc' || $name eq 'yaccxx')
5763     {
5764         @names = ('yacc', 'yaccxx');
5765     }
5766     elsif ($name eq 'lex' || $name eq 'lexxx')
5767     {
5768         @names = ('lex', 'lexxx');
5769     }
5770     else
5771     {
5772         @names = ($name);
5773     }
5774
5775     my $r = 0;
5776     foreach $name (@names)
5777     {
5778         my $lang = $languages{$name};
5779         foreach my $ext (@{$lang->extensions})
5780         {
5781             $r += $extension_seen{$ext}
5782                 if defined $extension_seen{$ext};
5783         }
5784     }
5785
5786     return $r
5787 }
5788
5789 # Called to ask whether source files have been seen . If HEADERS is 1,
5790 # headers can be included.
5791 sub saw_sources_p
5792 {
5793     my ($headers) = @_;
5794
5795     # count all the sources
5796     my $count = 0;
5797     foreach my $val (values %extension_seen)
5798     {
5799         $count += $val;
5800     }
5801
5802     if (!$headers)
5803     {
5804         $count -= count_files_for_language ('header');
5805     }
5806
5807     return $count > 0;
5808 }
5809
5810
5811 # register_language (%ATTRIBUTE)
5812 # ------------------------------
5813 # Register a single language.
5814 # Each %ATTRIBUTE is of the form ATTRIBUTE => VALUE.
5815 sub register_language (%)
5816 {
5817   my (%option) = @_;
5818
5819   # Set the defaults.
5820   $option{'ansi'} = 0
5821     unless defined $option{'ansi'};
5822   $option{'autodep'} = 'no'
5823     unless defined $option{'autodep'};
5824   $option{'linker'} = ''
5825     unless defined $option{'linker'};
5826   $option{'flags'} = []
5827     unless defined $option{'flags'};
5828   $option{'output_extensions'} = sub { return ( '.$(OBJEXT)', '.lo' ) }
5829     unless defined $option{'output_extensions'};
5830
5831   my $lang = new Language (%option);
5832
5833   # Fill indexes.
5834   grep ($extension_map{$_} = $lang->name, @{$lang->extensions});
5835   $languages{$lang->name} = $lang;
5836
5837   # Update the pattern of known extensions.
5838   accept_extensions (@{$lang->extensions});
5839
5840   # Upate the $suffix_rule map.
5841   foreach my $suffix (@{$lang->extensions})
5842     {
5843       foreach my $dest (&{$lang->output_extensions} ($suffix))
5844         {
5845           &register_suffix_rule ('internal', $suffix, $dest);
5846         }
5847     }
5848 }
5849
5850 # derive_suffix ($EXT, $OBJ)
5851 # --------------------------
5852 # This function is used to find a path from a user-specified suffix $EXT
5853 # to $OBJ or to some other suffix we recognize internally, eg `cc'.
5854 sub derive_suffix ($$)
5855 {
5856   my ($source_ext, $obj) = @_;
5857
5858   while (! $extension_map{$source_ext}
5859          && $source_ext ne $obj
5860          && exists $suffix_rules->{$source_ext}
5861          && exists $suffix_rules->{$source_ext}{$obj})
5862     {
5863       $source_ext = $suffix_rules->{$source_ext}{$obj}[0];
5864     }
5865
5866   return $source_ext;
5867 }
5868
5869
5870 ################################################################
5871
5872 # Pretty-print something.  HEAD is what should be printed at the
5873 # beginning of the first line, FILL is what should be printed at the
5874 # beginning of every subsequent line.
5875 sub pretty_print_internal
5876 {
5877     my ($head, $fill, @values) = @_;
5878
5879     my $column = length ($head);
5880     my $result = $head;
5881
5882     # Fill length is number of characters.  However, each Tab
5883     # character counts for eight.  So we count the number of Tabs and
5884     # multiply by 7.
5885     my $fill_length = length ($fill);
5886     $fill_length += 7 * ($fill =~ tr/\t/\t/d);
5887
5888     foreach (@values)
5889     {
5890         # "71" because we also print a space.
5891         if ($column + length ($_) > 71)
5892         {
5893             $result .= " \\\n" . $fill;
5894             $column = $fill_length;
5895         }
5896         $result .= ' ' if $result =~ /\S\z/;
5897         $result .= $_;
5898         $column += length ($_) + 1;
5899     }
5900
5901     $result .= "\n";
5902     return $result;
5903 }
5904
5905 # Pretty-print something and append to output_vars.
5906 sub pretty_print
5907 {
5908     $output_vars .= &pretty_print_internal (@_);
5909 }
5910
5911 # Pretty-print something and append to output_rules.
5912 sub pretty_print_rule
5913 {
5914     $output_rules .= &pretty_print_internal (@_);
5915 }
5916
5917
5918 ################################################################
5919
5920
5921 # $NEGATION
5922 # condition_negate ($COND)
5923 # ------------------------
5924 sub condition_negate ($)
5925 {
5926     my ($cond) = @_;
5927
5928     $cond =~ s/TRUE$/TRUEO/;
5929     $cond =~ s/FALSE$/TRUE/;
5930     $cond =~ s/TRUEO$/FALSE/;
5931
5932     return $cond;
5933 }
5934
5935
5936 # Compare condition names.
5937 # Issue them in alphabetical order, foo_TRUE before foo_FALSE.
5938 sub by_condition
5939 {
5940     # Be careful we might be comparing `' or `#'.
5941     $a->string =~ /^(.*)_(TRUE|FALSE)$/;
5942     my ($aname, $abool) = ($1 || '', $2 || '');
5943     $b->string =~ /^(.*)_(TRUE|FALSE)$/;
5944     my ($bname, $bbool) = ($1 || '', $2 || '');
5945     return ($aname cmp $bname
5946             # Don't bother with IFs, given that TRUE is after FALSE
5947             # just cmp in the reverse order.
5948             || $bbool cmp $abool
5949             # Just in case...
5950             || $a cmp $b);
5951 }
5952
5953
5954 ## ------------------------------ ##
5955 ## Handling the condition stack.  ##
5956 ## ------------------------------ ##
5957
5958
5959 # $COND
5960 # cond_stack_if ($NEGATE, $COND, $WHERE)
5961 # --------------------------------------
5962 sub cond_stack_if ($$$)
5963 {
5964   my ($negate, $cond, $where) = @_;
5965
5966   err $where, "$cond does not appear in AM_CONDITIONAL"
5967     if ! $configure_cond{$cond} && $cond !~ /^TRUE|FALSE$/;
5968
5969   $cond = "${cond}_TRUE"
5970     unless $cond =~ /^TRUE|FALSE$/;
5971   $cond = condition_negate ($cond)
5972     if $negate;
5973
5974   push (@cond_stack, $cond);
5975
5976   return new Automake::Conditional (@cond_stack);
5977 }
5978
5979
5980 # $COND
5981 # cond_stack_else ($NEGATE, $COND, $WHERE)
5982 # ----------------------------------------
5983 sub cond_stack_else ($$$)
5984 {
5985   my ($negate, $cond, $where) = @_;
5986
5987   if (! @cond_stack)
5988     {
5989       err $where, "else without if";
5990       return;
5991     }
5992
5993   $cond_stack[$#cond_stack] = condition_negate ($cond_stack[$#cond_stack]);
5994
5995   # If $COND is given, check against it.
5996   if (defined $cond)
5997     {
5998       $cond = "${cond}_TRUE"
5999         unless $cond =~ /^TRUE|FALSE$/;
6000       $cond = condition_negate ($cond)
6001         if $negate;
6002
6003       err ($where, "else reminder ($negate$cond) incompatible with "
6004            . "current conditional: $cond_stack[$#cond_stack]")
6005         if $cond_stack[$#cond_stack] ne $cond;
6006     }
6007
6008   return new Automake::Conditional (@cond_stack);
6009 }
6010
6011
6012 # $COND
6013 # cond_stack_endif ($NEGATE, $COND, $WHERE)
6014 # -----------------------------------------
6015 sub cond_stack_endif ($$$)
6016 {
6017   my ($negate, $cond, $where) = @_;
6018   my $old_cond;
6019
6020   if (! @cond_stack)
6021     {
6022       err $where, "endif without if: $negate$cond";
6023       return;
6024     }
6025
6026
6027   # If $COND is given, check against it.
6028   if (defined $cond)
6029     {
6030       $cond = "${cond}_TRUE"
6031         unless $cond =~ /^TRUE|FALSE$/;
6032       $cond = condition_negate ($cond)
6033         if $negate;
6034
6035       err ($where, "endif reminder ($negate$cond) incompatible with "
6036            . "current conditional: $cond_stack[$#cond_stack]")
6037         if $cond_stack[$#cond_stack] ne $cond;
6038     }
6039
6040   pop @cond_stack;
6041
6042   return new Automake::Conditional (@cond_stack);
6043 }
6044
6045
6046
6047
6048
6049 ## ------------------------ ##
6050 ## Handling the variables.  ##
6051 ## ------------------------ ##
6052
6053
6054 # check_ambiguous_conditional ($VAR, $COND, $WHERE)
6055 # -------------------------------------------------
6056 # Check for an ambiguous conditional.  This is called when a variable
6057 # is being defined conditionally.  If we already know about a
6058 # definition that is true under the same conditions, then we have an
6059 # ambiguity.
6060 sub check_ambiguous_conditional ($$$)
6061 {
6062   my ($var, $cond, $where) = @_;
6063   my ($message, $ambig_cond) =
6064     conditional_ambiguous_p ($var, $cond, keys %{$var_value{$var}});
6065   if ($message)
6066     {
6067       msg 'syntax', $where, "$message ...", partial => 1;
6068       msg_var ('syntax', $var, "... `$var' previously defined here");
6069       verb (macro_dump ($var));
6070     }
6071 }
6072
6073 # $STRING, $AMBIG_COND
6074 # conditional_ambiguous_p ($WHAT, $COND, @CONDS)
6075 # ----------------------------------------------
6076 # Check for an ambiguous conditional.  Return an error message and
6077 # the other condition involved if we have one, two empty strings otherwise.
6078 #   WHAT:  the thing being defined
6079 #   COND:  the condition under which is is being defined
6080 #   CONDS: the conditons under which is had already been defined
6081 sub conditional_ambiguous_p ($$@)
6082 {
6083   my ($var, $cond, @conds) = @_;
6084   foreach my $vcond (@conds)
6085     {
6086       # Note that these rules doesn't consider the following
6087       # example as ambiguous.
6088       #
6089       #   if COND1
6090       #     FOO = foo
6091       #   endif
6092       #   if COND2
6093       #     FOO = bar
6094       #   endif
6095       #
6096       # It's up to the user to not define COND1 and COND2
6097       # simultaneously.
6098       my $message;
6099       if ($vcond eq $cond)
6100         {
6101           return ("$var multiply defined in condition $cond", $vcond);
6102         }
6103       elsif ($vcond->true_when ($cond))
6104         {
6105           return ("$var was already defined in condition $vcond, "
6106                   . "which implies condition $cond", $vcond);
6107         }
6108       elsif ($cond->true_when ($vcond))
6109         {
6110           return ("$var was already defined in condition $vcond, "
6111                    . "which is implied by condition $cond", $vcond);
6112         }
6113     }
6114   return ('', '');
6115 }
6116
6117 # @MISSING_CONDS
6118 # variable_not_always_defined_in_cond ($VAR, $COND)
6119 # ---------------------------------------------
6120 # Check whether $VAR is always defined for condition $COND.
6121 # Return a list of conditions where the definition is missing.
6122 #
6123 # For instance, given
6124 #
6125 #   if COND1
6126 #     if COND2
6127 #       A = foo
6128 #       D = d1
6129 #     else
6130 #       A = bar
6131 #       D = d2
6132 #     endif
6133 #   else
6134 #     D = d3
6135 #   endif
6136 #   if COND3
6137 #     A = baz
6138 #     B = mumble
6139 #   endif
6140 #   C = mumble
6141 #
6142 # we should have (we display result as conditional strings in this
6143 # illustration, but we really return Conditional objects):
6144 #   variable_not_always_defined_in_cond ('A', 'COND1_TRUE COND2_TRUE')
6145 #     => ()
6146 #   variable_not_always_defined_in_cond ('A', 'COND1_TRUE')
6147 #     => ()
6148 #   variable_not_always_defined_in_cond ('A', 'TRUE')
6149 #     => ("COND1_FALSE COND2_FALSE COND3_FALSE",
6150 #         "COND1_FALSE COND2_TRUE COND3_FALSE",
6151 #         "COND1_TRUE COND2_FALSE COND3_FALSE",
6152 #         "COND1_TRUE COND2_TRUE COND3_FALSE")
6153 #   variable_not_always_defined_in_cond ('B', 'COND1_TRUE')
6154 #     => ("COND3_FALSE")
6155 #   variable_not_always_defined_in_cond ('C', 'COND1_TRUE')
6156 #     => ()
6157 #   variable_not_always_defined_in_cond ('D', 'TRUE')
6158 #     => ()
6159 #   variable_not_always_defined_in_cond ('Z', 'TRUE')
6160 #     => ("TRUE")
6161 sub variable_not_always_defined_in_cond ($$)
6162 {
6163   my ($var, $cond) = @_;
6164
6165   # It's easy to answer if the variable is not defined.
6166   return (TRUE,) unless exists $var_value{$var};
6167
6168   # How does it work?  Let's take the second example:
6169   #
6170   #   variable_not_always_defined_in_cond ('A', 'COND1_TRUE')
6171   #
6172   # (1) First, we get the list of conditions where A is defined:
6173   #
6174   #   ("COND1_TRUE COND2_TRUE", "COND1_TRUE COND2_FALSE", "COND3_TRUE")
6175   #
6176   # (2) Then we generate the set of inverted conditions:
6177   #
6178   #   ("COND1_FALSE COND2_TRUE COND3_FALSE",
6179   #    "COND1_FALSE COND2_FALSE COND3_FALSE")
6180   #
6181   # (3) Finally we remove these conditions which are not implied by
6182   #     COND1_TRUE.  This yields an empty list and we are done.
6183
6184   my @res = ();
6185   my @cond_defs = keys %{$var_value{$var}}; # (1)
6186   foreach my $icond (invert_conditions (@cond_defs)) # (2)
6187     {
6188       prog_error "invert_conditions returned an input condition"
6189         if exists $var_value{$var}{$icond};
6190
6191       push @res, $icond
6192         if ($cond->true_when ($icond)); # (3)
6193     }
6194   return @res;
6195 }
6196
6197 # &macro_define($VAR, $OWNER, $TYPE, $COND, $VALUE, $WHERE)
6198 # -------------------------------------------------------------
6199 # The $VAR can go from Automake to user, but not the converse.
6200 sub macro_define ($$$$$$)
6201 {
6202   my ($var, $owner, $type, $cond, $value, $where) = @_;
6203
6204   prog_error "$cond is not a reference"
6205     unless ref $where;
6206
6207   prog_error "$where is not a reference"
6208     unless ref $where;
6209
6210   # We will adjust the owener of this variable unless told otherwise.
6211   my $adjust_owner = 1;
6212
6213   err $where, "bad characters in variable name `$var'"
6214     if $var !~ /$MACRO_PATTERN/o;
6215
6216   # NEWS-OS 4.2R complains if a Makefile variable begins with `_'.
6217   msg ('portability', $where,
6218        "$var: variable names starting with `_' are not portable")
6219     if $var =~ /^_/;
6220
6221   # `:='-style assignments are not acknowledged by POSIX.  Moreover it
6222   # has multiple meanings.  In GNU make or BSD make it means "assign
6223   # with immediate expansion", while in OSF make it is used for
6224   # conditional assignments.
6225   msg ('portability', $where, "`:='-style assignments are not portable")
6226     if $type eq ':';
6227
6228   check_variable_expansions ($value, $where);
6229
6230   # An Automake variable must be consistently defined with the same
6231   # sign by Automake.  A user variable must be set by either `=' or
6232   # `:=', and later promoted to `+='.
6233   if ($owner == VAR_AUTOMAKE)
6234     {
6235       if (exists $var_type{$var}
6236           && exists $var_type{$var}{$cond}
6237           && $var_type{$var}{$cond} ne $type)
6238         {
6239           err ($where, "$var was set with `$var_type{$var}=' "
6240                . "and is now set with `$type='");
6241         }
6242     }
6243   else
6244     {
6245       if (!exists $var_type{$var} && $type eq '+')
6246         {
6247           err $where, "$var must be set with `=' before using `+='";
6248         }
6249     }
6250   $var_type{$var}{$cond} = $type;
6251
6252   # When adding, since we rewrite, don't try to preserve the
6253   # Automake continuation backslashes.
6254   $value =~ s/\\$//mg
6255     if $type eq '+' && $owner == VAR_AUTOMAKE;
6256
6257   # Differentiate assignment types.
6258
6259   # 1. append (+=) to a variable defined for current condition
6260   if ($type eq '+' && exists $var_value{$var}{$cond})
6261     {
6262       if (chomp $var_value{$var}{$cond})
6263         {
6264           # Insert a backslash before a trailing newline.
6265           $var_value{$var}{$cond} .= "\\\n";
6266         }
6267       elsif ($var_value{$var}{$cond})
6268         {
6269           # Insert a separator.
6270           $var_value{$var}{$cond} .= ' ';
6271         }
6272        $var_value{$var}{$cond} .= $value;
6273     }
6274   # 2. append (+=) to a variable defined for *another* condition
6275   elsif ($type eq '+' && keys %{$var_value{$var}})
6276     {
6277       # * Generally, $cond is not TRUE.  For instance:
6278       #     FOO = foo
6279       #     if COND
6280       #       FOO += bar
6281       #     endif
6282       #   In this case, we declare an helper variable conditionally,
6283       #   and append it to FOO:
6284       #     FOO = foo $(am__append_1)
6285       #     @COND_TRUE@am__append_1 = bar
6286       #   Of course if FOO is defined under several conditions, we add
6287       #   $(am__append_1) to each definitions.
6288       #
6289       # * If $cond is TRUE, we don't need the helper variable.  E.g., in
6290       #     if COND1
6291       #       FOO = foo1
6292       #     else
6293       #       FOO = foo2
6294       #     endif
6295       #     FOO += bar
6296       #   we can add bar directly to all definition of FOO, and output
6297       #     @COND_TRUE@FOO = foo1 bar
6298       #     @COND_FALSE@FOO = foo2 bar
6299
6300       # Do we need an helper variable?
6301       if ($cond != TRUE)
6302         {
6303             # Does the helper variable already exists?
6304             my $key = "$var:" . $cond->string;
6305             if (exists $appendvar{$key})
6306               {
6307                 # Yes, let's simply append to it.
6308                 $var = $appendvar{$key};
6309                 $owner = VAR_AUTOMAKE;
6310               }
6311             else
6312               {
6313                 # No, create it.
6314                 my $num = 1 + keys (%appendvar);
6315                 my $hvar = "am__append_$num";
6316                 $appendvar{$key} = $hvar;
6317                 &macro_define ($hvar, VAR_AUTOMAKE, '+',
6318                                $cond, $value, $where);
6319                 push @var_list, $hvar;
6320                 # Now HVAR is to be added to VAR.
6321                 $value = "\$($hvar)";
6322               }
6323         }
6324
6325       # Add VALUE to all definitions of VAR.
6326       foreach my $vcond (keys %{$var_value{$var}})
6327         {
6328           # We have a bit of error detection to do here.
6329           # This:
6330           #   if COND1
6331           #     X = Y
6332           #   endif
6333           #   X += Z
6334           # should be rejected because X is not defined for all conditions
6335           # where `+=' applies.
6336           my @undef_cond = variable_not_always_defined_in_cond $var, $cond;
6337           if (@undef_cond != 0)
6338             {
6339               err ($where,
6340                    "Cannot apply `+=' because `$var' is not defined "
6341                    . "in\nthe following conditions:\n  "
6342                    . join ("\n  ", map { $_->string } @undef_cond)
6343                    . "\nEither define `$var' in these conditions,"
6344                    . " or use\n`+=' in the same conditions as"
6345                    . " the definitions.");
6346             }
6347           else
6348             {
6349               &macro_define ($var, $owner, '+', $vcond, $value, $where);
6350             }
6351         }
6352       # Don't adjust the owner.  The above &macro_define did it in the
6353       # right conditions.
6354       $adjust_owner = 0;
6355     }
6356   # 3. first assignment (=, :=, or +=)
6357   else
6358     {
6359       # If Automake tries to override a value specified by the user,
6360       # just don't let it do.
6361       if (exists $var_value{$var}{$cond}
6362           && $var_owner{$var} != VAR_AUTOMAKE
6363           && $owner == VAR_AUTOMAKE)
6364         {
6365           verb ("refusing to override the user definition of:\n"
6366                 . macro_dump ($var)
6367                 ."with `$cond->string' => `$value'");
6368         }
6369       else
6370         {
6371           # There must be no previous value unless the user is redefining
6372           # an Automake variable or an AC_SUBST variable for an existing
6373           # condition.
6374           check_ambiguous_conditional ($var, $cond, $where)
6375             unless (exists $var_owner{$var}{$cond}
6376                     && (($var_owner{$var}{$cond} == VAR_AUTOMAKE
6377                          && $owner != VAR_AUTOMAKE)
6378                         || $var_owner{$var}{$cond} == VAR_CONFIGURE));
6379
6380           $var_value{$var}{$cond} = $value;
6381           # Assignments to a macro set its location.  We don't adjust
6382           # locations for `+='.  Ideally I suppose we would associate
6383           # line numbers with random bits of text.
6384           $var_location{$var}{$cond} = $where->clone;
6385         }
6386     }
6387
6388   # The owner of a variable can only increase, because an Automake
6389   # variable can be given to the user, but not the converse.
6390   if ($adjust_owner &&
6391       (! exists $var_owner{$var}{$cond}
6392        || $owner > $var_owner{$var}{$cond}))
6393     {
6394       $var_owner{$var}{$cond} = $owner;
6395       # Always adjust the location when the owner changes (even for
6396       # `+=' statements).  The risk otherwise is to warn about
6397       # a VAR_MAKEFILE variable and locate it in configure.ac...
6398       $var_location{$var}{$cond} = $where->clone;
6399     }
6400
6401   # Call var_VAR_trigger if it's defined.
6402   # This hook helps to update some internal state *while*
6403   # parsing the file.  For instance the handling of SUFFIXES
6404   # requires this (see var_SUFFIXES_trigger).
6405   my $var_trigger = "var_${var}_trigger";
6406   &$var_trigger($type, $value) if defined &$var_trigger;
6407 }
6408
6409
6410 # &macro_delete ($VAR, [@CONDS])
6411 # ------------------------------
6412 # Forget about $VAR under the conditions @CONDS, or completely if
6413 # @CONDS is empty.
6414 sub macro_delete ($@)
6415 {
6416   my ($var, @conds) = @_;
6417
6418   if (!@conds)
6419     {
6420       delete $var_value{$var};
6421       delete $var_location{$var};
6422       delete $var_owner{$var};
6423       delete $var_comment{$var};
6424       delete $var_type{$var};
6425     }
6426   else
6427     {
6428       foreach my $cond (@conds)
6429         {
6430           delete $var_value{$var}{$cond};
6431           delete $var_location{$var}{$cond};
6432           delete $var_owner{$var}{$cond};
6433           delete $var_comment{$var}{$cond};
6434           delete $var_type{$var}{$cond};
6435         }
6436     }
6437 }
6438
6439
6440 # &macro_dump ($VAR)
6441 # ------------------
6442 sub macro_dump ($)
6443 {
6444   my ($var) = @_;
6445   my $text = '';
6446
6447   if (!exists $var_value{$var})
6448     {
6449       $text = "  $var does not exist\n";
6450     }
6451   else
6452     {
6453       $text .= "  $var $var_type{$var}=\n  {\n";
6454       foreach my $vcond (sort by_condition keys %{$var_value{$var}})
6455         {
6456           prog_error ("`$var' is a key in \$var_value, "
6457                       . "but not in \$var_owner\n")
6458             unless exists $var_owner{$var}{$vcond};
6459
6460           my $var_owner;
6461           if ($var_owner{$var}{$vcond} == VAR_AUTOMAKE)
6462             {
6463               $var_owner = 'Automake';
6464             }
6465           elsif ($var_owner{$var}{$vcond} == VAR_CONFIGURE)
6466             {
6467               $var_owner = 'Configure';
6468             }
6469           elsif ($var_owner{$var}{$vcond} == VAR_MAKEFILE)
6470             {
6471               $var_owner = 'Makefile';
6472             }
6473           else
6474             {
6475               prog_error ("unexpected value for `\$var_owner{$var}{$vcond}': "
6476                           . $var_owner{$var}{$vcond})
6477                 unless defined $var_owner;
6478             }
6479
6480           my $where = (defined $var_location{$var}{$vcond}
6481                        ? $var_location{$var}{$vcond} : "undefined");
6482           $text .= "$var_comment{$var}{$vcond}"
6483             if exists $var_comment{$var}{$vcond};
6484           $text .= "    $vcond => $var_value{$var}{$vcond}\n";
6485         }
6486       $text .= "  }\n";
6487     }
6488   return $text;
6489 }
6490
6491
6492 # &macros_dump ()
6493 # ---------------
6494 sub macros_dump ()
6495 {
6496   my ($var) = @_;
6497
6498   my $text = "%var_value =\n{\n";
6499   foreach my $var (sort (keys %var_value))
6500     {
6501       $text .= macro_dump ($var);
6502     }
6503   $text .= "}\n";
6504   return $text;
6505 }
6506
6507
6508 # $BOOLEAN
6509 # variable_defined ($VAR, [$COND])
6510 # ---------------------------------
6511 # See if a variable exists.  $VAR is the variable name, and $COND is
6512 # the condition which we should check.  If no condition is given, we
6513 # currently return true if the variable is defined under any
6514 # condition.
6515 sub variable_defined ($;$)
6516 {
6517     my ($var, $cond) = @_;
6518
6519     if (! exists $var_value{$var}
6520         || (defined $cond && ! exists $var_value{$var}{$cond}))
6521       {
6522         # VAR is not defined.
6523
6524         # Check there is no target defined with the name of the
6525         # variable we check.
6526
6527         # adl> I'm wondering if this error still makes any sense today. I
6528         # adl> guess it was because targets and variables used to share
6529         # adl> the same namespace in older versions of Automake?
6530         # tom> While what you say is definitely part of it, I think it
6531         # tom> might also have been due to someone making a "spelling error"
6532         # tom> -- writing "foo:..." instead of "foo = ...".
6533         # tom> I'm not sure whether it is really worth diagnosing
6534         # tom> this sort of problem.  In the old days I used to add warnings
6535         # tom> and errors like this pretty randomly, based on bug reports I
6536         # tom> got.  But there's a plausible argument that I was trying
6537         # tom> too hard to prevent people from making mistakes.
6538         if (exists $targets{$var}
6539             && (! defined $cond || exists $targets{$var}{$cond}))
6540           {
6541             for my $tcond ($cond || keys %{$targets{$var}})
6542               {
6543                 prog_error ("\$targets{$var}{$tcond} exists but "
6544                             . "\$target_owner doesn't")
6545                   unless exists $target_owner{$var}{$tcond};
6546                 # Diagnose the first user target encountered, if any.
6547                 # Restricting this test to user targets allows Automake
6548                 # to create rules for things like `bin_PROGRAMS = LDADD'.
6549                 if ($target_owner{$var}{$tcond} == TARGET_USER)
6550                   {
6551                     msg_cond_target ('syntax', $tcond, $var,
6552                                      "`$var' is a target; "
6553                                      . "expected a variable");
6554                     return 0;
6555                   }
6556               }
6557           }
6558         return 0;
6559       }
6560
6561     # Even a var_value examination is good enough for us.  FIXME:
6562     # really should maintain examined status on a per-condition basis.
6563     $content_seen{$var} = 1;
6564     return 1;
6565 }
6566
6567
6568 # $BOOLEAN
6569 # variable_assert ($VAR, $WHERE)
6570 # ------------------------------
6571 # Make sure a variable exists.  $VAR is the variable name, and $WHERE
6572 # is the name of a macro which refers to $VAR.
6573 sub variable_assert ($$)
6574 {
6575   my ($var, $where) = @_;
6576
6577   return 1
6578     if variable_defined $var;
6579
6580   require_variables ($where, "variable `$var' is used", TRUE, $var);
6581
6582   return 0;
6583 }
6584
6585 # Mark a variable as examined.
6586 sub examine_variable
6587 {
6588   my ($var) = @_;
6589   variable_defined ($var);
6590 }
6591
6592
6593 # &variable_conditions_recursive ($VAR)
6594 # -------------------------------------
6595 # Return the set of conditions for which a variable is defined.
6596
6597 # If the variable is not defined conditionally, and is not defined in
6598 # terms of any variables which are defined conditionally, then this
6599 # returns the empty list.
6600
6601 # If the variable is defined conditionally, but is not defined in
6602 # terms of any variables which are defined conditionally, then this
6603 # returns the list of conditions for which the variable is defined.
6604
6605 # If the variable is defined in terms of any variables which are
6606 # defined conditionally, then this returns a full set of permutations
6607 # of the subvariable conditions.  For example, if the variable is
6608 # defined in terms of a variable which is defined for COND_TRUE,
6609 # then this returns both COND_TRUE and COND_FALSE.  This is
6610 # because we will need to define the variable under both conditions.
6611 sub variable_conditions_recursive ($)
6612 {
6613   my ($var) = @_;
6614
6615   %vars_scanned = ();
6616
6617   my @new_conds = variable_conditions_recursive_sub ($var, TRUE);
6618
6619   # Now we want to return all permutations of the subvariable
6620   # conditions.
6621   my %allconds = ();
6622     foreach my $item (@new_conds)
6623       {
6624         foreach ($item->conds)
6625           {
6626             s/^(.*)_(TRUE|FALSE)$/$1_TRUE/;
6627             $allconds{$_} = 1;
6628           }
6629       }
6630   @new_conds = variable_conditions_permutations (sort keys %allconds);
6631
6632   # Note we cannot just do `return sort @new_conds', because this
6633   # function is sometimes used in a scalar context.
6634   my @uniq_list = sort by_condition @new_conds;
6635   return @uniq_list;
6636 }
6637
6638
6639 # @CONDS
6640 # variable_conditions ($VAR)
6641 # --------------------------
6642 # Get the list of conditions that a variable is defined with, without
6643 # recursing through the conditions of any subvariables.
6644 # Argument is $VAR: the variable to get the conditions of.
6645 # Returns the list of conditions.
6646 sub variable_conditions ($)
6647 {
6648     my ($var) = @_;
6649     my @conds = keys %{$var_value{$var}};
6650     return sort by_condition @conds;
6651 }
6652
6653
6654 # $BOOLEAN
6655 # &variable_conditionally_defined ($VAR)
6656 # --------------------------------------
6657 sub variable_conditionally_defined ($)
6658 {
6659     my ($var) = @_;
6660     foreach my $cond (variable_conditions_recursive ($var))
6661       {
6662         return 1
6663           unless $cond =~ /^TRUE|FALSE$/;
6664       }
6665     return 0;
6666 }
6667
6668 # @LIST
6669 # &scan_variable_expansions ($TEXT)
6670 # ---------------------------------
6671 # Return the list of variable names expanded in $TEXT.
6672 # Note that unlike some other functions, $TEXT is not split
6673 # on spaces before we check for subvariables.
6674 sub scan_variable_expansions ($)
6675 {
6676   my ($text) = @_;
6677   my @result = ();
6678
6679   # Strip comments.
6680   $text =~ s/#.*$//;
6681
6682   # Record each use of ${stuff} or $(stuff) that do not follow a $.
6683   while ($text =~ /(?<!\$)\$(?:\{([^\}]*)\}|\(([^\)]*)\))/g)
6684     {
6685       my $var = $1 || $2;
6686       # The occurent may look like $(string1[:subst1=[subst2]]) but
6687       # we want only `string1'.
6688       $var =~ s/:[^:=]*=[^=]*$//;
6689       push @result, $var;
6690     }
6691
6692   return @result;
6693 }
6694
6695 # &check_variable_expansions ($TEXT, $WHERE)
6696 # ------------------------------------------
6697 # Check variable expansions in $TEXT and warn about any name that
6698 # does not conform to POSIX.  $WHERE is the location of $TEXT for
6699 # the error message.
6700 sub check_variable_expansions ($$)
6701 {
6702   my ($text, $where) = @_;
6703   # Catch expansion of variables whose name does not conform to POSIX.
6704   foreach my $var (scan_variable_expansions ($text))
6705     {
6706       if ($var !~ /$MACRO_PATTERN/)
6707         {
6708           # If the variable name contains a space, it's likely
6709           # to be a GNU make extension (such as $(addsuffix ...)).
6710           # Mention this in the diagnostic.
6711           my $gnuext = "";
6712           $gnuext = "\n(probably a GNU make extension)" if $var =~ / /;
6713           msg ('portability', $where,
6714                "$var: non-POSIX variable name$gnuext");
6715         }
6716     }
6717 }
6718
6719 # &variable_conditions_recursive_sub ($VAR, $PARENT)
6720 # -------------------------------------------------------
6721 # A subroutine of variable_conditions_recursive.  This returns all the
6722 # conditions of $VAR, including those of any sub-variables.
6723 sub variable_conditions_recursive_sub
6724 {
6725     my ($var, $parent) = @_;
6726     my @new_conds = ();
6727
6728     if (defined $vars_scanned{$var})
6729     {
6730         err_var $parent, "variable `$var' recursively defined";
6731         return ();
6732     }
6733     $vars_scanned{$var} = 1;
6734
6735     my @this_conds = ();
6736     # Examine every condition under which $VAR is defined.
6737     foreach my $vcond (keys %{$var_value{$var}})
6738     {
6739       push (@this_conds, $vcond);
6740
6741       # If $VAR references some other variable, then compute the
6742       # conditions for that subvariable.
6743       my @subvar_conds = ();
6744       foreach my $varname (scan_variable_expansions $var_value{$var}{$vcond})
6745         {
6746           if ($varname =~ /$SUBST_REF_PATTERN/o)
6747             {
6748               $varname = $1;
6749             }
6750
6751           # Here we compute all the conditions under which the
6752           # subvariable is defined.  Then we go through and add
6753           # $VCOND to each.
6754           my @svc = variable_conditions_recursive_sub ($varname, $var);
6755           foreach my $item (@svc)
6756             {
6757               push (@subvar_conds, $vcond->merge ($item));
6758             }
6759         }
6760
6761       # If there are no conditional subvariables, then we want to
6762       # return this condition.  Otherwise, we want to return the
6763       # permutations of the subvariables, taking into account the
6764       # conditions of $VAR.
6765       if (! @subvar_conds)
6766         {
6767           push (@new_conds, $vcond);
6768         }
6769       else
6770         {
6771           push (@new_conds, variable_conditions_reduce (@subvar_conds));
6772         }
6773     }
6774
6775     # Unset our entry in vars_scanned.  We only care about recursive
6776     # definitions.
6777     delete $vars_scanned{$var};
6778
6779     # If we are being called on behalf of another variable, we need to
6780     # return all possible permutations of the conditions.  We have
6781     # already handled everything in @this_conds along with their
6782     # subvariables.  We now need to add any permutations that are not
6783     # in @this_conds.
6784     foreach my $this_cond (@this_conds)
6785     {
6786         my @perms =
6787             variable_conditions_permutations ($this_cond->conds);
6788         foreach my $perm (@perms)
6789         {
6790             my $ok = 1;
6791             foreach my $scan (@this_conds)
6792             {
6793                 if ($perm->true_when ($scan) || $scan->true_when ($perm))
6794                 {
6795                     $ok = 0;
6796                     last;
6797                 }
6798             }
6799             next if ! $ok;
6800
6801             # This permutation was not already handled, and is valid
6802             # for the parents.
6803             push (@new_conds, $perm);
6804         }
6805     }
6806
6807     return @new_conds;
6808 }
6809
6810
6811 # Filter a list of conditionals so that only the exclusive ones are
6812 # retained.  For example, if both `COND1_TRUE COND2_TRUE' and
6813 # `COND1_TRUE' are in the list, discard the latter.
6814 # If the list is empty, return TRUE
6815 sub variable_conditions_reduce
6816 {
6817   my (@conds) = @_;
6818   my @ret = ();
6819   my $cond;
6820   while (@conds > 0)
6821     {
6822       $cond = shift @conds;
6823
6824       # FALSE is absorbent.
6825       return FALSE
6826         if $cond == FALSE;
6827
6828       if (! $cond->redundant_wrt (@ret, @conds))
6829         {
6830           push (@ret, $cond);
6831         }
6832     }
6833
6834   return TRUE if @ret == 0;
6835   return @ret;
6836 }
6837
6838 # @CONDS
6839 # invert_conditions (@CONDS)
6840 # --------------------------
6841 # Invert a list of conditionals.  Returns a set of conditionals which
6842 # are never true for any of the input conditionals, and when taken
6843 # together with the input conditionals cover all possible cases.
6844 #
6845 # For example:
6846 #   invert_conditions("A_TRUE B_TRUE", "A_FALSE B_FALSE")
6847 #     => ("A_FALSE B_TRUE", "A_TRUE B_FALSE")
6848 #
6849 #   invert_conditions("A_TRUE B_TRUE", "A_TRUE B_FALSE", "A_FALSE")
6850 #     => ()
6851 sub invert_conditions
6852 {
6853     my (@conds) = @_;
6854
6855     my @notconds = ();
6856
6857     # Generate all permutation for all inputs.
6858     my @perm = map { variable_conditions_permutations ($_->conds); } @conds;
6859     # Remove redundant conditions.
6860     @perm = variable_conditions_reduce @perm;
6861
6862     # Now remove all conditions which imply one of the input conditions.
6863     foreach my $perm (@perm)
6864     {
6865         push @notconds, $perm
6866             if ! $perm->implies_any (@conds);
6867     }
6868     return @notconds;
6869 }
6870
6871 # Return a list of permutations of a conditional string.
6872 # (But never output FALSE conditions, they are useless.)
6873 #
6874 # Examples:
6875 #   variable_conditions_permutations ("FOO_FALSE", "BAR_TRUE")
6876 #     => ("FOO_FALSE BAR_FALSE",
6877 #         "FOO_FALSE BAR_TRUE",
6878 #         "FOO_TRUE BAR_FALSE",
6879 #         "FOO_TRUE BAR_TRUE")
6880 #   variable_conditions_permutations ("FOO_FALSE", "TRUE")
6881 #     => ("FOO_FALSE TRUE",
6882 #         "FOO_TRUE TRUE")
6883 #   variable_conditions_permutations ("TRUE")
6884 #     => ("TRUE")
6885 #   variable_conditions_permutations ("FALSE")
6886 #     => ("TRUE")
6887 sub variable_conditions_permutations
6888 {
6889   my (@comps) = @_;
6890   return ()
6891     if ! @comps;
6892   my $comp = shift (@comps);
6893   return variable_conditions_permutations (@comps)
6894     if $comp eq '';
6895   my $neg = condition_negate ($comp);
6896
6897   my @ret;
6898   foreach my $sub (variable_conditions_permutations (@comps))
6899     {
6900       push (@ret, $sub->merge_conds ($comp)) if $comp ne 'FALSE';
6901       push (@ret, $sub->merge_conds ($neg)) if $neg ne 'FALSE';
6902     }
6903   if (! @ret)
6904     {
6905       push (@ret, new Automake::Conditional $comp) if $comp ne 'FALSE';
6906       push (@ret, new Automake::Conditional $neg) if $neg ne 'FALSE';
6907     }
6908   return @ret;
6909 }
6910
6911
6912 # $BOOL
6913 # &check_variable_defined_unconditionally($VAR, $PARENT)
6914 # ------------------------------------------------------
6915 # Warn if a variable is conditionally defined.  This is called if we
6916 # are using the value of a variable.
6917 sub check_variable_defined_unconditionally ($$)
6918 {
6919   my ($var, $parent) = @_;
6920   foreach my $cond (keys %{$var_value{$var}})
6921     {
6922       next
6923         if $cond->true || $cond->false;
6924
6925       if ($parent)
6926         {
6927           msg_var ('unsupported', $parent,
6928                    "automake does not support conditional definition of "
6929                    . "$var in $parent");
6930         }
6931       else
6932         {
6933           msg_var ('unsupported', $var,
6934                    "automake does not support $var being defined "
6935                    . "conditionally");
6936         }
6937     }
6938 }
6939
6940
6941 # Get the TRUE value of a variable, warn if the variable is
6942 # conditionally defined.
6943 sub variable_value
6944 {
6945     my ($var) = @_;
6946     &check_variable_defined_unconditionally ($var);
6947     return $var_value{$var}{&TRUE};
6948 }
6949
6950
6951 # @VALUES
6952 # &value_to_list ($VAR, $VAL, $COND, $WHERE, $LOC_WANTED)
6953 # -------------------------------------------------------
6954 # Convert a variable value to a list, split as whitespace.  This will
6955 # recursively follow $(...) and ${...} inclusions.  It preserves @...@
6956 # substitutions.
6957 #
6958 # If COND is 'all', then all values under all conditions should be
6959 # returned; if COND is a particular condition (all conditions are
6960 # surrounded by @...@) then only the value for that condition should
6961 # be returned; otherwise, warn if VAR is conditionally defined.
6962 # WHERE is the location where VAR=VAL.
6963 # If LOC_WANTED is set, return a list of [$location, @values] instead
6964 # of a list of @values.
6965 sub value_to_list ($$$$$)
6966 {
6967   my ($var, $val, $cond, $where, $loc_wanted) = @_;
6968   my @result;
6969
6970   # Strip backslashes
6971   $val =~ s/\\$/ /gm;
6972
6973   foreach (split (' ', $val))
6974     {
6975       # If a comment seen, just leave.
6976       last if /^#/;
6977
6978       # Handle variable substitutions. (The backslash in [^\}] and [^\)]
6979       # is here to help Emacs indenting correctly.)
6980       if (/^\$\{([^\}]*)\}$/ || /^\$\(([^\)]*)\)$/)
6981         {
6982           my $varname = $1;
6983
6984           # If the user uses a losing variable name, just ignore it.
6985           # This isn't ideal, but people have requested it.
6986           next if ($varname =~ /\@.*\@/);
6987
6988           my ($from, $to);
6989           my @temp_list;
6990           if ($varname =~ /$SUBST_REF_PATTERN/o)
6991             {
6992               $varname = $1;
6993               $to = $3;
6994               $from = quotemeta $2;
6995             }
6996
6997           # Find the value.
6998           @temp_list =
6999             variable_value_as_list_recursive_worker ($1, $cond, $var,
7000                                                      $loc_wanted);
7001
7002           # Now rewrite the values if appropriate.
7003           if (defined $from)
7004             {
7005               for my $val (@temp_list)
7006                 {
7007                   if ($loc_wanted)
7008                     {
7009                       $val->[0] =~ s/$from$/$to/;
7010                     }
7011                   else
7012                     {
7013                       $val =~ s/$from$/$to/;
7014                     }
7015                 }
7016             }
7017
7018           push (@result, @temp_list);
7019         }
7020       else
7021         {
7022           $_ = [$where->clone, $_] if $loc_wanted;
7023           push (@result, $_);
7024         }
7025     }
7026
7027   return @result;
7028 }
7029
7030
7031 # @VALUES
7032 # variable_value_as_list ($VAR, $COND, $PARENT)
7033 # ---------------------------------------------
7034 # Get the value of a variable given a specified condition. without
7035 # recursing through any subvariables.
7036 # Arguments are:
7037 #   $VAR    is the variable
7038 #   $COND   is the condition.  If this is not given, the value for the
7039 #           "TRUE" condition will be returned.
7040 #   $PARENT is the variable in which the variable is used: this is used
7041 #           only for error messages.
7042 # Returns the list of conditions.
7043 # For example, if A is defined as "foo $(B) bar", and B is defined as
7044 # "baz", this will return ("foo", "$(B)", "bar")
7045 sub variable_value_as_list
7046 {
7047     my ($var, $cond, $parent) = @_;
7048     my @result;
7049
7050     # Check defined
7051     return
7052       unless variable_assert $var, $parent;
7053
7054     # Get value for given condition
7055     my $onceflag;
7056     foreach my $vcond (keys %{$var_value{$var}})
7057     {
7058         my $val = $var_value{$var}{$vcond};
7059
7060         if ($vcond->true_when ($cond))
7061         {
7062             # Unless variable is not defined conditionally, there should only
7063             # be one value of $vcond true when $cond.
7064             &check_variable_defined_unconditionally ($var, $parent)
7065                     if $onceflag;
7066             $onceflag = 1;
7067
7068             # Strip backslashes
7069             $val =~ s/\\(\n|$)/ /g;
7070
7071             foreach (split (' ', $val))
7072             {
7073                 # If a comment seen, just leave.
7074                 last if /^#/;
7075
7076                 push (@result, $_);
7077             }
7078         }
7079     }
7080
7081     return @result;
7082 }
7083
7084
7085 # @VALUE
7086 # &variable_value_as_list_recursive_worker ($VAR, $COND, $PARENT, $LOC_WANTED)
7087 # ----------------------------------------------------------------------------
7088 # Return contents of VAR as a list, split on whitespace.  This will
7089 # recursively follow $(...) and ${...} inclusions.  It preserves @...@
7090 # substitutions.  If COND is 'all', then all values under all
7091 # conditions should be returned; if COND is a particular condition
7092 # (all conditions are surrounded by @...@) then only the value for
7093 # that condition should be returned; otherwise, warn if VAR is
7094 # conditionally defined.  If PARENT is specified, it is the name of
7095 # the including variable; this is only used for error reports.
7096 # If $LOC_WANTED is set, return a list of [$location, @values] instead
7097 # of a list of @values.
7098 sub variable_value_as_list_recursive_worker ($$$$)
7099 {
7100     my ($var, $cond, $parent, $loc_wanted) = @_;
7101     my @result = ();
7102
7103     return
7104       unless variable_assert $var, $parent;
7105
7106     if (defined $vars_scanned{$var})
7107     {
7108         # `vars_scanned' is a global we use to keep track of which
7109         # variables we've already examined.
7110         err_var $parent, "variable `$var' recursively defined";
7111     }
7112     elsif ($cond eq 'all')
7113     {
7114         $vars_scanned{$var} = 1;
7115         foreach my $vcond (keys %{$var_value{$var}})
7116         {
7117             push (@result, &value_to_list ($var,
7118                                            $var_value{$var}{$vcond},
7119                                            $cond,
7120                                            $var_location{$var}{$vcond},
7121                                            $loc_wanted));
7122         }
7123     }
7124     else
7125     {
7126         $vars_scanned{$var} = 1;
7127         my $onceflag;
7128         foreach my $vcond (keys %{$var_value{$var}})
7129         {
7130             my $val = $var_value{$var}{$vcond};
7131             my $where = $var_location{$var}{$vcond};
7132             if ($vcond->true_when ($cond))
7133             {
7134                 # Warn if we have an ambiguity.  It's hard to know how
7135                 # to handle this case correctly.
7136                 &check_variable_defined_unconditionally ($var, $parent)
7137                     if $onceflag;
7138                 $onceflag = 1;
7139                 push (@result, &value_to_list ($var, $val, $cond, $where,
7140                                                $loc_wanted));
7141             }
7142         }
7143     }
7144
7145     # Unset our entry in vars_scanned.  We only care about recursive
7146     # definitions.
7147     delete $vars_scanned{$var};
7148
7149     return @result;
7150 }
7151
7152
7153 # &variable_output ($VAR, [@CONDS])
7154 # ---------------------------------
7155 # Output all the values of $VAR is @COND is not specified, else only
7156 # that corresponding to @COND.
7157 sub variable_output ($@)
7158 {
7159   my ($var, @conds) = @_;
7160
7161   @conds = keys %{$var_value{$var}}
7162     unless @conds;
7163
7164   foreach my $cond (sort by_condition @conds)
7165     {
7166       prog_error ("unknown condition `$cond' for `$var'")
7167         unless exists $var_value{$var}{$cond};
7168
7169       if (exists $var_comment{$var} && exists $var_comment{$var}{$cond})
7170         {
7171           $output_vars .= $var_comment{$var}{$cond};
7172         }
7173
7174       my $val = $var_value{$var}{$cond};
7175       my $equals = $var_type{$var}{$cond} eq ':' ? ':=' : '=';
7176       my $output_var = "$var $equals $val";
7177       my $str = $cond->subst_string;
7178       $output_var =~ s/^/$str/meg;
7179       $output_vars .= $output_var . "\n";
7180     }
7181 }
7182
7183
7184 # &variable_pretty_output ($VAR, [@CONDS])
7185 # ----------------------------------------
7186 # Likewise, but pretty, i.e., we *split* the values at spaces.   Use only
7187 # with variables holding filenames.
7188 sub variable_pretty_output ($@)
7189 {
7190   my ($var, @conds) = @_;
7191
7192   @conds = keys %{$var_value{$var}}
7193     unless @conds;
7194
7195   foreach my $cond (sort by_condition @conds)
7196     {
7197       prog_error ("unknown condition `$cond' for `$var'")
7198         unless exists $var_value{$var}{$cond};
7199
7200       if (exists $var_comment{$var} && exists $var_comment{$var}{$cond})
7201         {
7202           $output_vars .= $var_comment{$var}{$cond};
7203         }
7204
7205       my $val = $var_value{$var}{$cond};
7206       my $equals = $var_type{$var}{$cond} eq ':' ? ':=' : '=';
7207       my $make_condition = $cond->subst_string;
7208       $output_vars .= pretty_print_internal ("$make_condition$var $equals",
7209                                              "$make_condition\t",
7210                                              split (' ' , $val));
7211     }
7212 }
7213
7214
7215 # &variable_value_as_list_recursive ($VAR, $COND, [$PARENT])
7216 # ----------------------------------------------------------
7217 # Return the list of values of $VAR in condition $COND.
7218 # $PARENT (if known) is the variable where this variable occurs,
7219 # in case we need to print an error message.
7220 sub variable_value_as_list_recursive ($$;$)
7221 {
7222     my ($var, $cond, $parent) = @_;
7223     # This global hash is used to avoid infinite recursion in
7224     # &variable_value_as_list_recursive_worker.
7225     %vars_scanned = ();
7226     return &variable_value_as_list_recursive_worker ($var, $cond, $parent, 0);
7227 }
7228
7229 # &variable_loc_and_value_as_list_recursive ($VAR, $COND, [$PARENT])
7230 # ----------------------------------------------------------------
7231 # Return the values of $VAR in condition $COND as a list of
7232 # [$location, @values] pairs.
7233 # $PARENT (if known) is the variable where this variable occurs,
7234 # in case we need to print an error message.
7235 sub variable_loc_and_value_as_list_recursive ($$;$)
7236 {
7237     my ($var, $cond, $parent) = @_;
7238     %vars_scanned = ();
7239     return &variable_value_as_list_recursive_worker ($var, $cond, $parent, 1);
7240 }
7241
7242
7243 # &define_pretty_variable ($VAR, $COND, $WHERE, @VALUE)
7244 # -----------------------------------------------------
7245 # Like define_variable, but the value is a list, and the variable may
7246 # be defined conditionally.  The second argument is the conditional
7247 # under which the value should be defined; this should be the empty
7248 # string to define the variable unconditionally.  The third argument
7249 # is a list holding the values to use for the variable.  The value is
7250 # pretty printed in the output file.
7251 sub define_pretty_variable ($$$@)
7252 {
7253     my ($var, $cond, $where, @value) = @_;
7254
7255     if (! variable_defined ($var, $cond))
7256     {
7257         macro_define ($var, VAR_AUTOMAKE, '', $cond, "@value", $where);
7258         variable_pretty_output ($var, $cond);
7259         $content_seen{$var} = 1;
7260     }
7261 }
7262
7263
7264 # define_variable ($VAR, $VALUE, $WHERE)
7265 # --------------------------------------
7266 # Define a new user variable VAR to VALUE, but only if not already defined.
7267 sub define_variable ($$$)
7268 {
7269     my ($var, $value, $where) = @_;
7270     define_pretty_variable ($var, TRUE, $where, $value);
7271 }
7272
7273
7274 # Like define_variable, but define a variable to be the configure
7275 # substitution by the same name.
7276 sub define_configure_variable ($)
7277 {
7278   my ($var) = @_;
7279   if (! variable_defined ($var, TRUE)
7280       # Explicitly avoid ANSI2KNR -- we AC_SUBST that in
7281       # protos.m4, but later define it elsewhere.  This is
7282       # pretty hacky.  We also explicitly avoid AMDEPBACKSLASH:
7283       # it might be subst'd by `\', which certainly would not be
7284       # appreciated by Make.
7285       && ! grep { $_ eq $var } (qw(ANSI2KNR AMDEPBACKSLASH)))
7286     {
7287       macro_define ($var, VAR_CONFIGURE, '', TRUE,
7288                     subst $var, $configure_vars{$var});
7289       variable_pretty_output ($var, TRUE);
7290     }
7291 }
7292
7293
7294 # define_compiler_variable ($LANG)
7295 # --------------------------------
7296 # Define a compiler variable.  We also handle defining the `LT'
7297 # version of the command when using libtool.
7298 sub define_compiler_variable ($)
7299 {
7300     my ($lang) = @_;
7301
7302     my ($var, $value) = ($lang->compiler, $lang->compile);
7303     &define_variable ($var, $value, INTERNAL);
7304     &define_variable ("LT$var", "\$(LIBTOOL) --mode=compile $value", INTERNAL)
7305       if variable_defined ('LIBTOOL');
7306 }
7307
7308
7309 # define_linker_variable ($LANG)
7310 # ------------------------------
7311 # Define linker variables.
7312 sub define_linker_variable ($)
7313 {
7314     my ($lang) = @_;
7315
7316     my ($var, $value) = ($lang->lder, $lang->ld);
7317     # CCLD = $(CC).
7318     &define_variable ($lang->lder, $lang->ld, INTERNAL);
7319     # CCLINK = $(CCLD) blah blah...
7320     &define_variable ($lang->linker,
7321                       ((variable_defined ('LIBTOOL')
7322                         ? '$(LIBTOOL) --mode=link ' : '')
7323                        . $lang->link),
7324                       INTERNAL);
7325 }
7326
7327 ################################################################
7328
7329 ## ---------------- ##
7330 ## Handling rules.  ##
7331 ## ---------------- ##
7332
7333 sub register_suffix_rule ($$$)
7334 {
7335   my ($where, $src, $dest) = @_;
7336
7337   verb "Sources ending in $src become $dest";
7338   push @suffixes, $src, $dest;
7339
7340   # When tranforming sources to objects, Automake uses the
7341   # %suffix_rules to move from each source extension to
7342   # `.$(OBJEXT)', not to `.o' or `.obj'.  However some people
7343   # define suffix rules for `.o' or `.obj', so internally we will
7344   # consider these extensions equivalent to `.$(OBJEXT)'.  We
7345   # CANNOT rewrite the target (i.e., automagically replace `.o'
7346   # and `.obj' by `.$(OBJEXT)' in the output), or warn the user
7347   # that (s)he'd better use `.$(OBJEXT)', because Automake itself
7348   # output suffix rules for `.o' or `.obj'...
7349   $dest = '.$(OBJEXT)' if ($dest eq '.o' || $dest eq '.obj');
7350
7351   # Reading the comments near the declaration of $suffix_rules might
7352   # help to understand the update of $suffix_rules that follows...
7353
7354   # Register $dest as a possible destination from $src.
7355   # We might have the create the \hash.
7356   if (exists $suffix_rules->{$src})
7357     {
7358       $suffix_rules->{$src}{$dest} = [ $dest, 1 ];
7359     }
7360   else
7361     {
7362       $suffix_rules->{$src} = { $dest => [ $dest, 1 ] };
7363     }
7364
7365   # If we know how to transform $dest in something else, then
7366   # we know how to transform $src in that "something else".
7367   if (exists $suffix_rules->{$dest})
7368     {
7369       for my $dest2 (keys %{$suffix_rules->{$dest}})
7370         {
7371           my $dist = $suffix_rules->{$dest}{$dest2}[1] + 1;
7372           # Overwrite an existing $src->$dest2 path only if
7373           # the path via $dest which is shorter.
7374           if (! exists $suffix_rules->{$src}{$dest2}
7375               || $suffix_rules->{$src}{$dest2}[1] > $dist)
7376             {
7377               $suffix_rules->{$src}{$dest2} = [ $dest, $dist ];
7378             }
7379         }
7380     }
7381
7382   # Similarly, any extension that can be derived into $src
7383   # can be derived into the same extenstions as $src can.
7384   my @dest2 = keys %{$suffix_rules->{$src}};
7385   for my $src2 (keys %$suffix_rules)
7386     {
7387       if (exists $suffix_rules->{$src2}{$src})
7388         {
7389           for my $dest2 (@dest2)
7390             {
7391               my $dist = $suffix_rules->{$src}{$dest2} + 1;
7392               # Overwrite an existing $src2->$dest2 path only if
7393               # the path via $src is shorter.
7394               if (! exists $suffix_rules->{$src2}{$dest2}
7395                   || $suffix_rules->{$src2}{$dest2}[1] > $dist)
7396                 {
7397                   $suffix_rules->{$src2}{$dest2} = [ $src, $dist ];
7398                 }
7399             }
7400         }
7401     }
7402 }
7403
7404 # @CONDS
7405 # rule_define ($TARGET, $SOURCE, $OWNER, $COND, $WHERE)
7406 # -----------------------------------------------------
7407 # Define a new rule.  $TARGET is the rule name.  $SOURCE
7408 # is the filename the rule comes from.  $OWNER is the
7409 # owener of the rule (TARGET_AUTOMAKE or TARGET_USER).
7410 # $COND is the condition string under which the rule is defined.
7411 # $WHERE is the location where the rule is defined.
7412 # Returns a (possibly empty) list of conditions where the rule
7413 # should be defined.
7414 sub rule_define ($$$$$)
7415 {
7416   my ($target, $source, $owner, $cond, $where) = @_;
7417
7418   prog_error "$where is not a reference"
7419     unless ref $where;
7420   prog_error "$cond is not a reference"
7421     unless ref $cond;
7422
7423   # Don't even think about defining a rule in condition FALSE.
7424   return () if $cond == FALSE;
7425
7426   # For now `foo:' will override `foo$(EXEEXT):'.  This is temporary,
7427   # though, so we emit a warning.
7428   (my $noexe = $target) =~ s,\$\(EXEEXT\)$,,;
7429   if ($noexe ne $target
7430       && exists $targets{$noexe}
7431       && exists $targets{$noexe}{$cond}
7432       && $target_name{$noexe}{$cond} ne $target)
7433     {
7434       # The no-exeext option enables this feature.
7435       if (! defined $options{'no-exeext'})
7436         {
7437           msg ('obsolete', $targets{$noexe}{$cond},
7438                "deprecated feature: target `$noexe' overrides "
7439                . "`$noexe\$(EXEEXT)'\n"
7440                . "change your target to read `$noexe\$(EXEEXT)'");
7441           msg ('obsolete', $where, "target `$target' was defined here");
7442         }
7443       # Don't `return ()' now, as this might hide target clashes
7444       # detected below.
7445     }
7446
7447   # For now on, strip off $(EXEEXT) from $target, so we can diagnose
7448   # a clash if `ctags$(EXEEXT):' is redefined after `ctags:'.
7449   my $realtarget = $target;
7450   $target = $noexe;
7451
7452   # A GNU make-style pattern rule has a single "%" in the target name.
7453   msg ('portability', $where,
7454        "`%'-style pattern rules are a GNU make extension")
7455     if $target =~ /^[^%]*%[^%]*$/;
7456
7457   # Diagnose target redefinitions.
7458   if (exists $target_source{$target}{$cond})
7459     {
7460       # Sanity checks.
7461       prog_error ("\$target_source{$target}{$cond} exists, but \$target_owner"
7462                   . " doesn't.")
7463         unless exists $target_owner{$target}{$cond};
7464       prog_error ("\$target_source{$target}{$cond} exists, but \$targets"
7465                   . " doesn't.")
7466         unless exists $targets{$target}{$cond};
7467       prog_error ("\$target_source{$target}{$cond} exists, but \$target_name"
7468                   . " doesn't.")
7469         unless exists $target_name{$target}{$cond};
7470
7471       my $oldowner  = $target_owner{$target}{$cond};
7472
7473       # Don't mention true conditions in diagnostics.
7474       my $condmsg = $cond == TRUE ? " in condition `$cond'" : '';
7475
7476       if ($owner == TARGET_USER)
7477         {
7478           if ($oldowner eq TARGET_USER)
7479             {
7480               # Ignore `%'-style pattern rules.  We'd need the
7481               # dependencies to detect duplicates, and they are
7482               # already diagnosed as unportable by -Wportability.
7483               if ($target !~ /^[^%]*%[^%]*$/)
7484                 {
7485                   ## FIXME: Presently we can't diagnose duplcate user rules
7486                   ## because we doesn't distinguish rules with commands
7487                   ## from rules that only add dependencies.  E.g.,
7488                   ##   .PHONY: foo
7489                   ##   .PHONY: bar
7490                   ## is legitimate. (This is phony.test.)
7491
7492                   # msg ('syntax', $where,
7493                   #      "redefinition of `$target'$condmsg...", partial => 1);
7494                   # msg_cond_target ('syntax', $cond, $target,
7495                   #                "... `$target' previously defined here");
7496                 }
7497               # Return so we don't redefine the rule in our tables,
7498               # don't check for ambiguous conditional, etc.  The rule
7499               # will be output anyway beauce &read_am_file ignore the
7500               # return code.
7501               return ();
7502             }
7503           else
7504             {
7505               # Since we parse the user Makefile.am before reading
7506               # the Automake fragments, this condition should never happen.
7507               prog_error ("user target `$target' seen after Automake's "
7508                           . "definition\nfrom `$targets{$target}$condmsg'");
7509             }
7510         }
7511       else # $owner == TARGET_AUTOMAKE
7512         {
7513           if ($oldowner == TARGET_USER)
7514             {
7515               # Don't overwrite the user definition of TARGET.
7516               return ();
7517             }
7518           else # $oldowner == TARGET_AUTOMAKE
7519             {
7520               # Automake should ignore redefinitions of its own
7521               # rules if they came from the same file.  This makes
7522               # it easier to process a Makefile fragment several times.
7523               # Hower it's an error if the target is defined in many
7524               # files.  E.g., the user might be using bin_PROGRAMS = ctags
7525               # which clashes with our `ctags' rule.
7526               # (It would be more accurate if we had a way to compare
7527               # the *content* of both rules.  Then $targets_source would
7528               # be useless.)
7529               my $oldsource = $target_source{$target}{$cond};
7530               return () if $source eq $oldsource;
7531
7532               msg ('syntax', $where, "redefinition of `$target'$condmsg...",
7533                    partial => 1);
7534               msg_cond_target ('syntax', $cond, $target,
7535                                "... `$target' previously defined here");
7536               return ();
7537             }
7538         }
7539       # Never reached.
7540       prog_error ("Unreachable place reached.");
7541     }
7542
7543   # Conditions for which the rule should be defined.
7544   my @conds = $cond;
7545
7546   # Check ambiguous conditional definitions.
7547   my ($message, $ambig_cond) =
7548     conditional_ambiguous_p ($target, $cond, keys %{$targets{$target}});
7549   if ($message)                 # We have an ambiguty.
7550     {
7551       if ($owner == TARGET_USER)
7552         {
7553           # For user rules, just diagnose the ambiguity.
7554           msg 'syntax', $where, "$message ...", partial => 1;
7555           msg_cond_target ('syntax', $ambig_cond, $target,
7556                            "... `$target' previously defined here");
7557           return ();
7558         }
7559       else
7560         {
7561           # FIXME: for Automake rules, we can't diagnose ambiguities yet.
7562           # The point is that Automake doesn't propagate conditionals
7563           # everywhere.  For instance &handle_PROGRAMS doesn't care if
7564           # bin_PROGRAMS was defined conditionally or not.
7565           # On the following input
7566           #   if COND1
7567           #   foo:
7568           #           ...
7569           #   else
7570           #   bin_PROGRAMS = foo
7571           #   endif
7572           # &handle_PROGRAMS will attempt to define a `foo:' rule
7573           # in condition TRUE (which conflicts with COND1).  Fixing
7574           # this in &handle_PROGRAMS and siblings seems hard: you'd
7575           # have to explain &file_contents what to do with a
7576           # conditional.  So for now we do our best *here*.  If `foo:'
7577           # was already defined in condition COND1 and we want to define
7578           # it in condition TRUE, then define it only in condition !COND1.
7579           # (See cond14.test and cond15.test for some test cases.)
7580           my @defined_conds = keys %{$targets{$target}};
7581           @conds = ();
7582           for my $undefined_cond (invert_conditions(@defined_conds))
7583             {
7584               push @conds, $cond->merge ($undefined_cond);
7585             }
7586           # No conditions left to define the rule.
7587           # Warn, because our workaround is meaningless in this case.
7588           if (scalar @conds == 0)
7589             {
7590               msg 'syntax', $where, "$message ...", partial => 1;
7591               msg_cond_target ('syntax', $ambig_cond, $target,
7592                                "... `$target' previously defined here");
7593               return ();
7594             }
7595         }
7596     }
7597
7598   # Finally define this rule.
7599   for my $c (@conds)
7600     {
7601       $targets{$target}{$c} = $where->clone;
7602       $target_source{$target}{$c} = $source;
7603       $target_owner{$target}{$c} = $owner;
7604       $target_name{$target}{$c} = $realtarget;
7605     }
7606
7607   # Check the rule for being a suffix rule. If so, store in a hash.
7608   # Either it's a rule for two known extensions...
7609   if ($target =~ /^($KNOWN_EXTENSIONS_PATTERN)($KNOWN_EXTENSIONS_PATTERN)$/
7610       # ...or it's a rule with unknown extensions (.i.e, the rule looks like
7611       # `.foo.bar:' but `.foo' or `.bar' are not declared in SUFFIXES
7612       # and are not known language extensions).
7613       # Automake will complete SUFFIXES from @suffixes automatically
7614       # (see handle_footer).
7615       || ($target =~ /$SUFFIX_RULE_PATTERN/o && accept_extensions($1)))
7616     {
7617       register_suffix_rule ($where, $1, $2);
7618     }
7619
7620   return @conds;
7621 }
7622
7623
7624 # See if a target exists.
7625 sub target_defined
7626 {
7627     my ($target) = @_;
7628     return exists $targets{$target};
7629 }
7630
7631
7632 ################################################################
7633
7634 # &append_comments ($VARIABLE, $SPACING, $COMMENT)
7635 # ------------------------------------------------
7636 # Apped $COMMENT to the other comments for $VARIABLE, using
7637 # $SPACING as separator.
7638 sub append_comments ($$$$)
7639 {
7640     my ($cond, $var, $spacing, $comment) = @_;
7641     $var_comment{$var}{$cond} .= $spacing
7642         if (!defined $var_comment{$var}{$cond}
7643             || $var_comment{$var}{$cond} !~ /\n$/o);
7644     $var_comment{$var}{$cond} .= $comment;
7645 }
7646
7647
7648 # &read_am_file ($AMFILE, $WHERE)
7649 # -------------------------------
7650 # Read Makefile.am and set up %contents.  Simultaneously copy lines
7651 # from Makefile.am into $output_trailer or $output_vars as
7652 # appropriate.  NOTE we put rules in the trailer section.  We want
7653 # user rules to come after our generated stuff.
7654 sub read_am_file ($$)
7655 {
7656     my ($amfile, $where) = @_;
7657
7658     my $am_file = new Automake::XFile ("< $amfile");
7659     verb "reading $amfile";
7660
7661     my $spacing = '';
7662     my $comment = '';
7663     my $blank = 0;
7664     my $saw_bk = 0;
7665
7666     use constant IN_VAR_DEF => 0;
7667     use constant IN_RULE_DEF => 1;
7668     use constant IN_COMMENT => 2;
7669     my $prev_state = IN_RULE_DEF;
7670
7671     while ($_ = $am_file->getline)
7672     {
7673         $where->set ("$amfile:$.");
7674         if (/$IGNORE_PATTERN/o)
7675         {
7676             # Merely delete comments beginning with two hashes.
7677         }
7678         elsif (/$WHITE_PATTERN/o)
7679         {
7680             err $where, "blank line following trailing backslash"
7681               if $saw_bk;
7682             # Stick a single white line before the incoming macro or rule.
7683             $spacing = "\n";
7684             $blank = 1;
7685             # Flush all comments seen so far.
7686             if ($comment ne '')
7687             {
7688                 $output_vars .= $comment;
7689                 $comment = '';
7690             }
7691         }
7692         elsif (/$COMMENT_PATTERN/o)
7693         {
7694             # Stick comments before the incoming macro or rule.  Make
7695             # sure a blank line preceeds first block of comments.
7696             $spacing = "\n" unless $blank;
7697             $blank = 1;
7698             $comment .= $spacing . $_;
7699             $spacing = '';
7700             $prev_state = IN_COMMENT;
7701         }
7702         else
7703         {
7704             last;
7705         }
7706         $saw_bk = /\\$/ && ! /$IGNORE_PATTERN/o;
7707     }
7708
7709     # We save the conditional stack on entry, and then check to make
7710     # sure it is the same on exit.  This lets us conditonally include
7711     # other files.
7712     my @saved_cond_stack = @cond_stack;
7713     my $cond = new Automake::Conditional (@cond_stack);
7714
7715     my $last_var_name = '';
7716     my $last_var_type = '';
7717     my $last_var_value = '';
7718     # FIXME: shouldn't use $_ in this loop; it is too big.
7719     while ($_)
7720     {
7721         $where->set ("$amfile:$.");
7722
7723         # Make sure the line is \n-terminated.
7724         chomp;
7725         $_ .= "\n";
7726
7727         # Don't look at MAINTAINER_MODE_TRUE here.  That shouldn't be
7728         # used by users.  @MAINT@ is an anachronism now.
7729         $_ =~ s/\@MAINT\@//g
7730             unless $seen_maint_mode;
7731
7732         my $new_saw_bk = /\\$/ && ! /$IGNORE_PATTERN/o;
7733
7734         if (/$IGNORE_PATTERN/o)
7735         {
7736             # Merely delete comments beginning with two hashes.
7737         }
7738         elsif (/$WHITE_PATTERN/o)
7739         {
7740             # Stick a single white line before the incoming macro or rule.
7741             $spacing = "\n";
7742             err $where, "blank line following trailing backslash"
7743               if $saw_bk;
7744         }
7745         elsif (/$COMMENT_PATTERN/o)
7746         {
7747             # Stick comments before the incoming macro or rule.
7748             $comment .= $spacing . $_;
7749             $spacing = '';
7750             err $where, "comment following trailing backslash"
7751               if $saw_bk && $comment eq '';
7752             $prev_state = IN_COMMENT;
7753         }
7754         elsif ($saw_bk)
7755         {
7756             if ($prev_state == IN_RULE_DEF)
7757             {
7758               my $cond = new Automake::Conditional @cond_stack;
7759               $output_trailer .= $cond->subst_string;
7760               $output_trailer .= $_;
7761             }
7762             elsif ($prev_state == IN_COMMENT)
7763             {
7764                 # If the line doesn't start with a `#', add it.
7765                 # We do this because a continuated comment like
7766                 #   # A = foo \
7767                 #         bar \
7768                 #         baz
7769                 # is not portable.  BSD make doesn't honor
7770                 # escaped newlines in comments.
7771                 s/^#?/#/;
7772                 $comment .= $spacing . $_;
7773             }
7774             else # $prev_state == IN_VAR_DEF
7775             {
7776               $last_var_value .= ' '
7777                 unless $last_var_value =~ /\s$/;
7778               $last_var_value .= $_;
7779
7780               if (!/\\$/)
7781                 {
7782                   append_comments ($cond, $last_var_name, $spacing, $comment);
7783                   $comment = $spacing = '';
7784                   macro_define ($last_var_name, VAR_MAKEFILE,
7785                                 $last_var_type, $cond,
7786                                 $last_var_value, $where)
7787                     if $cond != FALSE;
7788                   push (@var_list, $last_var_name);
7789                 }
7790             }
7791         }
7792
7793         elsif (/$IF_PATTERN/o)
7794           {
7795             $cond = cond_stack_if ($1, $2, $where);
7796           }
7797         elsif (/$ELSE_PATTERN/o)
7798           {
7799             $cond = cond_stack_else ($1, $2, $where);
7800           }
7801         elsif (/$ENDIF_PATTERN/o)
7802           {
7803             $cond = cond_stack_endif ($1, $2, $where);
7804           }
7805
7806         elsif (/$RULE_PATTERN/o)
7807         {
7808             # Found a rule.
7809             $prev_state = IN_RULE_DEF;
7810
7811             # For now we have to output all definitions of user rules
7812             # and can't diagnose duplicates (see the comment in
7813             # rule_define). So we go on and ignore the return value.
7814             rule_define ($1, $amfile, TARGET_USER, $cond, $where);
7815
7816             check_variable_expansions ($_, $where);
7817
7818             $output_trailer .= $comment . $spacing;
7819             my $cond = new Automake::Conditional @cond_stack;
7820             $output_trailer .= $cond->subst_string;
7821             $output_trailer .= $_;
7822             $comment = $spacing = '';
7823         }
7824         elsif (/$ASSIGNMENT_PATTERN/o)
7825         {
7826             # Found a macro definition.
7827             $prev_state = IN_VAR_DEF;
7828             $last_var_name = $1;
7829             $last_var_type = $2;
7830             $last_var_value = $3;
7831             if ($3 ne '' && substr ($3, -1) eq "\\")
7832             {
7833                 # We preserve the `\' because otherwise the long lines
7834                 # that are generated will be truncated by broken
7835                 # `sed's.
7836                 $last_var_value = $3 . "\n";
7837             }
7838
7839             if (!/\\$/)
7840               {
7841                 # Accumulating variables must not be output.
7842                 append_comments ($cond, $last_var_name, $spacing, $comment);
7843                 $comment = $spacing = '';
7844
7845                 macro_define ($last_var_name, VAR_MAKEFILE,
7846                               $last_var_type, $cond,
7847                               $last_var_value, $where)
7848                   if $cond != FALSE;
7849                 push (@var_list, $last_var_name);
7850               }
7851         }
7852         elsif (/$INCLUDE_PATTERN/o)
7853         {
7854             my $path = $1;
7855
7856             if ($path =~ s/^\$\(top_srcdir\)\///)
7857               {
7858                 push (@include_stack, "\$\(top_srcdir\)/$path");
7859                 # Distribute any included file.
7860
7861                 # Always use the $(top_srcdir) prefix in DIST_COMMON,
7862                 # otherwise OSF make will implicitely copy the included
7863                 # file in the build tree during `make distdir' to satisfy
7864                 # the dependency.
7865                 # (subdircond2.test and subdircond3.test will fail.)
7866                 push_dist_common ("\$\(top_srcdir\)/$path");
7867               }
7868             else
7869               {
7870                 $path =~ s/\$\(srcdir\)\///;
7871                 push (@include_stack, "\$\(srcdir\)/$path");
7872                 # Always use the $(srcdir) prefix in DIST_COMMON,
7873                 # otherwise OSF make will implicitely copy the included
7874                 # file in the build tree during `make distdir' to satisfy
7875                 # the dependency.
7876                 # (subdircond2.test and subdircond3.test will fail.)
7877                 push_dist_common ("\$\(srcdir\)/$path");
7878                 $path = $relative_dir . "/" . $path if $relative_dir ne '.';
7879               }
7880             $where->push_context ("`$path' included from here");
7881             &read_am_file ($path, $where);
7882             $where->pop_context;
7883         }
7884         else
7885         {
7886             # This isn't an error; it is probably a continued rule.
7887             # In fact, this is what we assume.
7888             $prev_state = IN_RULE_DEF;
7889             check_variable_expansions ($_, $where);
7890             $output_trailer .= $comment . $spacing;
7891             my $cond = new Automake::Conditional @cond_stack;
7892             $output_trailer .= $cond->subst_string;
7893             $output_trailer .= $_;
7894             $comment = $spacing = '';
7895             err $where, "`#' comment at start of rule is unportable"
7896               if $_ =~ /^\t\s*\#/;
7897         }
7898
7899         $saw_bk = $new_saw_bk;
7900         $_ = $am_file->getline;
7901     }
7902
7903     $output_trailer .= $comment;
7904
7905     err ($where, (@cond_stack ? "unterminated conditionals: @cond_stack"
7906                   : "too many conditionals closed in include file"))
7907       if "@saved_cond_stack" ne "@cond_stack";
7908 }
7909
7910
7911 # define_standard_variables ()
7912 # ----------------------------
7913 # A helper for read_main_am_file which initializes configure variables
7914 # and variables from header-vars.am.
7915 sub define_standard_variables
7916 {
7917     my $saved_output_vars = $output_vars;
7918     my ($comments, undef, $rules) =
7919       file_contents_internal (1, "$libdir/am/header-vars.am",
7920                               new Automake::Location);
7921
7922     # This will output the definitions in $output_vars, which we don't
7923     # want...
7924     foreach my $var (sort keys %configure_vars)
7925     {
7926         &define_configure_variable ($var);
7927         push (@var_list, $var);
7928     }
7929
7930     # ... hence, we restore $output_vars.
7931     $output_vars = $saved_output_vars . $comments . $rules;
7932 }
7933
7934 # Read main am file.
7935 sub read_main_am_file
7936 {
7937     my ($amfile) = @_;
7938
7939     # This supports the strange variable tricks we are about to play.
7940     prog_error (macros_dump () . "variable defined before read_main_am_file")
7941       if (scalar keys %var_value > 0);
7942
7943     # Generate copyright header for generated Makefile.in.
7944     # We do discard the output of predefined variables, handled below.
7945     $output_vars = ("# $in_file_name generated by automake "
7946                    . $VERSION . " from $am_file_name.\n");
7947     $output_vars .= '# ' . subst ('configure_input') . "\n";
7948     $output_vars .= $gen_copyright;
7949
7950     # We want to predefine as many variables as possible.  This lets
7951     # the user set them with `+=' in Makefile.am.  However, we don't
7952     # want these initial definitions to end up in the output quite
7953     # yet.  So we just load them, but output them later.
7954     &define_standard_variables;
7955
7956     # Read user file, which might override some of our values.
7957     &read_am_file ($amfile, new Automake::Location);
7958
7959     # Output all the Automake variables.  If the user changed one,
7960     # then it is now marked as VAR_CONFIGURE or VAR_MAKEFILE.
7961     foreach my $var (uniq @var_list)
7962     {
7963       # Some variables, like AMDEPBACKSLASH are in @var_list
7964       # but don't have a owner.  This is good, because we don't want
7965       # to output them.
7966       foreach my $cond (keys %{$var_owner{$var}})
7967         {
7968           variable_output ($var, $cond)
7969             if $var_owner{$var}{$cond} == VAR_AUTOMAKE;
7970         }
7971     }
7972
7973     # Now dump the user variables that were defined.  We do it in the same
7974     # order in which they were defined (skipping duplicates).
7975     foreach my $var (uniq @var_list)
7976     {
7977       foreach my $cond (keys %{$var_owner{$var}})
7978         {
7979           variable_output ($var, $cond)
7980             if $var_owner{$var}{$cond} != VAR_AUTOMAKE;
7981         }
7982     }
7983 }
7984
7985 ################################################################
7986
7987 # $FLATTENED
7988 # &flatten ($STRING)
7989 # ------------------
7990 # Flatten the $STRING and return the result.
7991 sub flatten
7992 {
7993   $_ = shift;
7994
7995   s/\\\n//somg;
7996   s/\s+/ /g;
7997   s/^ //;
7998   s/ $//;
7999
8000   return $_;
8001 }
8002
8003
8004 # @PARAGRAPHS
8005 # &make_paragraphs ($MAKEFILE, [%TRANSFORM])
8006 # ------------------------------------------
8007 # Load a $MAKEFILE, apply the %TRANSFORM, and return it as a list of
8008 # paragraphs.
8009 sub make_paragraphs ($%)
8010 {
8011     my ($file, %transform) = @_;
8012
8013     # Complete %transform with global options and make it a Perl
8014     # $command.
8015     my $command =
8016       "s/$IGNORE_PATTERN//gm;"
8017         . transform (%transform,
8018
8019                      'CYGNUS'          => $cygnus_mode,
8020                      'MAINTAINER-MODE'
8021                      => $seen_maint_mode ? subst ('MAINTAINER_MODE_TRUE') : '',
8022
8023                      'SHAR'        => $options{'dist-shar'} || 0,
8024                      'BZIP2'       => $options{'dist-bzip2'} || 0,
8025                      'ZIP'         => $options{'dist-zip'} || 0,
8026                      'COMPRESS'    => $options{'dist-tarZ'} || 0,
8027
8028                      'INSTALL-INFO' => !$options{'no-installinfo'},
8029                      'INSTALL-MAN'  => !$options{'no-installman'},
8030                      'CK-NEWS'      => $options{'check-news'} || 0,
8031
8032                      'SUBDIRS'      => variable_defined ('SUBDIRS'),
8033                      'TOPDIR'       => backname ($relative_dir),
8034                      'TOPDIR_P'     => $relative_dir eq '.',
8035                      'CONFIGURE-AC' => $configure_ac,
8036
8037                      'BUILD'    => $seen_canonical == AC_CANONICAL_SYSTEM,
8038                      'HOST'     => $seen_canonical,
8039                      'TARGET'   => $seen_canonical == AC_CANONICAL_SYSTEM,
8040
8041                      'LIBTOOL'      => variable_defined ('LIBTOOL'))
8042           # We don't need more than two consecutive new-lines.
8043           . 's/\n{3,}/\n\n/g';
8044
8045     # Swallow the file and apply the COMMAND.
8046     my $fc_file = new Automake::XFile "< $file";
8047     # Looks stupid?
8048     verb "reading $file";
8049     my $saved_dollar_slash = $/;
8050     undef $/;
8051     $_ = $fc_file->getline;
8052     $/ = $saved_dollar_slash;
8053     eval $command;
8054     $fc_file->close;
8055     my $content = $_;
8056
8057     # Split at unescaped new lines.
8058     my @lines = split (/(?<!\\)\n/, $content);
8059     my @res;
8060
8061     while (defined ($_ = shift @lines))
8062       {
8063         my $paragraph = "$_";
8064         # If we are a rule, eat as long as we start with a tab.
8065         if (/$RULE_PATTERN/smo)
8066           {
8067             while (defined ($_ = shift @lines) && $_ =~ /^\t/)
8068               {
8069                 $paragraph .= "\n$_";
8070               }
8071             unshift (@lines, $_);
8072           }
8073
8074         # If we are a comments, eat as much comments as you can.
8075         elsif (/$COMMENT_PATTERN/smo)
8076           {
8077             while (defined ($_ = shift @lines)
8078                    && $_ =~ /$COMMENT_PATTERN/smo)
8079               {
8080                 $paragraph .= "\n$_";
8081               }
8082             unshift (@lines, $_);
8083           }
8084
8085         push @res, $paragraph;
8086         $paragraph = '';
8087       }
8088
8089     return @res;
8090 }
8091
8092
8093
8094 # ($COMMENT, $VARIABLES, $RULES)
8095 # &file_contents_internal ($IS_AM, $FILE, $WHERE, [%TRANSFORM])
8096 # -------------------------------------------------------------
8097 # Return contents of a file from $libdir/am, automatically skipping
8098 # macros or rules which are already known. $IS_AM iff the caller is
8099 # reading an Automake file (as opposed to the user's Makefile.am).
8100 sub file_contents_internal ($$$%)
8101 {
8102     my ($is_am, $file, $where, %transform) = @_;
8103
8104     $where->set ($file);
8105
8106     my $result_vars = '';
8107     my $result_rules = '';
8108     my $comment = '';
8109     my $spacing = '';
8110
8111     # The following flags are used to track rules spanning across
8112     # multiple paragraphs.
8113     my $is_rule = 0;            # 1 if we are processing a rule.
8114     my $discard_rule = 0;       # 1 if the current rule should not be output.
8115
8116     # We save the conditional stack on entry, and then check to make
8117     # sure it is the same on exit.  This lets us conditonally include
8118     # other files.
8119     my @saved_cond_stack = @cond_stack;
8120     my $cond = new Automake::Conditional (@cond_stack);
8121
8122     foreach (make_paragraphs ($file, %transform))
8123     {
8124         # FIXME: no line number available.
8125         $where->set ($file);
8126
8127         # Sanity checks.
8128         err $where, "blank line following trailing backslash:\n$_"
8129           if /\\$/;
8130         err $where, "comment following trailing backslash:\n$_"
8131           if /\\#/;
8132
8133         if (/^$/)
8134         {
8135             $is_rule = 0;
8136             # Stick empty line before the incoming macro or rule.
8137             $spacing = "\n";
8138         }
8139         elsif (/$COMMENT_PATTERN/mso)
8140         {
8141             $is_rule = 0;
8142             # Stick comments before the incoming macro or rule.
8143             $comment = "$_\n";
8144         }
8145
8146         # Handle inclusion of other files.
8147         elsif (/$INCLUDE_PATTERN/o)
8148         {
8149             if ($cond != FALSE)
8150               {
8151                 my $file = ($is_am ? "$libdir/am/" : '') . $1;
8152                 $where->push_context ("`$file' included from here");
8153                 # N-ary `.=' fails.
8154                 my ($com, $vars, $rules)
8155                   = file_contents_internal ($is_am, $file, $where, %transform);
8156                 $where->pop_context;
8157                 $comment .= $com;
8158                 $result_vars .= $vars;
8159                 $result_rules .= $rules;
8160               }
8161         }
8162
8163         # Handling the conditionals.
8164         elsif (/$IF_PATTERN/o)
8165           {
8166             $cond = cond_stack_if ($1, $2, $file);
8167           }
8168         elsif (/$ELSE_PATTERN/o)
8169           {
8170             $cond = cond_stack_else ($1, $2, $file);
8171           }
8172         elsif (/$ENDIF_PATTERN/o)
8173           {
8174             $cond = cond_stack_endif ($1, $2, $file);
8175           }
8176
8177         # Handling rules.
8178         elsif (/$RULE_PATTERN/mso)
8179         {
8180           $is_rule = 1;
8181           $discard_rule = 0;
8182           # Separate relationship from optional actions: the first
8183           # `new-line tab" not preceded by backslash (continuation
8184           # line).
8185           my $paragraph = $_;
8186           /^(.*?)(?:(?<!\\)\n(\t.*))?$/s;
8187           my ($relationship, $actions) = ($1, $2 || '');
8188
8189           # Separate targets from dependencies: the first colon.
8190           $relationship =~ /^([^:]+\S+) *: *(.*)$/som;
8191           my ($targets, $dependencies) = ($1, $2);
8192           # Remove the escaped new lines.
8193           # I don't know why, but I have to use a tmp $flat_deps.
8194           my $flat_deps = &flatten ($dependencies);
8195           my @deps = split (' ', $flat_deps);
8196
8197           foreach (split (' ' , $targets))
8198             {
8199               # FIXME: 1. We are not robust to people defining several targets
8200               # at once, only some of them being in %dependencies.  The
8201               # actions from the targets in %dependencies are usually generated
8202               # from the content of %actions, but if some targets in $targets
8203               # are not in %dependencies the ELSE branch will output
8204               # a rule for all $targets (i.e. the targets which are both
8205               # in %dependencies and $targets will have two rules).
8206
8207               # FIXME: 2. The logic here is not able to output a
8208               # multi-paragraph rule several time (e.g. for each conditional
8209               # it is defined for) because it only knows the first paragraph.
8210
8211               # FIXME: 3. We are not robust to people defining a subset
8212               # of a previously defined "multiple-target" rule.  E.g.
8213               # `foo:' after `foo bar:'.
8214
8215               # Output only if not in FALSE.
8216               if (defined $dependencies{$_} && $cond != FALSE)
8217                 {
8218                   &depend ($_, @deps);
8219                   $actions{$_} .= $actions;
8220                 }
8221               else
8222                 {
8223                   # Free-lance dependency.  Output the rule for all the
8224                   # targets instead of one by one.
8225                   my @undefined_conds =
8226                     rule_define ($targets, $file,
8227                                  $is_am ? TARGET_AUTOMAKE : TARGET_USER,
8228                                  $cond, $where);
8229                   for my $undefined_cond (@undefined_conds)
8230                     {
8231                       my $condparagraph = $paragraph;
8232                       $condparagraph =~ s/^/$undefined_cond->subst_string/gme;
8233                       $result_rules .= "$spacing$comment$condparagraph\n";
8234                     }
8235                   if (scalar @undefined_conds == 0)
8236                     {
8237                       # Remember to discard next paragraphs
8238                       # if they belong to this rule.
8239                       # (but see also FIXME: #2 above.)
8240                       $discard_rule = 1;
8241                     }
8242                   $comment = $spacing = '';
8243                   last;
8244                 }
8245             }
8246         }
8247
8248         elsif (/$ASSIGNMENT_PATTERN/mso)
8249         {
8250             my ($var, $type, $val) = ($1, $2, $3);
8251             err $where, "variable `$var' with trailing backslash"
8252               if /\\$/;
8253
8254             $is_rule = 0;
8255
8256             # Accumulating variables must not be output.
8257             append_comments ($cond, $var, $spacing, $comment);
8258             macro_define ($var, $is_am ? VAR_AUTOMAKE : VAR_MAKEFILE,
8259                           $type, $cond, $val, $where)
8260               if $cond != FALSE;
8261             push (@var_list, $var);
8262
8263             # If the user has set some variables we were in charge
8264             # of (which is detected by the first reading of
8265             # `header-vars.am'), we must not output them.
8266             $result_vars .= "$spacing$comment$_\n"
8267               if ($cond != FALSE && $type ne '+'
8268                   && exists $var_owner{$var}{$cond}
8269                   && $var_owner{$var}{$cond} == VAR_AUTOMAKE);
8270
8271             $comment = $spacing = '';
8272         }
8273         else
8274         {
8275             # This isn't an error; it is probably some tokens which
8276             # configure is supposed to replace, such as `@SET-MAKE@',
8277             # or some part of a rule cut by an if/endif.
8278             if (! $cond->false && ! ($is_rule && $discard_rule))
8279               {
8280                 s/^/$cond->subst_string/gme;
8281                 $result_rules .= "$spacing$comment$_\n";
8282               }
8283             $comment = $spacing = '';
8284         }
8285     }
8286
8287     err ($where, @cond_stack ?
8288          "unterminated conditionals: @cond_stack" :
8289          "too many conditionals closed in include file")
8290       if "@saved_cond_stack" ne "@cond_stack";
8291
8292     return ($comment, $result_vars, $result_rules);
8293 }
8294
8295
8296 # $CONTENTS
8297 # &file_contents ($BASENAME, $WHERE, [%TRANSFORM])
8298 # ------------------------------------------------
8299 # Return contents of a file from $libdir/am, automatically skipping
8300 # macros or rules which are already known.
8301 sub file_contents ($$%)
8302 {
8303     my ($basename, $where, %transform) = @_;
8304     my ($comments, $variables, $rules) =
8305       file_contents_internal (1, "$libdir/am/$basename.am", $where,
8306                               %transform);
8307     return "$comments$variables$rules";
8308 }
8309
8310
8311 # $REGEXP
8312 # &transform (%PAIRS)
8313 # -------------------
8314 # Foreach ($TOKEN, $VAL) in %PAIRS produce a replacement expression suitable
8315 # for file_contents which:
8316 #   - replaces %$TOKEN% with $VAL,
8317 #   - enables/disables ?$TOKEN? and ?!$TOKEN?,
8318 #   - replaces %?$TOKEN% with TRUE or FALSE.
8319 sub transform (%)
8320 {
8321     my (%pairs) = @_;
8322     my $result = '';
8323
8324     while (my ($token, $val) = each %pairs)
8325     {
8326         $result .= "s/\Q%$token%\E/\Q$val\E/gm;";
8327         if ($val)
8328         {
8329             $result .= "s/\Q?$token?\E//gm;s/^.*\Q?!$token?\E.*\\n//gm;";
8330             $result .= "s/\Q%?$token%\E/TRUE/gm;";
8331         }
8332         else
8333         {
8334             $result .= "s/\Q?!$token?\E//gm;s/^.*\Q?$token?\E.*\\n//gm;";
8335             $result .= "s/\Q%?$token%\E/FALSE/gm;";
8336         }
8337     }
8338
8339     return $result;
8340 }
8341
8342
8343 # &append_exeext ($MACRO)
8344 # -----------------------
8345 # Macro is an Automake magic macro which primary is PROGRAMS, e.g.
8346 # bin_PROGRAMS.  Make sure these programs have $(EXEEXT) appended.
8347 sub append_exeext ($)
8348 {
8349   my ($macro) = @_;
8350
8351   prog_error "append_exeext ($macro)"
8352     unless $macro =~ /_PROGRAMS$/;
8353
8354   my @conds = variable_conditions_recursive ($macro);
8355
8356   my @condvals;
8357   foreach my $cond (@conds)
8358     {
8359       my @one_binlist = ();
8360       my @condval = variable_value_as_list_recursive ($macro, $cond);
8361       foreach my $rcurs (@condval)
8362         {
8363           # Skip autoconf substs.  Also skip if the user
8364           # already applied $(EXEEXT).
8365           if ($rcurs =~ /^\@.*\@$/ || $rcurs =~ /\$\(EXEEXT\)$/)
8366             {
8367               push (@one_binlist, $rcurs);
8368             }
8369           else
8370             {
8371               push (@one_binlist, $rcurs . '$(EXEEXT)');
8372             }
8373         }
8374
8375       push (@condvals, $cond);
8376       push (@condvals, "@one_binlist");
8377     }
8378
8379   # FIXME: Currently it's a bit hard to chose a condition becose the
8380   # set of input condition is different from the set of ouput
8381   # conditions.  See also PR/352.   So we just pick the first one.
8382   my $cond = (keys %{$var_value{$macro}})[0];
8383   my $where = $var_location{$macro}{$cond};
8384
8385   macro_delete ($macro);
8386   while (@condvals)
8387     {
8388       my $cond = shift (@condvals);
8389       my @val = split (' ', shift (@condvals));
8390       define_pretty_variable ($macro, $cond, $where, @val);
8391     }
8392  }
8393
8394
8395 # @PREFIX
8396 # &am_primary_prefixes ($PRIMARY, $CAN_DIST, @PREFIXES)
8397 # -----------------------------------------------------
8398 # Find all variable prefixes that are used for install directories.  A
8399 # prefix `zar' qualifies iff:
8400 #
8401 # * `zardir' is a variable.
8402 # * `zar_PRIMARY' is a variable.
8403 #
8404 # As a side effect, it looks for misspellings.  It is an error to have
8405 # a variable ending in a "reserved" suffix whose prefix is unknown, eg
8406 # "bni_PROGRAMS".  However, unusual prefixes are allowed if a variable
8407 # of the same name (with "dir" appended) exists.  For instance, if the
8408 # variable "zardir" is defined, then "zar_PROGRAMS" becomes valid.
8409 # This is to provide a little extra flexibility in those cases which
8410 # need it.
8411 sub am_primary_prefixes ($$@)
8412 {
8413   my ($primary, $can_dist, @prefixes) = @_;
8414
8415   local $_;
8416   my %valid = map { $_ => 0 } @prefixes;
8417   $valid{'EXTRA'} = 0;
8418   foreach my $varname (keys %var_value)
8419     {
8420       # Automake is allowed to define variables that look like primaries
8421       # but which aren't.  E.g. INSTALL_sh_DATA.
8422       # Autoconf can also define variables like INSTALL_DATA, so
8423       # ignore all configure variables (at least those which are not
8424       # redefined in Makefile.am).
8425       # FIXME: We should make sure that these variables are not
8426       # conditionally defined (or else adjust the condition below).
8427       next
8428         if (exists $var_owner{$varname}
8429             && exists $var_owner{$varname}{&TRUE}
8430             && $var_owner{$varname}{&TRUE} != VAR_MAKEFILE);
8431
8432       if ($varname =~ /^(nobase_)?(dist_|nodist_)?(.*)_$primary$/)
8433         {
8434           my ($base, $dist, $X) = ($1 || '', $2 || '', $3 || '');
8435           if ($dist ne '' && ! $can_dist)
8436             {
8437               err_var ($varname,
8438                        "invalid variable `$varname': `dist' is forbidden");
8439             }
8440           # Standard directories must be explicitely allowed.
8441           elsif (! defined $valid{$X} && exists $standard_prefix{$X})
8442             {
8443               err_var ($varname,
8444                        "`${X}dir' is not a legitimate directory " .
8445                        "for `$primary'");
8446             }
8447           # A not explicitely valid directory is allowed if Xdir is defined.
8448           elsif (! defined $valid{$X} &&
8449                  require_variables_for_macro ($varname, "`$varname' is used",
8450                                               "${X}dir"))
8451             {
8452               # Nothing to do.  Any error message has been output
8453               # by require_variables_for_macro.
8454             }
8455           else
8456             {
8457               # Ensure all extended prefixes are actually used.
8458               $valid{"$base$dist$X"} = 1;
8459             }
8460         }
8461     }
8462
8463   # Return only those which are actually defined.
8464   return sort grep { variable_defined ($_ . '_' . $primary) } keys %valid;
8465 }
8466
8467
8468 # Handle `where_HOW' variable magic.  Does all lookups, generates
8469 # install code, and possibly generates code to define the primary
8470 # variable.  The first argument is the name of the .am file to munge,
8471 # the second argument is the primary variable (eg HEADERS), and all
8472 # subsequent arguments are possible installation locations.
8473 #
8474 # Returns list of [$location, $value] pairs, where
8475 # $value's are the values in all where_HOW variable, and $location
8476 # there associated location (the place here their parent variables were
8477 # defined).
8478 #
8479 # FIXME: this should be rewritten to be cleaner.  It should be broken
8480 # up into multiple functions.
8481 #
8482 # Usage is: am_install_var (OPTION..., file, HOW, where...)
8483 sub am_install_var
8484 {
8485   my (@args) = @_;
8486
8487   my $do_require = 1;
8488   my $can_dist = 0;
8489   my $default_dist = 0;
8490   while (@args)
8491     {
8492       if ($args[0] eq '-noextra')
8493         {
8494           $do_require = 0;
8495         }
8496       elsif ($args[0] eq '-candist')
8497         {
8498           $can_dist = 1;
8499         }
8500       elsif ($args[0] eq '-defaultdist')
8501         {
8502           $default_dist = 1;
8503           $can_dist = 1;
8504         }
8505       elsif ($args[0] !~ /^-/)
8506         {
8507           last;
8508         }
8509       shift (@args);
8510     }
8511
8512   my ($file, $primary, @prefix) = @args;
8513
8514   # Now that configure substitutions are allowed in where_HOW
8515   # variables, it is an error to actually define the primary.  We
8516   # allow `JAVA', as it is customarily used to mean the Java
8517   # interpreter.  This is but one of several Java hacks.  Similarly,
8518   # `PYTHON' is customarily used to mean the Python interpreter.
8519   reject_var $primary, "`$primary' is an anachronism"
8520     unless $primary eq 'JAVA' || $primary eq 'PYTHON';
8521
8522   # Get the prefixes which are valid and actually used.
8523   @prefix = am_primary_prefixes ($primary, $can_dist, @prefix);
8524
8525   # If a primary includes a configure substitution, then the EXTRA_
8526   # form is required.  Otherwise we can't properly do our job.
8527   my $require_extra;
8528
8529   my @used = ();
8530   my @result = ();
8531
8532   # True if the iteration is the first one.  Used for instance to
8533   # output parts of the associated file only once.
8534   my $first = 1;
8535   foreach my $X (@prefix)
8536     {
8537       my $nodir_name = $X;
8538       my $one_name = $X . '_' . $primary;
8539
8540       my $strip_subdir = 1;
8541       # If subdir prefix should be preserved, do so.
8542       if ($nodir_name =~ /^nobase_/)
8543         {
8544           $strip_subdir = 0;
8545           $nodir_name =~ s/^nobase_//;
8546         }
8547
8548       # If files should be distributed, do so.
8549       my $dist_p = 0;
8550       if ($can_dist)
8551         {
8552           $dist_p = (($default_dist && $nodir_name !~ /^nodist_/)
8553                      || (! $default_dist && $nodir_name =~ /^dist_/));
8554           $nodir_name =~ s/^(dist|nodist)_//;
8555         }
8556
8557
8558       # Use the location of the currently processed variable.
8559       # We are not processing a particular condition, so pick the first
8560       # available.
8561       my $tmpcond = (keys %{$var_value{$one_name}})[0];
8562       my $where = $var_location{$one_name}{$tmpcond}->clone;
8563
8564       # Append actual contents of where_PRIMARY variable to
8565       # result.
8566       foreach my $locvals (&variable_loc_and_value_as_list_recursive
8567                            ($one_name, 'all'))
8568         {
8569           my ($loc, @values) = @$locvals;
8570           my @nosubst = (); # @values without substitutions.
8571           for my $rcurs (@values)
8572             {
8573               # Skip configure substitutions.  Possibly bogus.
8574               if ($rcurs =~ /^\@.*\@$/)
8575                 {
8576                   if ($nodir_name eq 'EXTRA')
8577                     {
8578                       err ($where,
8579                            "`$one_name' contains configure substitution, "
8580                            . "but shouldn't");
8581                     }
8582                   # Check here to make sure variables defined in
8583                   # configure.ac do not imply that EXTRA_PRIMARY
8584                   # must be defined.
8585                   elsif (! defined $configure_vars{$one_name})
8586                     {
8587                       $require_extra = $one_name
8588                         if $do_require;
8589                     }
8590                   next;
8591                 }
8592               push @nosubst, $rcurs;
8593             }
8594           push (@result, [$loc, @nosubst]) if @nosubst;
8595         }
8596       # A blatant hack: we rewrite each _PROGRAMS primary to include
8597       # EXEEXT.
8598       append_exeext ($one_name)
8599         if $primary eq 'PROGRAMS';
8600       # "EXTRA" shouldn't be used when generating clean targets,
8601       # all, or install targets.  We used to warn if EXTRA_FOO was
8602       # defined uselessly, but this was annoying.
8603       next
8604         if $nodir_name eq 'EXTRA';
8605
8606       if ($nodir_name eq 'check')
8607         {
8608           push (@check, '$(' . $one_name . ')');
8609         }
8610       else
8611         {
8612           push (@used, '$(' . $one_name . ')');
8613         }
8614
8615       # Is this to be installed?
8616       my $install_p = $nodir_name ne 'noinst' && $nodir_name ne 'check';
8617
8618       # If so, with install-exec? (or install-data?).
8619       my $exec_p = ($nodir_name =~ /$EXEC_DIR_PATTERN/o);
8620
8621       my $check_options_p = $install_p
8622         && defined $options{'std-options'};
8623
8624       # Use the location of the currently processed variable as context.
8625       $where->push_context ("while processing `$one_name'");
8626
8627       # Singular form of $PRIMARY.
8628       (my $one_primary = $primary) =~ s/S$//;
8629       $output_rules .= &file_contents ($file, $where,
8630                                          FIRST => $first,
8631
8632                                          PRIMARY     => $primary,
8633                                          ONE_PRIMARY => $one_primary,
8634                                          DIR         => $X,
8635                                          NDIR        => $nodir_name,
8636                                          BASE        => $strip_subdir,
8637
8638                                          EXEC      => $exec_p,
8639                                          INSTALL   => $install_p,
8640                                          DIST      => $dist_p,
8641                                          'CK-OPTS' => $check_options_p);
8642
8643       $first = 0;
8644     }
8645
8646   # The JAVA variable is used as the name of the Java interpreter.
8647   # The PYTHON variable is used as the name of the Python interpreter.
8648   if (@used && $primary ne 'JAVA' && $primary ne 'PYTHON')
8649     {
8650       # Define it.
8651       define_pretty_variable ($primary, TRUE, INTERNAL, @used);
8652       $output_vars .= "\n";
8653     }
8654
8655   err_var ($require_extra,
8656            "`$require_extra' contains configure substitution,\n"
8657            . "but `EXTRA_$primary' not defined")
8658     if ($require_extra && ! variable_defined ('EXTRA_' . $primary));
8659
8660   # Push here because PRIMARY might be configure time determined.
8661   push (@all, '$(' . $primary . ')')
8662     if @used && $primary ne 'JAVA' && $primary ne 'PYTHON';
8663
8664   # Make the result unique.  This lets the user use conditionals in
8665   # a natural way, but still lets us program lazily -- we don't have
8666   # to worry about handling a particular object more than once.
8667   # We will keep only one location per object.
8668   my %result = ();
8669   for my $pair (@result)
8670     {
8671       my ($loc, @values) = @$pair;
8672       for my $val (@values)
8673         {
8674           $result{$val} = $loc;
8675         }
8676     }
8677   my @l = sort keys %result;
8678   return map { [$result{$_}->clone, $_] } @l;
8679 }
8680
8681
8682 ################################################################
8683
8684 # Each key in this hash is the name of a directory holding a
8685 # Makefile.in.  These variables are local to `is_make_dir'.
8686 my %make_dirs = ();
8687 my $make_dirs_set = 0;
8688
8689 sub is_make_dir
8690 {
8691     my ($dir) = @_;
8692     if (! $make_dirs_set)
8693     {
8694         foreach my $iter (@configure_input_files)
8695         {
8696             $make_dirs{dirname ($iter)} = 1;
8697         }
8698         # We also want to notice Makefile.in's.
8699         foreach my $iter (@other_input_files)
8700         {
8701             if ($iter =~ /Makefile\.in$/)
8702             {
8703                 $make_dirs{dirname ($iter)} = 1;
8704             }
8705         }
8706         $make_dirs_set = 1;
8707     }
8708     return defined $make_dirs{$dir};
8709 }
8710
8711 ################################################################
8712
8713 # This variable is local to the "require file" set of functions.
8714 my @require_file_paths = ();
8715
8716
8717 # &maybe_push_required_file ($DIR, $FILE, $FULLFILE)
8718 # --------------------------------------------------
8719 # See if we want to push this file onto dist_common.  This function
8720 # encodes the rules for deciding when to do so.
8721 sub maybe_push_required_file
8722 {
8723     my ($dir, $file, $fullfile) = @_;
8724
8725     if ($dir eq $relative_dir)
8726     {
8727         push_dist_common ($file);
8728         return 1;
8729     }
8730     elsif ($relative_dir eq '.' && ! &is_make_dir ($dir))
8731     {
8732         # If we are doing the topmost directory, and the file is in a
8733         # subdir which does not have a Makefile, then we distribute it
8734         # here.
8735         push_dist_common ($fullfile);
8736         return 1;
8737     }
8738     return 0;
8739 }
8740
8741
8742 # &require_file_internal ($WHERE, $MYSTRICT, @FILES)
8743 # --------------------------------------------------
8744 # Verify that the file must exist in the current directory.
8745 # $MYSTRICT is the strictness level at which this file becomes required.
8746 #
8747 # Must set require_file_paths before calling this function.
8748 # require_file_paths is set to hold a single directory (the one in
8749 # which the first file was found) before return.
8750 sub require_file_internal ($$@)
8751 {
8752     my ($where, $mystrict, @files) = @_;
8753
8754     foreach my $file (@files)
8755     {
8756         my $fullfile;
8757         my $errdir;
8758         my $errfile;
8759         my $save_dir;
8760
8761         my $found_it = 0;
8762         my $dangling_sym = 0;
8763         foreach my $dir (@require_file_paths)
8764         {
8765             $fullfile = $dir . "/" . $file;
8766             $errdir = $dir unless $errdir;
8767
8768             # Use different name for "error filename".  Otherwise on
8769             # an error the bad file will be reported as eg
8770             # `../../install-sh' when using the default
8771             # config_aux_path.
8772             $errfile = $errdir . '/' . $file;
8773
8774             if (-l $fullfile && ! -f $fullfile)
8775             {
8776                 $dangling_sym = 1;
8777                 last;
8778             }
8779             elsif (-f $fullfile)
8780             {
8781                 $found_it = 1;
8782                 maybe_push_required_file ($dir, $file, $fullfile);
8783                 $save_dir = $dir;
8784                 last;
8785             }
8786         }
8787
8788         # `--force-missing' only has an effect if `--add-missing' is
8789         # specified.
8790         if ($found_it && (! $add_missing || ! $force_missing))
8791         {
8792             # Prune the path list.
8793             @require_file_paths = $save_dir;
8794         }
8795         else
8796         {
8797             # If we've already looked for it, we're done.  You might
8798             # wonder why we don't do this before searching for the
8799             # file.  If we do that, then something like
8800             # AC_OUTPUT(subdir/foo foo) will fail to put foo.in into
8801             # DIST_COMMON.
8802             if (! $found_it)
8803             {
8804                 next if defined $require_file_found{$fullfile};
8805                 $require_file_found{$fullfile} = 1;
8806             }
8807
8808             if ($strictness >= $mystrict)
8809             {
8810                 if ($dangling_sym && $add_missing)
8811                 {
8812                     unlink ($fullfile);
8813                 }
8814
8815                 my $trailer = '';
8816                 my $suppress = 0;
8817
8818                 # Only install missing files according to our desired
8819                 # strictness level.
8820                 my $message = "required file `$errfile' not found";
8821                 if ($add_missing)
8822                 {
8823                     $suppress = 1;
8824
8825                     if (-f ("$libdir/$file"))
8826                     {
8827                         # Install the missing file.  Symlink if we
8828                         # can, copy if we must.  Note: delete the file
8829                         # first, in case it is a dangling symlink.
8830                         $message = "installing `$errfile'";
8831                         # Windows Perl will hang if we try to delete a
8832                         # file that doesn't exist.
8833                         unlink ($errfile) if -f $errfile;
8834                         if ($symlink_exists && ! $copy_missing)
8835                         {
8836                             if (! symlink ("$libdir/$file", $errfile))
8837                             {
8838                                 $suppress = 0;
8839                                 $trailer = "; error while making link: $!";
8840                             }
8841                         }
8842                         elsif (system ('cp', "$libdir/$file", $errfile))
8843                         {
8844                             $suppress = 0;
8845                             $trailer = "\n    error while copying";
8846                         }
8847                     }
8848
8849                     if (! maybe_push_required_file (dirname ($errfile),
8850                                                     $file, $errfile))
8851                     {
8852                         if (! $found_it)
8853                         {
8854                             # We have added the file but could not push it
8855                             # into DIST_COMMON (probably because this is
8856                             # an auxiliary file and we are not processing
8857                             # the top level Makefile). This is unfortunate,
8858                             # since it means we are using a file which is not
8859                             # distributed!
8860
8861                             # Get Automake to be run again: on the second
8862                             # run the file will be found, and pushed into
8863                             # the toplevel DIST_COMMON automatically.
8864                             $automake_needs_to_reprocess_all_files = 1;
8865                         }
8866                     }
8867
8868                     # Prune the path list.
8869                     @require_file_paths = &dirname ($errfile);
8870                 }
8871
8872                 # If --force-missing was specified, and we have
8873                 # actually found the file, then do nothing.
8874                 next
8875                     if $found_it && $force_missing;
8876
8877                 msg ($suppress ? 'note' : 'error', $where, "$message$trailer");
8878             }
8879         }
8880     }
8881 }
8882
8883 # &require_file ($WHERE, $MYSTRICT, @FILES)
8884 # -----------------------------------------
8885 sub require_file ($$@)
8886 {
8887     my ($where, $mystrict, @files) = @_;
8888     @require_file_paths = $relative_dir;
8889     require_file_internal ($where, $mystrict, @files);
8890 }
8891
8892 # &require_file_with_macro ($COND, $MACRO, $MYSTRICT, @FILES)
8893 # -----------------------------------------------------------
8894 sub require_file_with_macro ($$$@)
8895 {
8896     my ($cond, $macro, $mystrict, @files) = @_;
8897     require_file ($var_location{$macro}{$cond}, $mystrict, @files);
8898 }
8899
8900
8901 # &require_conf_file ($WHERE, $MYSTRICT, @FILES)
8902 # ----------------------------------------------
8903 # Looks in configuration path, as specified by AC_CONFIG_AUX_DIR.
8904 sub require_conf_file ($$@)
8905 {
8906     my ($where, $mystrict, @files) = @_;
8907     @require_file_paths = @config_aux_path;
8908     require_file_internal ($where, $mystrict, @files);
8909     my $dir = $require_file_paths[0];
8910     @config_aux_path = @require_file_paths;
8911      # Avoid unsightly '/.'s.
8912     $config_aux_dir = '$(top_srcdir)' . ($dir eq '.' ? "" : "/$dir");
8913 }
8914
8915
8916 # &require_conf_file_with_macro ($COND, $MACRO, $MYSTRICT, @FILES)
8917 # ----------------------------------------------------------------
8918 sub require_conf_file_with_macro ($$$@)
8919 {
8920     my ($cond, $macro, $mystrict, @files) = @_;
8921     require_conf_file ($var_location{$macro}{$cond}, $mystrict, @files);
8922 }
8923
8924 ################################################################
8925
8926 # &require_build_directory ($DIRECTORY)
8927 # ------------------------------------
8928 # Emit rules to create $DIRECTORY if needed, and return
8929 # the file that any target requiring this directory should be made
8930 # dependent upon.
8931 sub require_build_directory ($)
8932 {
8933     my $directory = shift;
8934     my $dirstamp = "$directory/.dirstamp";
8935
8936     # Don't emit the rule twice.
8937     if (! defined $directory_map{$directory})
8938     {
8939         $directory_map{$directory} = 1;
8940
8941         # Directory must be removed by `make distclean'.
8942         $clean_files{$dirstamp} = DIST_CLEAN;
8943
8944         $output_rules .= ("$dirstamp:\n"
8945                           . "\t\@\$(mkinstalldirs) $directory\n"
8946                           . "\t\@: > $dirstamp\n");
8947     }
8948
8949     return $dirstamp;
8950 }
8951
8952 # &require_build_directory_maybe ($FILE)
8953 # --------------------------------------
8954 # If $FILE lies in a subdirectory, emit a rule to create this
8955 # directory and return the file that $FILE should be made
8956 # dependent upon.  Otherwise, just return the empty string.
8957 sub require_build_directory_maybe ($)
8958 {
8959     my $file = shift;
8960     my $directory = dirname ($file);
8961
8962     if ($directory ne '.')
8963     {
8964         return require_build_directory ($directory);
8965     }
8966     else
8967     {
8968         return '';
8969     }
8970 }
8971
8972 ################################################################
8973
8974 # Push a list of files onto dist_common.
8975 sub push_dist_common
8976 {
8977   prog_error "push_dist_common run after handle_dist"
8978     if $handle_dist_run;
8979   macro_define ('DIST_COMMON', VAR_AUTOMAKE, '+', TRUE, "@_", INTERNAL);
8980 }
8981
8982
8983 # Set strictness.
8984 sub set_strictness
8985 {
8986   $strictness_name = $_[0];
8987
8988   # FIXME: 'portability' warnings are currently disabled by default.
8989   # Eventually we want to turn them on in GNU and GNITS modes, but
8990   # we don't do this yet in Automake 1.7 to help the 1.6/1.7 transition.
8991   #
8992   # Indeed there would be only two ways to get rid of these new warnings:
8993   #  1. adjusting Makefile.am
8994   #     This is not always easy (or wanted).  Consider %-rules or
8995   #     $(function args) variables.
8996   #  2. using -Wno-portability
8997   #     This means there is no way to have the same Makefile.am
8998   #     working both with Automake 1.6 and 1.7 (since 1.6 does not
8999   #     understand -Wno-portability).
9000   #
9001   # In Automake 1.8 (or whatever it is called) we can turn these
9002   # warnings on, since -Wno-portability will not be an issue for
9003   # the 1.7/1.8 transition.
9004   if ($strictness_name eq 'gnu')
9005     {
9006       $strictness = GNU;
9007       setup_channel 'error-gnu', silent => 0;
9008       setup_channel 'error-gnu/warn', silent => 0, type => 'error';
9009       setup_channel 'error-gnits', silent => 1;
9010       # setup_channel 'portability', silent => 0;
9011       setup_channel 'gnu', silent => 0;
9012     }
9013   elsif ($strictness_name eq 'gnits')
9014     {
9015       $strictness = GNITS;
9016       setup_channel 'error-gnu', silent => 0;
9017       setup_channel 'error-gnu/warn', silent => 0, type => 'error';
9018       setup_channel 'error-gnits', silent => 0;
9019       # setup_channel 'portability', silent => 0;
9020       setup_channel 'gnu', silent => 0;
9021     }
9022   elsif ($strictness_name eq 'foreign')
9023     {
9024       $strictness = FOREIGN;
9025       setup_channel 'error-gnu', silent => 1;
9026       setup_channel 'error-gnu/warn', silent => 0, type => 'warning';
9027       setup_channel 'error-gnits', silent => 1;
9028       # setup_channel 'portability', silent => 1;
9029       setup_channel 'gnu', silent => 1;
9030     }
9031   else
9032     {
9033       prog_error "level `$strictness_name' not recognized\n";
9034     }
9035 }
9036
9037
9038 ################################################################
9039
9040 # Glob something.  Do this to avoid indentation screwups everywhere we
9041 # want to glob.  Gross!
9042 sub my_glob
9043 {
9044     my ($pat) = @_;
9045     return <${pat}>;
9046 }
9047
9048 ################################################################
9049
9050 # INTEGER
9051 # require_variables ($WHERE, $REASON, $COND, @VARIABLES)
9052 # ------------------------------------------------------
9053 # Make sure that each supplied variable is defined in $COND.
9054 # Otherwise, issue a warning.  If we know which macro can
9055 # define this variable, hint the user.
9056 # Return the number of undefined variables.
9057 sub require_variables ($$$@)
9058 {
9059   my ($where, $reason, $cond, @vars) = @_;
9060   my $res = 0;
9061   $reason .= ' but ' unless $reason eq '';
9062
9063  VARIABLE:
9064   foreach my $var (@vars)
9065     {
9066       # Nothing to do if the variable exists.  The $configure_vars test
9067       # needed for strange variables like AMDEPBACKSLASH or ANSI2KNR
9068       # that are AC_SUBST'ed but never macro_define'd.
9069       next VARIABLE
9070         if ((exists $var_value{$var} && exists $var_value{$var}{$cond})
9071             || exists $configure_vars{$var});
9072
9073       my @undef_cond = variable_not_always_defined_in_cond $var, $cond;
9074       next VARIABLE
9075         unless @undef_cond;
9076
9077       my $text = "$reason`$var' is undefined\n";
9078       if (@undef_cond && $undef_cond[0] != TRUE)
9079         {
9080           $text .= ("in the following conditions:\n  "
9081                     . join ("\n  ", map { $_->string } @undef_cond));
9082         }
9083
9084       ++$res;
9085
9086       if (exists $am_macro_for_var{$var})
9087         {
9088           $text .= "\nThe usual way to define `$var' is to add "
9089             . "`$am_macro_for_var{$var}'\nto `$configure_ac' and run "
9090             . "`aclocal' and `autoconf' again.";
9091         }
9092       elsif (exists $ac_macro_for_var{$var})
9093         {
9094           $text .= "\nThe usual way to define `$var' is to add "
9095             . "`$ac_macro_for_var{$var}'\nto `$configure_ac' and run "
9096             . "`autoconf' again.";
9097         }
9098
9099       err $where, $text, uniq_scope => US_GLOBAL;
9100     }
9101   return $res;
9102 }
9103
9104 # INTEGER
9105 # require_variables_for_macro ($MACRO, $REASON, @VARIABLES)
9106 # ---------------------------------------------------------
9107 # Same as require_variables, but take a macro mame as first argument.
9108 sub require_variables_for_macro ($$@)
9109 {
9110   my ($macro, $reason, @args) = @_;
9111   for my $cond (keys %{$var_value{$macro}})
9112     {
9113       return require_variables ($var_location{$macro}{$cond}, $reason,
9114                                 $cond, @args);
9115     }
9116 }
9117
9118 # Print usage information.
9119 sub usage ()
9120 {
9121     print "Usage: $0 [OPTION] ... [Makefile]...
9122
9123 Generate Makefile.in for configure from Makefile.am.
9124
9125 Operation modes:
9126       --help               print this help, then exit
9127       --version            print version number, then exit
9128   -v, --verbose            verbosely list files processed
9129       --no-force           only update Makefile.in's that are out of date
9130   -W, --warnings=CATEGORY  report the warnings falling in CATEGORY
9131
9132 Dependency tracking:
9133   -i, --ignore-deps      disable dependency tracking code
9134       --include-deps     enable dependency tracking code
9135
9136 Flavors:
9137       --cygnus           assume program is part of Cygnus-style tree
9138       --foreign          set strictness to foreign
9139       --gnits            set strictness to gnits
9140       --gnu              set strictness to gnu
9141
9142 Library files:
9143   -a, --add-missing      add missing standard files to package
9144       --libdir=DIR       directory storing library files
9145   -c, --copy             with -a, copy missing files (default is symlink)
9146   -f, --force-missing    force update of standard files
9147
9148 Warning categories include:
9149   `gnu'           GNU coding standards (default in gnu and gnits modes)
9150   `obsolete'      obsolete features or constructions
9151   `portability'   portability issues
9152   `syntax'        dubious syntactic constructs (default)
9153   `unsupported'   unsupported or incomplete features (default)
9154   `all'           all the warnings
9155   `no-CATEGORY'   turn off warnings in CATEGORY
9156   `none'          turn off all the warnings
9157   `error'         treat warnings as errors
9158 ";
9159
9160     my ($last, @lcomm);
9161     $last = '';
9162     foreach my $iter (sort ((@common_files, @common_sometimes)))
9163     {
9164         push (@lcomm, $iter) unless $iter eq $last;
9165         $last = $iter;
9166     }
9167
9168     my @four;
9169     print "\nFiles which are automatically distributed, if found:\n";
9170     format USAGE_FORMAT =
9171   @<<<<<<<<<<<<<<<<   @<<<<<<<<<<<<<<<<   @<<<<<<<<<<<<<<<<   @<<<<<<<<<<<<<<<<
9172   $four[0],           $four[1],           $four[2],           $four[3]
9173 .
9174     $~ = "USAGE_FORMAT";
9175
9176     my $cols = 4;
9177     my $rows = int(@lcomm / $cols);
9178     my $rest = @lcomm % $cols;
9179
9180     if ($rest)
9181     {
9182         $rows++;
9183     }
9184     else
9185     {
9186         $rest = $cols;
9187     }
9188
9189     for (my $y = 0; $y < $rows; $y++)
9190     {
9191         @four = ("", "", "", "");
9192         for (my $x = 0; $x < $cols; $x++)
9193         {
9194             last if $y + 1 == $rows && $x == $rest;
9195
9196             my $idx = (($x > $rest)
9197                        ?  ($rows * $rest + ($rows - 1) * ($x - $rest))
9198                        : ($rows * $x));
9199
9200             $idx += $y;
9201             $four[$x] = $lcomm[$idx];
9202         }
9203         write;
9204     }
9205
9206     print "\nReport bugs to <bug-automake\@gnu.org>.\n";
9207
9208     # --help always returns 0 per GNU standards.
9209     exit 0;
9210 }
9211
9212
9213 # &version ()
9214 # -----------
9215 # Print version information
9216 sub version ()
9217 {
9218   print <<EOF;
9219 automake (GNU $PACKAGE) $VERSION
9220 Written by Tom Tromey <tromey\@redhat.com>.
9221
9222 Copyright 2002 Free Software Foundation, Inc.
9223 This is free software; see the source for copying conditions.  There is NO
9224 warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
9225 EOF
9226   # --version always returns 0 per GNU standards.
9227   exit 0;
9228 }
9229
9230 ### Setup "GNU" style for perl-mode and cperl-mode.
9231 ## Local Variables:
9232 ## perl-indent-level: 2
9233 ## perl-continued-statement-offset: 2
9234 ## perl-continued-brace-offset: 0
9235 ## perl-brace-offset: 0
9236 ## perl-brace-imaginary-offset: 0
9237 ## perl-label-offset: -2
9238 ## cperl-indent-level: 2
9239 ## cperl-brace-offset: 0
9240 ## cperl-continued-brace-offset: 0
9241 ## cperl-label-offset: -2
9242 ## cperl-extra-newline-before-brace: t
9243 ## cperl-merge-trailing-else: nil
9244 ## cperl-continued-statement-offset: 2
9245 ## End: