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