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