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