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