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