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