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