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       my $soutdir = '$(srcdir)/' . $outdir;
3221
3222       if (option 'info-in-builddir')
3223         {
3224           $insrc = 0;
3225         }
3226       elsif ($out_file =~ $user_cleaned_files)
3227         {
3228           $insrc = 0;
3229           msg 'obsolete', "$am_file.am", <<EOF;
3230 Oops!
3231     It appears this file (or files included by it) are triggering
3232     an undocumented, soon-to-be-removed automake hack.
3233     Future automake versions will no longer place in the builddir
3234     (rather than in the srcdir) the generated '.info' files that
3235     appear to be cleaned, by e.g. being listed in CLEANFILES or
3236     DISTCLEANFILES.
3237     If you want your '.info' files to be placed in the builddir
3238     rather than in the srcdir, you have to use the shiny new
3239     'info-in-builddir' automake option.
3240 EOF
3241         }
3242
3243       $outdir = $soutdir if $insrc;
3244
3245       # If user specified file_TEXINFOS, then use that as explicit
3246       # dependency list.
3247       @texi_deps = ();
3248       push (@texi_deps, "${soutdir}${vtexi}") if $vtexi;
3249
3250       my $canonical = canonicalize ($infobase);
3251       if (var ($canonical . "_TEXINFOS"))
3252         {
3253           push (@texi_deps, '$(' . $canonical . '_TEXINFOS)');
3254           push_dist_common ('$(' . $canonical . '_TEXINFOS)');
3255         }
3256
3257       my ($dirstamp, @cfiles) =
3258         output_texinfo_build_rules ($texi, $out_file, $insrc, @texi_deps);
3259       push (@texi_cleans, @cfiles);
3260
3261       push (@info_deps_list, $out_file);
3262
3263       # If a vers*.texi file is needed, emit the rule.
3264       if ($vtexi)
3265         {
3266           err_am ("'$vtexi', included in '$texi', "
3267                   . "also included in '$versions{$vtexi}'")
3268             if defined $versions{$vtexi};
3269           $versions{$vtexi} = $texi;
3270
3271           # We number the stamp-vti files.  This is doable since the
3272           # actual names don't matter much.  We only number starting
3273           # with the second one, so that the common case looks nice.
3274           my $vti = ($done ? $done : 'vti');
3275           ++$done;
3276
3277           # This is ugly, but it is our historical practice.
3278           if ($config_aux_dir_set_in_configure_ac)
3279             {
3280               require_conf_file_with_macro (TRUE, 'info_TEXINFOS', FOREIGN,
3281                                             'mdate-sh');
3282             }
3283           else
3284             {
3285               require_file_with_macro (TRUE, 'info_TEXINFOS',
3286                                        FOREIGN, 'mdate-sh');
3287             }
3288
3289           my $conf_dir;
3290           if ($config_aux_dir_set_in_configure_ac)
3291             {
3292               $conf_dir = "$am_config_aux_dir/";
3293             }
3294           else
3295             {
3296               $conf_dir = '$(srcdir)/';
3297             }
3298           $output_rules .= file_contents ('texi-vers',
3299                                           new Automake::Location,
3300                                           TEXI     => $texi,
3301                                           VTI      => $vti,
3302                                           STAMPVTI => "${soutdir}stamp-$vti",
3303                                           VTEXI    => "$soutdir$vtexi",
3304                                           MDDIR    => $conf_dir,
3305                                           DIRSTAMP => $dirstamp);
3306         }
3307     }
3308
3309   # Handle location of texinfo.tex.
3310   my $need_texi_file = 0;
3311   my $texinfodir;
3312   if (var ('TEXINFO_TEX'))
3313     {
3314       # The user defined TEXINFO_TEX so assume he knows what he is
3315       # doing.
3316       $texinfodir = ('$(srcdir)/'
3317                      . dirname (variable_value ('TEXINFO_TEX')));
3318     }
3319   elsif ($config_aux_dir_set_in_configure_ac)
3320     {
3321       $texinfodir = $am_config_aux_dir;
3322       define_variable ('TEXINFO_TEX', "$texinfodir/texinfo.tex", INTERNAL);
3323       $need_texi_file = 2; # so that we require_conf_file later
3324     }
3325   else
3326     {
3327       $texinfodir = '$(srcdir)';
3328       $need_texi_file = 1;
3329     }
3330   define_variable ('am__TEXINFO_TEX_DIR', $texinfodir, INTERNAL);
3331
3332   push (@dist_targets, 'dist-info');
3333
3334   if (! option 'no-installinfo')
3335     {
3336       # Make sure documentation is made and installed first.  Use
3337       # $(INFO_DEPS), not 'info', because otherwise recursive makes
3338       # get run twice during "make all".
3339       unshift (@all, '$(INFO_DEPS)');
3340     }
3341
3342   define_files_variable ("DVIS", @infobase, 'dvi', INTERNAL);
3343   define_files_variable ("PDFS", @infobase, 'pdf', INTERNAL);
3344   define_files_variable ("PSS", @infobase, 'ps', INTERNAL);
3345   define_files_variable ("HTMLS", @infobase, 'html', INTERNAL);
3346
3347   # This next isn't strictly needed now -- the places that look here
3348   # could easily be changed to look in info_TEXINFOS.  But this is
3349   # probably better, in case noinst_TEXINFOS is ever supported.
3350   define_variable ("TEXINFOS", variable_value ('info_TEXINFOS'), INTERNAL);
3351
3352   # Do some error checking.  Note that this file is not required
3353   # when in Cygnus mode; instead we defined TEXINFO_TEX explicitly
3354   # up above.
3355   if ($need_texi_file && ! option 'no-texinfo.tex')
3356     {
3357       if ($need_texi_file > 1)
3358         {
3359           require_conf_file_with_macro (TRUE, 'info_TEXINFOS', FOREIGN,
3360                                         'texinfo.tex');
3361         }
3362       else
3363         {
3364           require_file_with_macro (TRUE, 'info_TEXINFOS', FOREIGN,
3365                                    'texinfo.tex');
3366         }
3367     }
3368
3369   return (makefile_wrap ("", "\t  ", @mostly_cleans),
3370           makefile_wrap ("", "\t  ", @texi_cleans),
3371           makefile_wrap ("", "\t  ", @maint_cleans));
3372 }
3373
3374
3375 sub handle_texinfo ()
3376 {
3377   reject_var 'TEXINFOS', "'TEXINFOS' is an anachronism; use 'info_TEXINFOS'";
3378   # FIXME: I think this is an obsolete future feature name.
3379   reject_var 'html_TEXINFOS', "HTML generation not yet supported";
3380
3381   my $info_texinfos = var ('info_TEXINFOS');
3382   my ($mostlyclean, $clean, $maintclean) = ('', '', '');
3383   if ($info_texinfos)
3384     {
3385       define_verbose_texinfo;
3386       ($mostlyclean, $clean, $maintclean) = handle_texinfo_helper ($info_texinfos);
3387       chomp $mostlyclean;
3388       chomp $clean;
3389       chomp $maintclean;
3390     }
3391
3392   $output_rules .=  file_contents ('texinfos',
3393                                    new Automake::Location,
3394                                    AM_V_DVIPS    => verbose_flag('DVIPS'),
3395                                    MOSTLYCLEAN   => $mostlyclean,
3396                                    TEXICLEAN     => $clean,
3397                                    MAINTCLEAN    => $maintclean,
3398                                    'LOCAL-TEXIS' => !!$info_texinfos,
3399                                    TEXIQUIET     => verbose_flag('texinfo'));
3400 }
3401
3402
3403 sub handle_man_pages ()
3404 {
3405   reject_var 'MANS', "'MANS' is an anachronism; use 'man_MANS'";
3406
3407   # Find all the sections in use.  We do this by first looking for
3408   # "standard" sections, and then looking for any additional
3409   # sections used in man_MANS.
3410   my (%sections, %notrans_sections, %trans_sections,
3411       %notrans_vars, %trans_vars, %notrans_sect_vars, %trans_sect_vars);
3412   # We handle nodist_ for uniformity.  man pages aren't distributed
3413   # by default so it isn't actually very important.
3414   foreach my $npfx ('', 'notrans_')
3415     {
3416       foreach my $pfx ('', 'dist_', 'nodist_')
3417         {
3418           # Add more sections as needed.
3419           foreach my $section ('0'..'9', 'n', 'l')
3420             {
3421               my $varname = $npfx . $pfx . 'man' . $section . '_MANS';
3422               if (var ($varname))
3423                 {
3424                   $sections{$section} = 1;
3425                   $varname = '$(' . $varname . ')';
3426                   if ($npfx eq 'notrans_')
3427                     {
3428                       $notrans_sections{$section} = 1;
3429                       $notrans_sect_vars{$varname} = 1;
3430                     }
3431                   else
3432                     {
3433                       $trans_sections{$section} = 1;
3434                       $trans_sect_vars{$varname} = 1;
3435                     }
3436
3437                   push_dist_common ($varname)
3438                     if $pfx eq 'dist_';
3439                 }
3440             }
3441
3442           my $varname = $npfx . $pfx . 'man_MANS';
3443           my $var = var ($varname);
3444           if ($var)
3445             {
3446               foreach ($var->value_as_list_recursive)
3447                 {
3448                   # A page like 'foo.1c' goes into man1dir.
3449                   if (/\.([0-9a-z])([a-z]*)$/)
3450                     {
3451                       $sections{$1} = 1;
3452                       if ($npfx eq 'notrans_')
3453                         {
3454                           $notrans_sections{$1} = 1;
3455                         }
3456                       else
3457                         {
3458                           $trans_sections{$1} = 1;
3459                         }
3460                     }
3461                 }
3462
3463               $varname = '$(' . $varname . ')';
3464               if ($npfx eq 'notrans_')
3465                 {
3466                   $notrans_vars{$varname} = 1;
3467                 }
3468               else
3469                 {
3470                   $trans_vars{$varname} = 1;
3471                 }
3472               push_dist_common ($varname)
3473                 if $pfx eq 'dist_';
3474             }
3475         }
3476     }
3477
3478   return unless %sections;
3479
3480   my @unsorted_deps;
3481
3482   # Build section independent variables.
3483   my $have_notrans = %notrans_vars;
3484   my @notrans_list = sort keys %notrans_vars;
3485   my $have_trans = %trans_vars;
3486   my @trans_list = sort keys %trans_vars;
3487
3488   # Now for each section, generate an install and uninstall rule.
3489   # Sort sections so output is deterministic.
3490   foreach my $section (sort keys %sections)
3491     {
3492       # Build section dependent variables.
3493       my $notrans_mans = $have_notrans || exists $notrans_sections{$section};
3494       my $trans_mans = $have_trans || exists $trans_sections{$section};
3495       my (%notrans_this_sect, %trans_this_sect);
3496       my $expr = 'man' . $section . '_MANS';
3497       foreach my $varname (keys %notrans_sect_vars)
3498         {
3499           if ($varname =~ /$expr/)
3500             {
3501               $notrans_this_sect{$varname} = 1;
3502             }
3503         }
3504       foreach my $varname (keys %trans_sect_vars)
3505         {
3506           if ($varname =~ /$expr/)
3507             {
3508               $trans_this_sect{$varname} = 1;
3509             }
3510         }
3511       my @notrans_sect_list = sort keys %notrans_this_sect;
3512       my @trans_sect_list = sort keys %trans_this_sect;
3513       @unsorted_deps = (keys %notrans_vars, keys %trans_vars,
3514                         keys %notrans_this_sect, keys %trans_this_sect);
3515       my @deps = sort @unsorted_deps;
3516       $output_rules .= file_contents ('mans',
3517                                       new Automake::Location,
3518                                       SECTION           => $section,
3519                                       DEPS              => "@deps",
3520                                       NOTRANS_MANS      => $notrans_mans,
3521                                       NOTRANS_SECT_LIST => "@notrans_sect_list",
3522                                       HAVE_NOTRANS      => $have_notrans,
3523                                       NOTRANS_LIST      => "@notrans_list",
3524                                       TRANS_MANS        => $trans_mans,
3525                                       TRANS_SECT_LIST   => "@trans_sect_list",
3526                                       HAVE_TRANS        => $have_trans,
3527                                       TRANS_LIST        => "@trans_list");
3528     }
3529
3530   @unsorted_deps  = (keys %notrans_vars, keys %trans_vars,
3531                      keys %notrans_sect_vars, keys %trans_sect_vars);
3532   my @mans = sort @unsorted_deps;
3533   $output_vars .= file_contents ('mans-vars',
3534                                  new Automake::Location,
3535                                  MANS => "@mans");
3536
3537   push (@all, '$(MANS)')
3538     unless option 'no-installman';
3539 }
3540
3541
3542 sub handle_data ()
3543 {
3544     am_install_var ('-noextra', '-candist', 'data', 'DATA',
3545                     'data', 'dataroot', 'doc', 'dvi', 'html', 'pdf',
3546                     'ps', 'sysconf', 'sharedstate', 'localstate',
3547                     'pkgdata', 'lisp', 'noinst', 'check');
3548 }
3549
3550
3551 sub handle_tags ()
3552 {
3553     my @config;
3554     foreach my $spec (@config_headers)
3555       {
3556         my ($out, @ins) = split_config_file_spec ($spec);
3557         foreach my $in (@ins)
3558           {
3559             # If the config header source is in this directory,
3560             # require it.
3561             push @config, basename ($in)
3562               if $relative_dir eq dirname ($in);
3563            }
3564       }
3565
3566     define_variable ('am__tagged_files',
3567                      '$(HEADERS) $(SOURCES) $(TAGS_FILES) $(LISP)'
3568                      . "@config", INTERNAL);
3569
3570     if (rvar('am__tagged_files')->value_as_list_recursive
3571           || var ('ETAGS_ARGS') || var ('SUBDIRS'))
3572       {
3573         $output_rules .= file_contents ('tags', new Automake::Location);
3574         set_seen 'TAGS_DEPENDENCIES';
3575       }
3576     else
3577       {
3578         reject_var ('TAGS_DEPENDENCIES',
3579                     "it doesn't make sense to define 'TAGS_DEPENDENCIES'"
3580                     . " without\nsources or 'ETAGS_ARGS'");
3581         # Every Makefile must define some sort of TAGS rule.
3582         # Otherwise, it would be possible for a top-level "make TAGS"
3583         # to fail because some subdirectory failed.  Ditto ctags and
3584         # cscope.
3585         $output_rules .=
3586           "tags TAGS:\n\n" .
3587           "ctags CTAGS:\n\n" .
3588           "cscope cscopelist:\n\n";
3589       }
3590 }
3591
3592
3593 # user_phony_rule ($NAME)
3594 # -----------------------
3595 # Return false if rule $NAME does not exist.  Otherwise,
3596 # declare it as phony, complete its definition (in case it is
3597 # conditional), and return its Automake::Rule instance.
3598 sub user_phony_rule
3599 {
3600   my ($name) = @_;
3601   my $rule = rule $name;
3602   if ($rule)
3603     {
3604       depend ('.PHONY', $name);
3605       # Define $NAME in all condition where it is not already defined,
3606       # so that it is always OK to depend on $NAME.
3607       for my $c ($rule->not_always_defined_in_cond (TRUE)->conds)
3608         {
3609           Automake::Rule::define ($name, 'internal', RULE_AUTOMAKE,
3610                                   $c, INTERNAL);
3611           $output_rules .= $c->subst_string . "$name:\n";
3612         }
3613     }
3614   return $rule;
3615 }
3616
3617
3618 # Handle 'dist' target.
3619 sub handle_dist ()
3620 {
3621   # Substitutions for distdir.am
3622   my %transform;
3623
3624   # Define DIST_SUBDIRS.  This must always be done, regardless of the
3625   # no-dist setting: target like 'distclean' or 'maintainer-clean' use it.
3626   my $subdirs = var ('SUBDIRS');
3627   if ($subdirs)
3628     {
3629       # If SUBDIRS is conditionally defined, then set DIST_SUBDIRS
3630       # to all possible directories, and use it.  If DIST_SUBDIRS is
3631       # defined, just use it.
3632
3633       # Note that we check DIST_SUBDIRS first on purpose, so that
3634       # we don't call has_conditional_contents for now reason.
3635       # (In the past one project used so many conditional subdirectories
3636       # that calling has_conditional_contents on SUBDIRS caused
3637       # automake to grow to 150Mb -- this should not happen with
3638       # the current implementation of has_conditional_contents,
3639       # but it's more efficient to avoid the call anyway.)
3640       if (var ('DIST_SUBDIRS'))
3641         {
3642         }
3643       elsif ($subdirs->has_conditional_contents)
3644         {
3645           define_pretty_variable
3646             ('DIST_SUBDIRS', TRUE, INTERNAL,
3647              uniq ($subdirs->value_as_list_recursive));
3648         }
3649       else
3650         {
3651           # We always define this because that is what 'distclean'
3652           # wants.
3653           define_pretty_variable ('DIST_SUBDIRS', TRUE, INTERNAL,
3654                                   '$(SUBDIRS)');
3655         }
3656     }
3657
3658   # The remaining definitions are only required when a dist target is used.
3659   return if option 'no-dist';
3660
3661   # At least one of the archive formats must be enabled.
3662   if ($relative_dir eq '.')
3663     {
3664       my $archive_defined = option 'no-dist-gzip' ? 0 : 1;
3665       $archive_defined ||=
3666         grep { option "dist-$_" } qw(shar zip tarZ bzip2 lzip xz);
3667       error (option 'no-dist-gzip',
3668              "no-dist-gzip specified but no dist-* specified,\n"
3669              . "at least one archive format must be enabled")
3670         unless $archive_defined;
3671     }
3672
3673   # Look for common files that should be included in distribution.
3674   # If the aux dir is set, and it does not have a Makefile.am, then
3675   # we check for these files there as well.
3676   my $check_aux = 0;
3677   if ($relative_dir eq '.'
3678       && $config_aux_dir_set_in_configure_ac)
3679     {
3680       if (! is_make_dir ($config_aux_dir))
3681         {
3682           $check_aux = 1;
3683         }
3684     }
3685   foreach my $cfile (@common_files)
3686     {
3687       if (dir_has_case_matching_file ($relative_dir, $cfile)
3688           # The file might be absent, but if it can be built it's ok.
3689           || rule $cfile)
3690         {
3691           push_dist_common ($cfile);
3692         }
3693
3694       # Don't use 'elsif' here because a file might meaningfully
3695       # appear in both directories.
3696       if ($check_aux && dir_has_case_matching_file ($config_aux_dir, $cfile))
3697         {
3698           push_dist_common ("$config_aux_dir/$cfile")
3699         }
3700     }
3701
3702   # We might copy elements from $configure_dist_common to
3703   # %dist_common if we think we need to.  If the file appears in our
3704   # directory, we would have discovered it already, so we don't
3705   # check that.  But if the file is in a subdir without a Makefile,
3706   # we want to distribute it here if we are doing '.'.  Ugly!
3707   # Also, in some corner cases, it's possible that the following code
3708   # will cause the same file to appear in the $(DIST_COMMON) variables
3709   # of two distinct Makefiles; but this is not a problem, since the
3710   # 'distdir' target in 'lib/am/distdir.am' can deal with the same
3711   # file being distributed multiple times.
3712   # See also automake bug#9651.
3713   if ($relative_dir eq '.')
3714     {
3715       foreach my $file (split (' ' , $configure_dist_common))
3716         {
3717           my $dir = dirname ($file);
3718           push_dist_common ($file)
3719             if ($dir eq '.' || ! is_make_dir ($dir));
3720         }
3721     }
3722
3723   # Files to distributed.  Don't use ->value_as_list_recursive
3724   # as it recursively expands '$(dist_pkgdata_DATA)' etc.
3725   my @dist_common = split (' ', rvar ('DIST_COMMON')->variable_value);
3726   @dist_common = uniq (@dist_common);
3727   variable_delete 'DIST_COMMON';
3728   define_pretty_variable ('DIST_COMMON', TRUE, INTERNAL, @dist_common);
3729
3730   # Now that we've processed DIST_COMMON, disallow further attempts
3731   # to set it.
3732   $handle_dist_run = 1;
3733
3734   $transform{'DISTCHECK-HOOK'} = !! rule 'distcheck-hook';
3735   $transform{'GETTEXT'} = $seen_gettext && !$seen_gettext_external;
3736
3737   # If the target 'dist-hook' exists, make sure it is run.  This
3738   # allows users to do random weird things to the distribution
3739   # before it is packaged up.
3740   push (@dist_targets, 'dist-hook')
3741     if user_phony_rule 'dist-hook';
3742   $transform{'DIST-TARGETS'} = join (' ', @dist_targets);
3743
3744   my $flm = option ('filename-length-max');
3745   my $filename_filter = $flm ? '.' x $flm->[1] : '';
3746
3747   $output_rules .= file_contents ('distdir',
3748                                   new Automake::Location,
3749                                   %transform,
3750                                   FILENAME_FILTER => $filename_filter);
3751 }
3752
3753
3754 # check_directory ($NAME, $WHERE [, $RELATIVE_DIR = "."])
3755 # -------------------------------------------------------
3756 # Ensure $NAME is a directory (in $RELATIVE_DIR), and that it uses a sane
3757 # name.  Use $WHERE as a location in the diagnostic, if any.
3758 sub check_directory
3759 {
3760   my ($dir, $where, $reldir) = @_;
3761   $reldir = '.' unless defined $reldir;
3762
3763   error $where, "required directory $reldir/$dir does not exist"
3764     unless -d "$reldir/$dir";
3765
3766   # If an 'obj/' directory exists, BSD make will enter it before
3767   # reading 'Makefile'.  Hence the 'Makefile' in the current directory
3768   # will not be read.
3769   #
3770   #  % cat Makefile
3771   #  all:
3772   #          echo Hello
3773   #  % cat obj/Makefile
3774   #  all:
3775   #          echo World
3776   #  % make      # GNU make
3777   #  echo Hello
3778   #  Hello
3779   #  % pmake     # BSD make
3780   #  echo World
3781   #  World
3782   msg ('portability', $where,
3783        "naming a subdirectory 'obj' causes troubles with BSD make")
3784     if $dir eq 'obj';
3785
3786   # 'aux' is probably the most important of the following forbidden name,
3787   # since it's tempting to use it as an AC_CONFIG_AUX_DIR.
3788   msg ('portability', $where,
3789        "name '$dir' is reserved on W32 and DOS platforms")
3790     if grep (/^\Q$dir\E$/i, qw/aux lpt1 lpt2 lpt3 com1 com2 com3 com4 con prn/);
3791 }
3792
3793 # check_directories_in_var ($VARIABLE)
3794 # ------------------------------------
3795 # Recursively check all items in variables $VARIABLE as directories
3796 sub check_directories_in_var
3797 {
3798   my ($var) = @_;
3799   $var->traverse_recursively
3800     (sub
3801      {
3802        my ($var, $val, $cond, $full_cond) = @_;
3803        check_directory ($val, $var->rdef ($cond)->location, $relative_dir);
3804        return ();
3805      },
3806      undef,
3807      skip_ac_subst => 1);
3808 }
3809
3810
3811 sub handle_subdirs ()
3812 {
3813   my $subdirs = var ('SUBDIRS');
3814   return
3815     unless $subdirs;
3816
3817   check_directories_in_var $subdirs;
3818
3819   my $dsubdirs = var ('DIST_SUBDIRS');
3820   check_directories_in_var $dsubdirs
3821     if $dsubdirs;
3822
3823   $output_rules .= file_contents ('subdirs', new Automake::Location);
3824   rvar ('RECURSIVE_TARGETS')->rdef (TRUE)->{'pretty'} = VAR_SORTED; # Gross!
3825 }
3826
3827
3828 # ($REGEN, @DEPENDENCIES)
3829 # scan_aclocal_m4
3830 # ---------------
3831 # If aclocal.m4 creation is automated, return the list of its dependencies.
3832 sub scan_aclocal_m4 ()
3833 {
3834   my $regen_aclocal = 0;
3835
3836   set_seen 'CONFIG_STATUS_DEPENDENCIES';
3837   set_seen 'CONFIGURE_DEPENDENCIES';
3838
3839   if (-f 'aclocal.m4')
3840     {
3841       define_variable ("ACLOCAL_M4", '$(top_srcdir)/aclocal.m4', INTERNAL);
3842
3843       my $aclocal = new Automake::XFile "< aclocal.m4";
3844       my $line = $aclocal->getline;
3845       $regen_aclocal = $line =~ 'generated automatically by aclocal';
3846     }
3847
3848   my @ac_deps = ();
3849
3850   if (set_seen ('ACLOCAL_M4_SOURCES'))
3851     {
3852       push (@ac_deps, '$(ACLOCAL_M4_SOURCES)');
3853       msg_var ('obsolete', 'ACLOCAL_M4_SOURCES',
3854                "'ACLOCAL_M4_SOURCES' is obsolete.\n"
3855                . "It should be safe to simply remove it");
3856     }
3857
3858   # Note that it might be possible that aclocal.m4 doesn't exist but
3859   # should be auto-generated.  This case probably isn't very
3860   # important.
3861
3862   return ($regen_aclocal, @ac_deps);
3863 }
3864
3865
3866 # Helper function for 'substitute_ac_subst_variables'.
3867 sub substitute_ac_subst_variables_worker
3868 {
3869   my ($token) = @_;
3870   return "\@$token\@" if var $token;
3871   return "\${$token\}";
3872 }
3873
3874 # substitute_ac_subst_variables ($TEXT)
3875 # -------------------------------------
3876 # Replace any occurrence of ${FOO} in $TEXT by @FOO@ if FOO is an AC_SUBST
3877 # variable.
3878 sub substitute_ac_subst_variables
3879 {
3880   my ($text) = @_;
3881   $text =~ s/\${([^ \t=:+{}]+)}/substitute_ac_subst_variables_worker ($1)/ge;
3882   return $text;
3883 }
3884
3885 # @DEPENDENCIES
3886 # prepend_srcdir (@INPUTS)
3887 # ------------------------
3888 # Prepend $(srcdir) or $(top_srcdir) to all @INPUTS.  The idea is that
3889 # if an input file has a directory part the same as the current
3890 # directory, then the directory part is simply replaced by $(srcdir).
3891 # But if the directory part is different, then $(top_srcdir) is
3892 # prepended.
3893 sub prepend_srcdir
3894 {
3895   my (@inputs) = @_;
3896   my @newinputs;
3897
3898   foreach my $single (@inputs)
3899     {
3900       if (dirname ($single) eq $relative_dir)
3901         {
3902           push (@newinputs, '$(srcdir)/' . basename ($single));
3903         }
3904       else
3905         {
3906           push (@newinputs, '$(top_srcdir)/' . $single);
3907         }
3908     }
3909   return @newinputs;
3910 }
3911
3912 # @DEPENDENCIES
3913 # rewrite_inputs_into_dependencies ($OUTPUT, @INPUTS)
3914 # ---------------------------------------------------
3915 # Compute a list of dependencies appropriate for the rebuild
3916 # rule of
3917 #   AC_CONFIG_FILES($OUTPUT:$INPUT[0]:$INPUTS[1]:...)
3918 # Also distribute $INPUTs which are not built by another AC_CONFIG_FOOs.
3919 sub rewrite_inputs_into_dependencies
3920 {
3921   my ($file, @inputs) = @_;
3922   my @res = ();
3923
3924   for my $i (@inputs)
3925     {
3926       # We cannot create dependencies on shell variables.
3927       next if (substitute_ac_subst_variables $i) =~ /\$/;
3928
3929       if (exists $ac_config_files_location{$i} && $i ne $file)
3930         {
3931           my $di = dirname $i;
3932           if ($di eq $relative_dir)
3933             {
3934               $i = basename $i;
3935             }
3936           # In the top-level Makefile we do not use $(top_builddir), because
3937           # we are already there, and since the targets are built without
3938           # a $(top_builddir), it helps BSD Make to match them with
3939           # dependencies.
3940           elsif ($relative_dir ne '.')
3941             {
3942               $i = '$(top_builddir)/' . $i;
3943             }
3944         }
3945       else
3946         {
3947           msg ('error', $ac_config_files_location{$file},
3948                "required file '$i' not found")
3949             unless $i =~ /\$/ || exists $output_files{$i} || -f $i;
3950           ($i) = prepend_srcdir ($i);
3951           push_dist_common ($i);
3952         }
3953       push @res, $i;
3954     }
3955   return @res;
3956 }
3957
3958
3959
3960 # handle_configure ($MAKEFILE_AM, $MAKEFILE_IN, $MAKEFILE, @INPUTS)
3961 # -----------------------------------------------------------------
3962 # Handle remaking and configure stuff.
3963 # We need the name of the input file, to do proper remaking rules.
3964 sub handle_configure
3965 {
3966   my ($makefile_am, $makefile_in, $makefile, @inputs) = @_;
3967
3968   prog_error 'empty @inputs'
3969     unless @inputs;
3970
3971   my ($rel_makefile_am, $rel_makefile_in) = prepend_srcdir ($makefile_am,
3972                                                             $makefile_in);
3973   my $rel_makefile = basename $makefile;
3974
3975   my $colon_infile = ':' . join (':', @inputs);
3976   $colon_infile = '' if $colon_infile eq ":$makefile.in";
3977   my @rewritten = rewrite_inputs_into_dependencies ($makefile, @inputs);
3978   my ($regen_aclocal_m4, @aclocal_m4_deps) = scan_aclocal_m4;
3979   define_pretty_variable ('am__aclocal_m4_deps', TRUE, INTERNAL,
3980                           @configure_deps, @aclocal_m4_deps,
3981                           '$(top_srcdir)/' . $configure_ac);
3982   my @configuredeps = ('$(am__aclocal_m4_deps)', '$(CONFIGURE_DEPENDENCIES)');
3983   push @configuredeps, '$(ACLOCAL_M4)' if -f 'aclocal.m4';
3984   define_pretty_variable ('am__configure_deps', TRUE, INTERNAL,
3985                           @configuredeps);
3986
3987   my $automake_options = '--' . $strictness_name .
3988                          (global_option 'no-dependencies' ? ' --ignore-deps' : '');
3989
3990   $output_rules .= file_contents
3991     ('configure',
3992      new Automake::Location,
3993      MAKEFILE              => $rel_makefile,
3994      'MAKEFILE-DEPS'       => "@rewritten",
3995      'CONFIG-MAKEFILE'     => ($relative_dir eq '.') ? '$@' : '$(subdir)/$@',
3996      'MAKEFILE-IN'         => $rel_makefile_in,
3997      'HAVE-MAKEFILE-IN-DEPS' => (@include_stack > 0),
3998      'MAKEFILE-IN-DEPS'    => "@include_stack",
3999      'MAKEFILE-AM'         => $rel_makefile_am,
4000      'AUTOMAKE-OPTIONS'    => $automake_options,
4001      'MAKEFILE-AM-SOURCES' => "$makefile$colon_infile",
4002      'REGEN-ACLOCAL-M4'    => $regen_aclocal_m4,
4003      VERBOSE               => verbose_flag ('GEN'));
4004
4005   if ($relative_dir eq '.')
4006     {
4007       push_dist_common ('acconfig.h')
4008         if -f 'acconfig.h';
4009     }
4010
4011   # If we have a configure header, require it.
4012   my $hdr_index = 0;
4013   my @distclean_config;
4014   foreach my $spec (@config_headers)
4015     {
4016       $hdr_index += 1;
4017       # $CONFIG_H_PATH: config.h from top level.
4018       my ($config_h_path, @ins) = split_config_file_spec ($spec);
4019       my $config_h_dir = dirname ($config_h_path);
4020
4021       # If the header is in the current directory we want to build
4022       # the header here.  Otherwise, if we're at the topmost
4023       # directory and the header's directory doesn't have a
4024       # Makefile, then we also want to build the header.
4025       if ($relative_dir eq $config_h_dir
4026           || ($relative_dir eq '.' && ! is_make_dir ($config_h_dir)))
4027         {
4028           my ($cn_sans_dir, $stamp_dir);
4029           if ($relative_dir eq $config_h_dir)
4030             {
4031               $cn_sans_dir = basename ($config_h_path);
4032               $stamp_dir = '';
4033             }
4034           else
4035             {
4036               $cn_sans_dir = $config_h_path;
4037               if ($config_h_dir eq '.')
4038                 {
4039                   $stamp_dir = '';
4040                 }
4041               else
4042                 {
4043                   $stamp_dir = $config_h_dir . '/';
4044                 }
4045             }
4046
4047           # This will also distribute all inputs.
4048           @ins = rewrite_inputs_into_dependencies ($config_h_path, @ins);
4049
4050           # Cannot define rebuild rules for filenames with shell variables.
4051           next if (substitute_ac_subst_variables $config_h_path) =~ /\$/;
4052
4053           # Header defined in this directory.
4054           my @files;
4055           if (-f $config_h_path . '.top')
4056             {
4057               push (@files, "$cn_sans_dir.top");
4058             }
4059           if (-f $config_h_path . '.bot')
4060             {
4061               push (@files, "$cn_sans_dir.bot");
4062             }
4063
4064           push_dist_common (@files);
4065
4066           # For now, acconfig.h can only appear in the top srcdir.
4067           if (-f 'acconfig.h')
4068             {
4069               push (@files, '$(top_srcdir)/acconfig.h');
4070             }
4071
4072           my $stamp = "${stamp_dir}stamp-h${hdr_index}";
4073           $output_rules .=
4074             file_contents ('remake-hdr',
4075                            new Automake::Location,
4076                            FILES            => "@files",
4077                            'FIRST-HDR'      => ($hdr_index == 1),
4078                            CONFIG_H         => $cn_sans_dir,
4079                            CONFIG_HIN       => $ins[0],
4080                            CONFIG_H_DEPS    => "@ins",
4081                            CONFIG_H_PATH    => $config_h_path,
4082                            STAMP            => "$stamp");
4083
4084           push @distclean_config, $cn_sans_dir, $stamp;
4085         }
4086     }
4087
4088   $output_rules .= file_contents ('clean-hdr',
4089                                   new Automake::Location,
4090                                   FILES => "@distclean_config")
4091     if @distclean_config;
4092
4093   # Distribute and define mkinstalldirs only if it is already present
4094   # in the package, for backward compatibility (some people may still
4095   # use $(mkinstalldirs)).
4096   # TODO: start warning about this in Automake 1.14, and have
4097   # TODO: Automake 2.0 drop it (and the mkinstalldirs script
4098   # TODO: as well).
4099   my $mkidpath = "$config_aux_dir/mkinstalldirs";
4100   if (-f $mkidpath)
4101     {
4102       # Use require_file so that any existing script gets updated
4103       # by --force-missing.
4104       require_conf_file ($mkidpath, FOREIGN, 'mkinstalldirs');
4105       define_variable ('mkinstalldirs',
4106                        "\$(SHELL) $am_config_aux_dir/mkinstalldirs", INTERNAL);
4107     }
4108   else
4109     {
4110       # Use $(install_sh), not $(MKDIR_P) because the latter requires
4111       # at least one argument, and $(mkinstalldirs) used to work
4112       # even without arguments (e.g. $(mkinstalldirs) $(conditional_dir)).
4113       define_variable ('mkinstalldirs', '$(install_sh) -d', INTERNAL);
4114     }
4115
4116   reject_var ('CONFIG_HEADER',
4117               "'CONFIG_HEADER' is an anachronism; now determined "
4118               . "automatically\nfrom '$configure_ac'");
4119
4120   my @config_h;
4121   foreach my $spec (@config_headers)
4122     {
4123       my ($out, @ins) = split_config_file_spec ($spec);
4124       # Generate CONFIG_HEADER define.
4125       if ($relative_dir eq dirname ($out))
4126         {
4127           push @config_h, basename ($out);
4128         }
4129       else
4130         {
4131           push @config_h, "\$(top_builddir)/$out";
4132         }
4133     }
4134   define_variable ("CONFIG_HEADER", "@config_h", INTERNAL)
4135     if @config_h;
4136
4137   # Now look for other files in this directory which must be remade
4138   # by config.status, and generate rules for them.
4139   my @actual_other_files = ();
4140   # These get cleaned only in a VPATH build.
4141   my @actual_other_vpath_files = ();
4142   foreach my $lfile (@other_input_files)
4143     {
4144       my $file;
4145       my @inputs;
4146       if ($lfile =~ /^([^:]*):(.*)$/)
4147         {
4148           # This is the ":" syntax of AC_OUTPUT.
4149           $file = $1;
4150           @inputs = split (':', $2);
4151         }
4152       else
4153         {
4154           # Normal usage.
4155           $file = $lfile;
4156           @inputs = $file . '.in';
4157         }
4158
4159       # Automake files should not be stored in here, but in %MAKE_LIST.
4160       prog_error ("$lfile in \@other_input_files\n"
4161                   . "\@other_input_files = (@other_input_files)")
4162         if -f $file . '.am';
4163
4164       my $local = basename ($file);
4165
4166       # We skip files that aren't in this directory.  However, if
4167       # the file's directory does not have a Makefile, and we are
4168       # currently doing '.', then we create a rule to rebuild the
4169       # file in the subdir.
4170       my $fd = dirname ($file);
4171       if ($fd ne $relative_dir)
4172         {
4173           if ($relative_dir eq '.' && ! is_make_dir ($fd))
4174             {
4175               $local = $file;
4176             }
4177           else
4178             {
4179               next;
4180             }
4181         }
4182
4183       my @rewritten_inputs = rewrite_inputs_into_dependencies ($file, @inputs);
4184
4185       # Cannot output rules for shell variables.
4186       next if (substitute_ac_subst_variables $local) =~ /\$/;
4187
4188       my $condstr = '';
4189       my $cond = $ac_config_files_condition{$lfile};
4190       if (defined $cond)
4191         {
4192           $condstr = $cond->subst_string;
4193           Automake::Rule::define ($local, $configure_ac, RULE_AUTOMAKE, $cond,
4194                                   $ac_config_files_location{$file});
4195         }
4196       $output_rules .= ($condstr . $local . ': '
4197                         . '$(top_builddir)/config.status '
4198                         . "@rewritten_inputs\n"
4199                         . $condstr . "\t"
4200                         . 'cd $(top_builddir) && '
4201                         . '$(SHELL) ./config.status '
4202                         . ($relative_dir eq '.' ? '' : '$(subdir)/')
4203                         . '$@'
4204                         . "\n");
4205       push (@actual_other_files, $local);
4206     }
4207
4208   # For links we should clean destinations and distribute sources.
4209   foreach my $spec (@config_links)
4210     {
4211       my ($link, $file) = split /:/, $spec;
4212       # Some people do AC_CONFIG_LINKS($computed).  We only handle
4213       # the DEST:SRC form.
4214       next unless $file;
4215       my $where = $ac_config_files_location{$link};
4216
4217       # Skip destinations that contain shell variables.
4218       if ((substitute_ac_subst_variables $link) !~ /\$/)
4219         {
4220           # We skip links that aren't in this directory.  However, if
4221           # the link's directory does not have a Makefile, and we are
4222           # currently doing '.', then we add the link to CONFIG_CLEAN_FILES
4223           # in '.'s Makefile.in.
4224           my $local = basename ($link);
4225           my $fd = dirname ($link);
4226           if ($fd ne $relative_dir)
4227             {
4228               if ($relative_dir eq '.' && ! is_make_dir ($fd))
4229                 {
4230                   $local = $link;
4231                 }
4232               else
4233                 {
4234                   $local = undef;
4235                 }
4236             }
4237           if ($file ne $link)
4238             {
4239               push @actual_other_files, $local if $local;
4240             }
4241           else
4242             {
4243               push @actual_other_vpath_files, $local if $local;
4244             }
4245         }
4246
4247       # Do not process sources that contain shell variables.
4248       if ((substitute_ac_subst_variables $file) !~ /\$/)
4249         {
4250           my $fd = dirname ($file);
4251
4252           # We distribute files that are in this directory.
4253           # At the top-level ('.') we also distribute files whose
4254           # directory does not have a Makefile.
4255           if (($fd eq $relative_dir)
4256               || ($relative_dir eq '.' && ! is_make_dir ($fd)))
4257             {
4258               # The following will distribute $file as a side-effect when
4259               # it is appropriate (i.e., when $file is not already an output).
4260               # We do not need the result, just the side-effect.
4261               rewrite_inputs_into_dependencies ($link, $file);
4262             }
4263         }
4264     }
4265
4266   # These files get removed by "make distclean".
4267   define_pretty_variable ('CONFIG_CLEAN_FILES', TRUE, INTERNAL,
4268                           @actual_other_files);
4269   define_pretty_variable ('CONFIG_CLEAN_VPATH_FILES', TRUE, INTERNAL,
4270                           @actual_other_vpath_files);
4271 }
4272
4273 sub handle_headers ()
4274 {
4275     my @r = am_install_var ('-defaultdist', 'header', 'HEADERS', 'include',
4276                             'oldinclude', 'pkginclude',
4277                             'noinst', 'check');
4278     foreach (@r)
4279     {
4280       next unless $_->[1] =~ /\..*$/;
4281       saw_extension ($&);
4282     }
4283 }
4284
4285 sub handle_gettext ()
4286 {
4287   return if ! $seen_gettext || $relative_dir ne '.';
4288
4289   my $subdirs = var 'SUBDIRS';
4290
4291   if (! $subdirs)
4292     {
4293       err_ac "AM_GNU_GETTEXT used but SUBDIRS not defined";
4294       return;
4295     }
4296
4297   # Perform some sanity checks to help users get the right setup.
4298   # We disable these tests when po/ doesn't exist in order not to disallow
4299   # unusual gettext setups.
4300   #
4301   # Bruno Haible:
4302   # | The idea is:
4303   # |
4304   # |  1) If a package doesn't have a directory po/ at top level, it
4305   # |     will likely have multiple po/ directories in subpackages.
4306   # |
4307   # |  2) It is useful to warn for the absence of intl/ if AM_GNU_GETTEXT
4308   # |     is used without 'external'. It is also useful to warn for the
4309   # |     presence of intl/ if AM_GNU_GETTEXT([external]) is used. Both
4310   # |     warnings apply only to the usual layout of packages, therefore
4311   # |     they should both be disabled if no po/ directory is found at
4312   # |     top level.
4313
4314   if (-d 'po')
4315     {
4316       my @subdirs = $subdirs->value_as_list_recursive;
4317
4318       msg_var ('syntax', $subdirs,
4319                "AM_GNU_GETTEXT used but 'po' not in SUBDIRS")
4320         if ! grep ($_ eq 'po', @subdirs);
4321
4322       # intl/ is not required when AM_GNU_GETTEXT is called with the
4323       # 'external' option and AM_GNU_GETTEXT_INTL_SUBDIR is not called.
4324       msg_var ('syntax', $subdirs,
4325                "AM_GNU_GETTEXT used but 'intl' not in SUBDIRS")
4326         if (! ($seen_gettext_external && ! $seen_gettext_intl)
4327             && ! grep ($_ eq 'intl', @subdirs));
4328
4329       # intl/ should not be used with AM_GNU_GETTEXT([external]), except
4330       # if AM_GNU_GETTEXT_INTL_SUBDIR is called.
4331       msg_var ('syntax', $subdirs,
4332                "'intl' should not be in SUBDIRS when "
4333                . "AM_GNU_GETTEXT([external]) is used")
4334         if ($seen_gettext_external && ! $seen_gettext_intl
4335             && grep ($_ eq 'intl', @subdirs));
4336     }
4337
4338   require_file ($ac_gettext_location, GNU, 'ABOUT-NLS');
4339 }
4340
4341 # Emit makefile footer.
4342 sub handle_footer ()
4343 {
4344     reject_rule ('.SUFFIXES',
4345                  "use variable 'SUFFIXES', not target '.SUFFIXES'");
4346
4347     # Note: AIX 4.1 /bin/make will fail if any suffix rule appears
4348     # before .SUFFIXES.  So we make sure that .SUFFIXES appears before
4349     # anything else, by sticking it right after the default: target.
4350     $output_header .= ".SUFFIXES:\n";
4351     my $suffixes = var 'SUFFIXES';
4352     my @suffixes = Automake::Rule::suffixes;
4353     if (@suffixes || $suffixes)
4354     {
4355         # Make sure SUFFIXES has unique elements.  Sort them to ensure
4356         # the output remains consistent.  However, $(SUFFIXES) is
4357         # always at the start of the list, unsorted.  This is done
4358         # because make will choose rules depending on the ordering of
4359         # suffixes, and this lets the user have some control.  Push
4360         # actual suffixes, and not $(SUFFIXES).  Some versions of make
4361         # do not like variable substitutions on the .SUFFIXES line.
4362         my @user_suffixes = ($suffixes
4363                              ? $suffixes->value_as_list_recursive : ());
4364
4365         my %suffixes = map { $_ => 1 } @suffixes;
4366         delete @suffixes{@user_suffixes};
4367
4368         $output_header .= (".SUFFIXES: "
4369                            . join (' ', @user_suffixes, sort keys %suffixes)
4370                            . "\n");
4371     }
4372
4373     $output_trailer .= file_contents ('footer', new Automake::Location);
4374 }
4375
4376
4377 # Generate 'make install' rules.
4378 sub handle_install ()
4379 {
4380   $output_rules .= file_contents
4381     ('install',
4382      new Automake::Location,
4383      maybe_BUILT_SOURCES => (set_seen ('BUILT_SOURCES')
4384                              ? (" \$(BUILT_SOURCES)\n"
4385                                 . "\t\$(MAKE) \$(AM_MAKEFLAGS)")
4386                              : ''),
4387      'installdirs-local' => (user_phony_rule ('installdirs-local')
4388                              ? ' installdirs-local' : ''),
4389      am__installdirs => variable_value ('am__installdirs') || '');
4390 }
4391
4392
4393 # handle_all ($MAKEFILE)
4394 #-----------------------
4395 # Deal with 'all' and 'all-am'.
4396 sub handle_all
4397 {
4398     my ($makefile) = @_;
4399
4400     # Output 'all-am'.
4401
4402     # Put this at the beginning for the sake of non-GNU makes.  This
4403     # is still wrong if these makes can run parallel jobs.  But it is
4404     # right enough.
4405     unshift (@all, basename ($makefile));
4406
4407     foreach my $spec (@config_headers)
4408       {
4409         my ($out, @ins) = split_config_file_spec ($spec);
4410         push (@all, basename ($out))
4411           if dirname ($out) eq $relative_dir;
4412       }
4413
4414     # Install 'all' hooks.
4415     push (@all, "all-local")
4416       if user_phony_rule "all-local";
4417
4418     pretty_print_rule ("all-am:", "\t\t", @all);
4419     depend ('.PHONY', 'all-am', 'all');
4420
4421
4422     # Output 'all'.
4423
4424     my @local_headers = ();
4425     push @local_headers, '$(BUILT_SOURCES)'
4426       if var ('BUILT_SOURCES');
4427     foreach my $spec (@config_headers)
4428       {
4429         my ($out, @ins) = split_config_file_spec ($spec);
4430         push @local_headers, basename ($out)
4431           if dirname ($out) eq $relative_dir;
4432       }
4433
4434     if (@local_headers)
4435       {
4436         # We need to make sure config.h is built before we recurse.
4437         # We also want to make sure that built sources are built
4438         # before any ordinary 'all' targets are run.  We can't do this
4439         # by changing the order of dependencies to the "all" because
4440         # that breaks when using parallel makes.  Instead we handle
4441         # things explicitly.
4442         $output_all .= ("all: @local_headers"
4443                         . "\n\t"
4444                         . '$(MAKE) $(AM_MAKEFLAGS) '
4445                         . (var ('SUBDIRS') ? 'all-recursive' : 'all-am')
4446                         . "\n\n");
4447         depend ('.MAKE', 'all');
4448       }
4449     else
4450       {
4451         $output_all .= "all: " . (var ('SUBDIRS')
4452                                   ? 'all-recursive' : 'all-am') . "\n\n";
4453       }
4454 }
4455
4456 # Generate helper targets for user-defined recursive targets, where needed.
4457 sub handle_user_recursion ()
4458 {
4459   return unless @extra_recursive_targets;
4460
4461   define_pretty_variable ('am__extra_recursive_targets', TRUE, INTERNAL,
4462                           map { "$_-recursive" } @extra_recursive_targets);
4463   my $aux = var ('SUBDIRS') ? 'recursive' : 'am';
4464   foreach my $target (@extra_recursive_targets)
4465     {
4466       # This allows the default target's rules to be overridden in
4467       # Makefile.am.
4468       user_phony_rule ($target);
4469       depend ("$target", "$target-$aux");
4470       depend ("$target-am", "$target-local");
4471       # Every user-defined recursive target 'foo' *must* have a valid
4472       # associated 'foo-local' rule; we define it as an empty rule by
4473       # default, so that the user can transparently extend it in his
4474       # own Makefile.am.
4475       pretty_print_rule ("$target-local:", '', '');
4476       # $target-recursive might as well be undefined, so do not add
4477       # it here; it's taken care of in subdirs.am anyway.
4478       depend (".PHONY", "$target-am", "$target-local");
4479     }
4480 }
4481
4482
4483 # Handle check merge target specially.
4484 sub do_check_merge_target ()
4485 {
4486   # Include user-defined local form of target.
4487   push @check_tests, 'check-local'
4488     if user_phony_rule 'check-local';
4489
4490   # The check target must depend on the local equivalent of
4491   # 'all', to ensure all the primary targets are built.  Then it
4492   # must build the local check rules.
4493   $output_rules .= "check-am: all-am\n";
4494   if (@check)
4495     {
4496       pretty_print_rule ("\t\$(MAKE) \$(AM_MAKEFLAGS)", "\t  ", @check);
4497       depend ('.MAKE', 'check-am');
4498     }
4499
4500   if (@check_tests)
4501     {
4502       pretty_print_rule ("\t\$(MAKE) \$(AM_MAKEFLAGS)", "\t  ",
4503                          @check_tests);
4504       depend ('.MAKE', 'check-am');
4505     }
4506
4507   depend '.PHONY', 'check', 'check-am';
4508   # Handle recursion.  We have to honor BUILT_SOURCES like for 'all:'.
4509   $output_rules .= ("check: "
4510                     . (var ('BUILT_SOURCES')
4511                        ? "\$(BUILT_SOURCES)\n\t\$(MAKE) \$(AM_MAKEFLAGS) "
4512                        : '')
4513                     . (var ('SUBDIRS') ? 'check-recursive' : 'check-am')
4514                     . "\n");
4515   depend ('.MAKE', 'check')
4516     if var ('BUILT_SOURCES');
4517 }
4518
4519 # Handle all 'clean' targets.
4520 sub handle_clean
4521 {
4522   my ($makefile) = @_;
4523
4524   # Clean the files listed in user variables if they exist.
4525   $clean_files{'$(MOSTLYCLEANFILES)'} = MOSTLY_CLEAN
4526     if var ('MOSTLYCLEANFILES');
4527   $clean_files{'$(CLEANFILES)'} = CLEAN
4528     if var ('CLEANFILES');
4529   $clean_files{'$(DISTCLEANFILES)'} = DIST_CLEAN
4530     if var ('DISTCLEANFILES');
4531   $clean_files{'$(MAINTAINERCLEANFILES)'} = MAINTAINER_CLEAN
4532     if var ('MAINTAINERCLEANFILES');
4533
4534   # Built sources are automatically removed by maintainer-clean.
4535   $clean_files{'$(BUILT_SOURCES)'} = MAINTAINER_CLEAN
4536     if var ('BUILT_SOURCES');
4537
4538   # Compute a list of "rm"s to run for each target.
4539   my %rms = (MOSTLY_CLEAN, [],
4540              CLEAN, [],
4541              DIST_CLEAN, [],
4542              MAINTAINER_CLEAN, []);
4543
4544   foreach my $file (keys %clean_files)
4545     {
4546       my $when = $clean_files{$file};
4547       prog_error 'invalid entry in %clean_files'
4548         unless exists $rms{$when};
4549
4550       my $rm = "rm -f $file";
4551       # If file is a variable, make sure when don't call 'rm -f' without args.
4552       $rm ="test -z \"$file\" || $rm"
4553         if ($file =~ /^\s*\$(\(.*\)|\{.*\})\s*$/);
4554
4555       push @{$rms{$when}}, "\t-$rm\n";
4556     }
4557
4558   $output_rules .= file_contents
4559     ('clean',
4560      new Automake::Location,
4561      MOSTLYCLEAN_RMS      => join ('', sort @{$rms{&MOSTLY_CLEAN}}),
4562      CLEAN_RMS            => join ('', sort @{$rms{&CLEAN}}),
4563      DISTCLEAN_RMS        => join ('', sort @{$rms{&DIST_CLEAN}}),
4564      MAINTAINER_CLEAN_RMS => join ('', sort @{$rms{&MAINTAINER_CLEAN}}),
4565      MAKEFILE             => basename $makefile,
4566      );
4567 }
4568
4569
4570 # Subroutine for handle_factored_dependencies() to let '.PHONY' and
4571 # other '.TARGETS' be last.  This is meant to be used as a comparison
4572 # subroutine passed to the sort built-int.
4573 sub target_cmp
4574 {
4575   return 0 if $a eq $b;
4576
4577   my $a1 = substr ($a, 0, 1);
4578   my $b1 = substr ($b, 0, 1);
4579   if ($a1 ne $b1)
4580     {
4581       return -1 if $b1 eq '.';
4582       return 1 if $a1 eq '.';
4583     }
4584   return $a cmp $b;
4585 }
4586
4587
4588 # Handle everything related to gathered targets.
4589 sub handle_factored_dependencies ()
4590 {
4591   # Reject bad hooks.
4592   foreach my $utarg ('uninstall-data-local', 'uninstall-data-hook',
4593                      'uninstall-exec-local', 'uninstall-exec-hook',
4594                      'uninstall-dvi-local',
4595                      'uninstall-html-local',
4596                      'uninstall-info-local',
4597                      'uninstall-pdf-local',
4598                      'uninstall-ps-local')
4599     {
4600       my $x = $utarg;
4601       $x =~ s/-.*-/-/;
4602       reject_rule ($utarg, "use '$x', not '$utarg'");
4603     }
4604
4605   reject_rule ('install-local',
4606                "use 'install-data-local' or 'install-exec-local', "
4607                . "not 'install-local'");
4608
4609   reject_rule ('install-hook',
4610                "use 'install-data-hook' or 'install-exec-hook', "
4611                . "not 'install-hook'");
4612
4613   # Install the -local hooks.
4614   foreach (keys %dependencies)
4615     {
4616       # Hooks are installed on the -am targets.
4617       s/-am$// or next;
4618       depend ("$_-am", "$_-local")
4619         if user_phony_rule "$_-local";
4620     }
4621
4622   # Install the -hook hooks.
4623   # FIXME: Why not be as liberal as we are with -local hooks?
4624   foreach ('install-exec', 'install-data', 'uninstall')
4625     {
4626       if (user_phony_rule "$_-hook")
4627         {
4628           depend ('.MAKE', "$_-am");
4629           register_action("$_-am",
4630                           ("\t\@\$(NORMAL_INSTALL)\n"
4631                            . "\t\$(MAKE) \$(AM_MAKEFLAGS) $_-hook"));
4632         }
4633     }
4634
4635   # All the required targets are phony.
4636   depend ('.PHONY', keys %required_targets);
4637
4638   # Actually output gathered targets.
4639   foreach (sort target_cmp keys %dependencies)
4640     {
4641       # If there is nothing about this guy, skip it.
4642       next
4643         unless (@{$dependencies{$_}}
4644                 || $actions{$_}
4645                 || $required_targets{$_});
4646
4647       # Define gathered targets in undefined conditions.
4648       # FIXME: Right now we must handle .PHONY as an exception,
4649       # because people write things like
4650       #    .PHONY: myphonytarget
4651       # to append dependencies.  This would not work if Automake
4652       # refrained from defining its own .PHONY target as it does
4653       # with other overridden targets.
4654       # Likewise for '.MAKE'.
4655       my @undefined_conds = (TRUE,);
4656       if ($_ ne '.PHONY' && $_ ne '.MAKE')
4657         {
4658           @undefined_conds =
4659             Automake::Rule::define ($_, 'internal',
4660                                     RULE_AUTOMAKE, TRUE, INTERNAL);
4661         }
4662       my @uniq_deps = uniq (sort @{$dependencies{$_}});
4663       foreach my $cond (@undefined_conds)
4664         {
4665           my $condstr = $cond->subst_string;
4666           pretty_print_rule ("$condstr$_:", "$condstr\t", @uniq_deps);
4667           $output_rules .= $actions{$_} if defined $actions{$_};
4668           $output_rules .= "\n";
4669         }
4670     }
4671 }
4672
4673
4674 sub handle_tests_dejagnu ()
4675 {
4676     push (@check_tests, 'check-DEJAGNU');
4677     $output_rules .= file_contents ('dejagnu', new Automake::Location);
4678 }
4679
4680 # handle_per_suffix_test ($TEST_SUFFIX, [%TRANSFORM])
4681 #----------------------------------------------------
4682 sub handle_per_suffix_test
4683 {
4684   my ($test_suffix, %transform) = @_;
4685   my ($pfx, $generic, $am_exeext);
4686   if ($test_suffix eq '')
4687     {
4688       $pfx = '';
4689       $generic = 0;
4690       $am_exeext = 'FALSE';
4691     }
4692   else
4693     {
4694       prog_error ("test suffix '$test_suffix' lacks leading dot")
4695         unless $test_suffix =~ m/^\.(.*)/;
4696       $pfx = uc ($1) . '_';
4697       $generic = 1;
4698       $am_exeext = exists $configure_vars{'EXEEXT'} ? 'am__EXEEXT'
4699                                                     : 'FALSE';
4700     }
4701   # The "test driver" program, deputed to handle tests protocol used by
4702   # test scripts.  By default, it's assumed that no protocol is used, so
4703   # we fall back to the old behaviour, implemented by the 'test-driver'
4704   # auxiliary script.
4705   if (! var "${pfx}LOG_DRIVER")
4706     {
4707       require_conf_file ("parallel-tests", FOREIGN, 'test-driver');
4708       define_variable ("${pfx}LOG_DRIVER",
4709                        "\$(SHELL) $am_config_aux_dir/test-driver",
4710                        INTERNAL);
4711     }
4712   my $driver = '$(' . $pfx . 'LOG_DRIVER)';
4713   my $driver_flags = '$(AM_' . $pfx . 'LOG_DRIVER_FLAGS)'
4714                        . ' $(' . $pfx . 'LOG_DRIVER_FLAGS)';
4715   my $compile = "${pfx}LOG_COMPILE";
4716   define_variable ($compile,
4717                    '$(' . $pfx . 'LOG_COMPILER)'
4718                       . ' $(AM_' .  $pfx . 'LOG_FLAGS)'
4719                       . ' $(' . $pfx . 'LOG_FLAGS)',
4720                      INTERNAL);
4721   $output_rules .= file_contents ('check2', new Automake::Location,
4722                                    GENERIC => $generic,
4723                                    DRIVER => $driver,
4724                                    DRIVER_FLAGS => $driver_flags,
4725                                    COMPILE => '$(' . $compile . ')',
4726                                    EXT => $test_suffix,
4727                                    am__EXEEXT => $am_exeext,
4728                                    %transform);
4729 }
4730
4731 # is_valid_test_extension ($EXT)
4732 # ------------------------------
4733 # Return true if $EXT can appear in $(TEST_EXTENSIONS), return false
4734 # otherwise.
4735 sub is_valid_test_extension
4736 {
4737   my $ext = shift;
4738   return 1
4739     if ($ext =~ /^\.[a-zA-Z_][a-zA-Z0-9_]*$/);
4740   return 1
4741     if (exists $configure_vars{'EXEEXT'} && $ext eq subst ('EXEEXT'));
4742   return 0;
4743 }
4744
4745
4746 sub handle_tests ()
4747 {
4748   if (option 'dejagnu')
4749     {
4750       handle_tests_dejagnu;
4751     }
4752   else
4753     {
4754       foreach my $c ('DEJATOOL', 'RUNTEST', 'RUNTESTFLAGS')
4755         {
4756           reject_var ($c, "'$c' defined but 'dejagnu' not in "
4757                       . "'AUTOMAKE_OPTIONS'");
4758         }
4759     }
4760
4761   if (var ('TESTS'))
4762     {
4763       push (@check_tests, 'check-TESTS');
4764       my $check_deps = "@check";
4765       $output_rules .= file_contents ('check', new Automake::Location,
4766                                       SERIAL_TESTS => !! option 'serial-tests',
4767                                       CHECK_DEPS => $check_deps);
4768
4769       # Tests that are known programs should have $(EXEEXT) appended.
4770       # For matching purposes, we need to adjust XFAIL_TESTS as well.
4771       append_exeext { exists $known_programs{$_[0]} } 'TESTS';
4772       append_exeext { exists $known_programs{$_[0]} } 'XFAIL_TESTS'
4773         if (var ('XFAIL_TESTS'));
4774
4775       if (! option 'serial-tests')
4776         {
4777           define_variable ('TEST_SUITE_LOG', 'test-suite.log', INTERNAL);
4778           my $suff = '.test';
4779           my $at_exeext = '';
4780           my $handle_exeext = exists $configure_vars{'EXEEXT'};
4781           if ($handle_exeext)
4782             {
4783               $at_exeext = subst ('EXEEXT');
4784               $suff = $at_exeext  . ' ' . $suff;
4785             }
4786           if (! var 'TEST_EXTENSIONS')
4787             {
4788               define_variable ('TEST_EXTENSIONS', $suff, INTERNAL);
4789             }
4790           my $var = var 'TEST_EXTENSIONS';
4791           # Currently, we are not able to deal with conditional contents
4792           # in TEST_EXTENSIONS.
4793           if ($var->has_conditional_contents)
4794            {
4795              msg_var 'unsupported', $var,
4796                      "'TEST_EXTENSIONS' cannot have conditional contents";
4797            }
4798           my @test_suffixes = $var->value_as_list_recursive;
4799           if ((my @invalid_test_suffixes =
4800                   grep { !is_valid_test_extension $_ } @test_suffixes) > 0)
4801             {
4802               error $var->rdef (TRUE)->location,
4803                     "invalid test extensions: @invalid_test_suffixes";
4804             }
4805           @test_suffixes = grep { is_valid_test_extension $_ } @test_suffixes;
4806           if ($handle_exeext)
4807             {
4808               unshift (@test_suffixes, $at_exeext)
4809                 unless $test_suffixes[0] eq $at_exeext;
4810             }
4811           unshift (@test_suffixes, '');
4812
4813           transform_variable_recursively
4814             ('TESTS', 'TEST_LOGS', 'am__testlogs', 1, INTERNAL,
4815               sub {
4816                 my ($subvar, $val, $cond, $full_cond) = @_;
4817                 my $obj = $val;
4818                 return $obj
4819                   if $val =~ /^\@.*\@$/;
4820                 $obj =~ s/\$\(EXEEXT\)$//o;
4821
4822                 if ($val =~ /(\$\((top_)?srcdir\))\//o)
4823                   {
4824                     msg ('error', $subvar->rdef ($cond)->location,
4825                          "using '$1' in TESTS is currently broken: '$val'");
4826                   }
4827
4828                 foreach my $test_suffix (@test_suffixes)
4829                   {
4830                     next
4831                       if $test_suffix eq $at_exeext || $test_suffix eq '';
4832                     return substr ($obj, 0, length ($obj) - length ($test_suffix)) . '.log'
4833                       if substr ($obj, - length ($test_suffix)) eq $test_suffix;
4834                   }
4835                 my $base = $obj;
4836                 $obj .= '.log';
4837                 handle_per_suffix_test ('',
4838                                         OBJ => $obj,
4839                                         BASE => $base,
4840                                         SOURCE => $val);
4841                 return $obj;
4842               });
4843
4844           my $nhelper=1;
4845           my $prev = 'TESTS';
4846           my $post = '';
4847           my $last_suffix = $test_suffixes[$#test_suffixes];
4848           my $cur = '';
4849           foreach my $test_suffix (@test_suffixes)
4850             {
4851               if ($test_suffix eq $last_suffix)
4852                 {
4853                   $cur = 'TEST_LOGS';
4854                 }
4855               else
4856                 {
4857                   $cur = 'am__test_logs' . $nhelper;
4858                 }
4859               define_variable ($cur,
4860                 '$(' . $prev . ':' . $test_suffix . $post . '=.log)', INTERNAL);
4861               $post = '.log';
4862               $prev = $cur;
4863               $nhelper++;
4864               if ($test_suffix ne $at_exeext && $test_suffix ne '')
4865                 {
4866                   handle_per_suffix_test ($test_suffix,
4867                                           OBJ => '',
4868                                           BASE => '$*',
4869                                           SOURCE => '$<');
4870                 }
4871             }
4872           $clean_files{'$(TEST_LOGS)'} = MOSTLY_CLEAN;
4873           $clean_files{'$(TEST_LOGS:.log=.trs)'} = MOSTLY_CLEAN;
4874           $clean_files{'$(TEST_SUITE_LOG)'} = MOSTLY_CLEAN;
4875         }
4876     }
4877 }
4878
4879 sub handle_emacs_lisp ()
4880 {
4881   my @elfiles = am_install_var ('-candist', 'lisp', 'LISP',
4882                                 'lisp', 'noinst');
4883
4884   return if ! @elfiles;
4885
4886   define_pretty_variable ('am__ELFILES', TRUE, INTERNAL,
4887                           map { $_->[1] } @elfiles);
4888   define_pretty_variable ('am__ELCFILES', TRUE, INTERNAL,
4889                           '$(am__ELFILES:.el=.elc)');
4890   # This one can be overridden by users.
4891   define_pretty_variable ('ELCFILES', TRUE, INTERNAL, '$(LISP:.el=.elc)');
4892
4893   push @all, '$(ELCFILES)';
4894
4895   require_variables ($elfiles[0][0], "Emacs Lisp sources seen", TRUE,
4896                      'EMACS', 'lispdir');
4897 }
4898
4899 sub handle_python ()
4900 {
4901   my @pyfiles = am_install_var ('-defaultdist', 'python', 'PYTHON',
4902                                 'noinst');
4903   return if ! @pyfiles;
4904
4905   require_variables ($pyfiles[0][0], "Python sources seen", TRUE, 'PYTHON');
4906   require_conf_file ($pyfiles[0][0], FOREIGN, 'py-compile');
4907   define_variable ('py_compile', "$am_config_aux_dir/py-compile", INTERNAL);
4908 }
4909
4910 sub handle_java ()
4911 {
4912     my @sourcelist = am_install_var ('-candist',
4913                                      'java', 'JAVA',
4914                                      'noinst', 'check');
4915     return if ! @sourcelist;
4916
4917     my @prefixes = am_primary_prefixes ('JAVA', 1,
4918                                         'noinst', 'check');
4919
4920     my $dir;
4921     my @java_sources = ();
4922     foreach my $prefix (@prefixes)
4923       {
4924         (my $curs = $prefix) =~ s/^(?:nobase_)?(?:dist_|nodist_)?//;
4925
4926         next
4927           if $curs eq 'EXTRA';
4928
4929         push @java_sources, '$(' . $prefix . '_JAVA' . ')';
4930
4931         if (defined $dir)
4932           {
4933             err_var "${curs}_JAVA", "multiple _JAVA primaries in use"
4934              unless $curs eq $dir;
4935           }
4936
4937         $dir = $curs;
4938       }
4939
4940     define_pretty_variable ('am__java_sources', TRUE, INTERNAL,
4941                             "@java_sources");
4942
4943     if ($dir eq 'check')
4944       {
4945         push (@check, "class$dir.stamp");
4946       }
4947     else
4948       {
4949         push (@all, "class$dir.stamp");
4950       }
4951 }
4952
4953
4954 sub handle_minor_options ()
4955 {
4956   if (option 'readme-alpha')
4957     {
4958       if ($relative_dir eq '.')
4959         {
4960           if ($package_version !~ /^$GNITS_VERSION_PATTERN$/)
4961             {
4962               msg ('error-gnits', $package_version_location,
4963                    "version '$package_version' doesn't follow " .
4964                    "Gnits standards");
4965             }
4966           if (defined $1 && -f 'README-alpha')
4967             {
4968               # This means we have an alpha release.  See
4969               # GNITS_VERSION_PATTERN for details.
4970               push_dist_common ('README-alpha');
4971             }
4972         }
4973     }
4974 }
4975
4976 ################################################################
4977
4978 # ($OUTPUT, @INPUTS)
4979 # split_config_file_spec ($SPEC)
4980 # ------------------------------
4981 # Decode the Autoconf syntax for config files (files, headers, links
4982 # etc.).
4983 sub split_config_file_spec
4984 {
4985   my ($spec) = @_;
4986   my ($output, @inputs) = split (/:/, $spec);
4987
4988   push @inputs, "$output.in"
4989     unless @inputs;
4990
4991   return ($output, @inputs);
4992 }
4993
4994 # $input
4995 # locate_am (@POSSIBLE_SOURCES)
4996 # -----------------------------
4997 # AC_CONFIG_FILES allow specifications such as Makefile:top.in:mid.in:bot.in
4998 # This functions returns the first *.in file for which a *.am exists.
4999 # It returns undef otherwise.
5000 sub locate_am
5001 {
5002   my (@rest) = @_;
5003   my $input;
5004   foreach my $file (@rest)
5005     {
5006       if (($file =~ /^(.*)\.in$/) && -f "$1.am")
5007         {
5008           $input = $file;
5009           last;
5010         }
5011     }
5012   return $input;
5013 }
5014
5015 my %make_list;
5016
5017 # scan_autoconf_config_files ($WHERE, $CONFIG-FILES)
5018 # --------------------------------------------------
5019 # Study $CONFIG-FILES which is the first argument to AC_CONFIG_FILES
5020 # (or AC_OUTPUT).
5021 sub scan_autoconf_config_files
5022 {
5023   my ($where, $config_files) = @_;
5024
5025   # Look at potential Makefile.am's.
5026   foreach (split ' ', $config_files)
5027     {
5028       # Must skip empty string for Perl 4.
5029       next if $_ eq "\\" || $_ eq '';
5030
5031       # Handle $local:$input syntax.
5032       my ($local, @rest) = split (/:/);
5033       @rest = ("$local.in",) unless @rest;
5034       # Keep in sync with test 'conffile-leading-dot.sh'.
5035       msg ('unsupported', $where,
5036            "omit leading './' from config file names such as '$local';"
5037            . "\nremake rules might be subtly broken otherwise")
5038         if ($local =~ /^\.\//);
5039       my $input = locate_am @rest;
5040       if ($input)
5041         {
5042           # We have a file that automake should generate.
5043           $make_list{$input} = join (':', ($local, @rest));
5044         }
5045       else
5046         {
5047           # We have a file that automake should cause to be
5048           # rebuilt, but shouldn't generate itself.
5049           push (@other_input_files, $_);
5050         }
5051       $ac_config_files_location{$local} = $where;
5052       $ac_config_files_condition{$local} =
5053         new Automake::Condition (@cond_stack)
5054           if (@cond_stack);
5055     }
5056 }
5057
5058
5059 sub scan_autoconf_traces
5060 {
5061   my ($filename) = @_;
5062
5063   # Macros to trace, with their minimal number of arguments.
5064   #
5065   # IMPORTANT: If you add a macro here, you should also add this macro
5066   # =========  to Automake-preselection in autoconf/lib/autom4te.in.
5067   my %traced = (
5068                 AC_CANONICAL_BUILD => 0,
5069                 AC_CANONICAL_HOST => 0,
5070                 AC_CANONICAL_TARGET => 0,
5071                 AC_CONFIG_AUX_DIR => 1,
5072                 AC_CONFIG_FILES => 1,
5073                 AC_CONFIG_HEADERS => 1,
5074                 AC_CONFIG_LIBOBJ_DIR => 1,
5075                 AC_CONFIG_LINKS => 1,
5076                 AC_FC_SRCEXT => 1,
5077                 AC_INIT => 0,
5078                 AC_LIBSOURCE => 1,
5079                 AC_REQUIRE_AUX_FILE => 1,
5080                 AC_SUBST_TRACE => 1,
5081                 AM_AUTOMAKE_VERSION => 1,
5082                 AM_PROG_MKDIR_P => 0,
5083                 AM_CONDITIONAL => 2,
5084                 AM_EXTRA_RECURSIVE_TARGETS => 1,
5085                 AM_GNU_GETTEXT => 0,
5086                 AM_GNU_GETTEXT_INTL_SUBDIR => 0,
5087                 AM_INIT_AUTOMAKE => 0,
5088                 AM_MAINTAINER_MODE => 0,
5089                 AM_PROG_AR => 0,
5090                 _AM_SUBST_NOTMAKE => 1,
5091                 _AM_COND_IF => 1,
5092                 _AM_COND_ELSE => 1,
5093                 _AM_COND_ENDIF => 1,
5094                 LT_SUPPORTED_TAG => 1,
5095                 _LT_AC_TAGCONFIG => 0,
5096                 m4_include => 1,
5097                 m4_sinclude => 1,
5098                 sinclude => 1,
5099               );
5100
5101   my $traces = ($ENV{AUTOCONF} || '@am_AUTOCONF@') . " ";
5102
5103   # Use a separator unlikely to be used, not ':', the default, which
5104   # has a precise meaning for AC_CONFIG_FILES and so on.
5105   $traces .= join (' ',
5106                    map { "--trace=$_" . ':\$f:\$l::\$d::\$n::\${::}%' }
5107                    (keys %traced));
5108
5109   my $tracefh = new Automake::XFile ("$traces $filename |");
5110   verb "reading $traces";
5111
5112   @cond_stack = ();
5113   my $where;
5114
5115   while ($_ = $tracefh->getline)
5116     {
5117       chomp;
5118       my ($here, $depth, @args) = split (/::/);
5119       $where = new Automake::Location $here;
5120       my $macro = $args[0];
5121
5122       prog_error ("unrequested trace '$macro'")
5123         unless exists $traced{$macro};
5124
5125       # Skip and diagnose malformed calls.
5126       if ($#args < $traced{$macro})
5127         {
5128           msg ('syntax', $where, "not enough arguments for $macro");
5129           next;
5130         }
5131
5132       # Alphabetical ordering please.
5133       if ($macro eq 'AC_CANONICAL_BUILD')
5134         {
5135           if ($seen_canonical <= AC_CANONICAL_BUILD)
5136             {
5137               $seen_canonical = AC_CANONICAL_BUILD;
5138             }
5139         }
5140       elsif ($macro eq 'AC_CANONICAL_HOST')
5141         {
5142           if ($seen_canonical <= AC_CANONICAL_HOST)
5143             {
5144               $seen_canonical = AC_CANONICAL_HOST;
5145             }
5146         }
5147       elsif ($macro eq 'AC_CANONICAL_TARGET')
5148         {
5149           $seen_canonical = AC_CANONICAL_TARGET;
5150         }
5151       elsif ($macro eq 'AC_CONFIG_AUX_DIR')
5152         {
5153           if ($seen_init_automake)
5154             {
5155               error ($where, "AC_CONFIG_AUX_DIR must be called before "
5156                      . "AM_INIT_AUTOMAKE ...", partial => 1);
5157               error ($seen_init_automake, "... AM_INIT_AUTOMAKE called here");
5158             }
5159           $config_aux_dir = $args[1];
5160           $config_aux_dir_set_in_configure_ac = 1;
5161           check_directory ($config_aux_dir, $where);
5162         }
5163       elsif ($macro eq 'AC_CONFIG_FILES')
5164         {
5165           # Look at potential Makefile.am's.
5166           scan_autoconf_config_files ($where, $args[1]);
5167         }
5168       elsif ($macro eq 'AC_CONFIG_HEADERS')
5169         {
5170           foreach my $spec (split (' ', $args[1]))
5171             {
5172               my ($dest, @src) = split (':', $spec);
5173               $ac_config_files_location{$dest} = $where;
5174               push @config_headers, $spec;
5175             }
5176         }
5177       elsif ($macro eq 'AC_CONFIG_LIBOBJ_DIR')
5178         {
5179           $config_libobj_dir = $args[1];
5180           check_directory ($config_libobj_dir, $where);
5181         }
5182       elsif ($macro eq 'AC_CONFIG_LINKS')
5183         {
5184           foreach my $spec (split (' ', $args[1]))
5185             {
5186               my ($dest, $src) = split (':', $spec);
5187               $ac_config_files_location{$dest} = $where;
5188               push @config_links, $spec;
5189             }
5190         }
5191       elsif ($macro eq 'AC_FC_SRCEXT')
5192         {
5193           my $suffix = $args[1];
5194           # These flags are used as %SOURCEFLAG% in depend2.am,
5195           # where the trailing space is important.
5196           $sourceflags{'.' . $suffix} = '$(FCFLAGS_' . $suffix . ') '
5197             if ($suffix eq 'f90' || $suffix eq 'f95' || $suffix eq 'f03' || $suffix eq 'f08');
5198         }
5199       elsif ($macro eq 'AC_INIT')
5200         {
5201           if (defined $args[2])
5202             {
5203               $package_version = $args[2];
5204               $package_version_location = $where;
5205             }
5206         }
5207       elsif ($macro eq 'AC_LIBSOURCE')
5208         {
5209           $libsources{$args[1]} = $here;
5210         }
5211       elsif ($macro eq 'AC_REQUIRE_AUX_FILE')
5212         {
5213           # Only remember the first time a file is required.
5214           $required_aux_file{$args[1]} = $where
5215             unless exists $required_aux_file{$args[1]};
5216         }
5217       elsif ($macro eq 'AC_SUBST_TRACE')
5218         {
5219           # Just check for alphanumeric in AC_SUBST_TRACE.  If you do
5220           # AC_SUBST(5), then too bad.
5221           $configure_vars{$args[1]} = $where
5222             if $args[1] =~ /^\w+$/;
5223         }
5224       elsif ($macro eq 'AM_AUTOMAKE_VERSION')
5225         {
5226           error ($where,
5227                  "version mismatch.  This is Automake $VERSION,\n" .
5228                  "but the definition used by this AM_INIT_AUTOMAKE\n" .
5229                  "comes from Automake $args[1].  You should recreate\n" .
5230                  "aclocal.m4 with aclocal and run automake again.\n",
5231                  # $? = 63 is used to indicate version mismatch to missing.
5232                  exit_code => 63)
5233             if $VERSION ne $args[1];
5234
5235           $seen_automake_version = 1;
5236         }
5237       elsif ($macro eq 'AM_PROG_MKDIR_P')
5238         {
5239           msg 'obsolete', $where, <<'EOF';
5240 The 'AM_PROG_MKDIR_P' macro is deprecated, and its use is discouraged.
5241 You should use the Autoconf-provided 'AC_PROG_MKDIR_P' macro instead,
5242 and use '$(MKDIR_P)' instead of '$(mkdir_p)'in your Makefile.am files.
5243 EOF
5244         }
5245       elsif ($macro eq 'AM_CONDITIONAL')
5246         {
5247           $configure_cond{$args[1]} = $where;
5248         }
5249       elsif ($macro eq 'AM_EXTRA_RECURSIVE_TARGETS')
5250         {
5251           # Empty leading/trailing fields might be produced by split,
5252           # hence the grep is really needed.
5253           push @extra_recursive_targets,
5254                grep (/./, (split /\s+/, $args[1]));
5255         }
5256       elsif ($macro eq 'AM_GNU_GETTEXT')
5257         {
5258           $seen_gettext = $where;
5259           $ac_gettext_location = $where;
5260           $seen_gettext_external = grep ($_ eq 'external', @args);
5261         }
5262       elsif ($macro eq 'AM_GNU_GETTEXT_INTL_SUBDIR')
5263         {
5264           $seen_gettext_intl = $where;
5265         }
5266       elsif ($macro eq 'AM_INIT_AUTOMAKE')
5267         {
5268           $seen_init_automake = $where;
5269           if (defined $args[2])
5270             {
5271               msg 'obsolete', $where, <<'EOF';
5272 AM_INIT_AUTOMAKE: two- and three-arguments forms are deprecated.  For more info, see:
5273 http://www.gnu.org/software/automake/manual/automake.html#Modernize-AM_005fINIT_005fAUTOMAKE-invocation
5274 EOF
5275               $package_version = $args[2];
5276               $package_version_location = $where;
5277             }
5278           elsif (defined $args[1])
5279             {
5280               my @opts = split (' ', $args[1]);
5281               @opts = map { { option => $_, where => $where } } @opts;
5282               exit $exit_code unless process_global_option_list (@opts);
5283             }
5284         }
5285       elsif ($macro eq 'AM_MAINTAINER_MODE')
5286         {
5287           $seen_maint_mode = $where;
5288         }
5289       elsif ($macro eq 'AM_PROG_AR')
5290         {
5291           $seen_ar = $where;
5292         }
5293       elsif ($macro eq '_AM_COND_IF')
5294         {
5295           cond_stack_if ('', $args[1], $where);
5296           error ($where, "missing m4 quoting, macro depth $depth")
5297             if ($depth != 1);
5298         }
5299       elsif ($macro eq '_AM_COND_ELSE')
5300         {
5301           cond_stack_else ('!', $args[1], $where);
5302           error ($where, "missing m4 quoting, macro depth $depth")
5303             if ($depth != 1);
5304         }
5305       elsif ($macro eq '_AM_COND_ENDIF')
5306         {
5307           cond_stack_endif (undef, undef, $where);
5308           error ($where, "missing m4 quoting, macro depth $depth")
5309             if ($depth != 1);
5310         }
5311       elsif ($macro eq '_AM_SUBST_NOTMAKE')
5312         {
5313           $ignored_configure_vars{$args[1]} = $where;
5314         }
5315       elsif ($macro eq 'm4_include'
5316              || $macro eq 'm4_sinclude'
5317              || $macro eq 'sinclude')
5318         {
5319           # Skip missing 'sinclude'd files.
5320           next if $macro ne 'm4_include' && ! -f $args[1];
5321
5322           # Some modified versions of Autoconf don't use
5323           # frozen files.  Consequently it's possible that we see all
5324           # m4_include's performed during Autoconf's startup.
5325           # Obviously we don't want to distribute Autoconf's files
5326           # so we skip absolute filenames here.
5327           push @configure_deps, '$(top_srcdir)/' . $args[1]
5328             unless $here =~ m,^(?:\w:)?[\\/],;
5329           # Keep track of the greatest timestamp.
5330           if (-e $args[1])
5331             {
5332               my $mtime = mtime $args[1];
5333               $configure_deps_greatest_timestamp = $mtime
5334                 if $mtime > $configure_deps_greatest_timestamp;
5335             }
5336         }
5337       elsif ($macro eq 'LT_SUPPORTED_TAG')
5338         {
5339           $libtool_tags{$args[1]} = 1;
5340           $libtool_new_api = 1;
5341         }
5342       elsif ($macro eq '_LT_AC_TAGCONFIG')
5343         {
5344           # _LT_AC_TAGCONFIG is an old macro present in Libtool 1.5.
5345           # We use it to detect whether tags are supported.  Our
5346           # preferred interface is LT_SUPPORTED_TAG, but it was
5347           # introduced in Libtool 1.6.
5348           if (0 == keys %libtool_tags)
5349             {
5350               # Hardcode the tags supported by Libtool 1.5.
5351               %libtool_tags = (CC => 1, CXX => 1, GCJ => 1, F77 => 1);
5352             }
5353         }
5354     }
5355
5356   error ($where, "condition stack not properly closed")
5357     if (@cond_stack);
5358
5359   $tracefh->close;
5360 }
5361
5362
5363 # Check whether we use 'configure.ac' or 'configure.in'.
5364 # Scan it (and possibly 'aclocal.m4') for interesting things.
5365 # We must scan aclocal.m4 because there might be AC_SUBSTs and such there.
5366 sub scan_autoconf_files ()
5367 {
5368   # Reinitialize libsources here.  This isn't really necessary,
5369   # since we currently assume there is only one configure.ac.  But
5370   # that won't always be the case.
5371   %libsources = ();
5372
5373   # Keep track of the youngest configure dependency.
5374   $configure_deps_greatest_timestamp = mtime $configure_ac;
5375   if (-e 'aclocal.m4')
5376     {
5377       my $mtime = mtime 'aclocal.m4';
5378       $configure_deps_greatest_timestamp = $mtime
5379         if $mtime > $configure_deps_greatest_timestamp;
5380     }
5381
5382   scan_autoconf_traces ($configure_ac);
5383
5384   @configure_input_files = sort keys %make_list;
5385   # Set input and output files if not specified by user.
5386   if (! @input_files)
5387     {
5388       @input_files = @configure_input_files;
5389       %output_files = %make_list;
5390     }
5391
5392
5393   if (! $seen_init_automake)
5394     {
5395       err_ac ("no proper invocation of AM_INIT_AUTOMAKE was found.\nYou "
5396               . "should verify that $configure_ac invokes AM_INIT_AUTOMAKE,"
5397               . "\nthat aclocal.m4 is present in the top-level directory,\n"
5398               . "and that aclocal.m4 was recently regenerated "
5399               . "(using aclocal)");
5400     }
5401   else
5402     {
5403       if (! $seen_automake_version)
5404         {
5405           if (-f 'aclocal.m4')
5406             {
5407               error ($seen_init_automake,
5408                      "your implementation of AM_INIT_AUTOMAKE comes from " .
5409                      "an\nold Automake version.  You should recreate " .
5410                      "aclocal.m4\nwith aclocal and run automake again",
5411                      # $? = 63 is used to indicate version mismatch to missing.
5412                      exit_code => 63);
5413             }
5414           else
5415             {
5416               error ($seen_init_automake,
5417                      "no proper implementation of AM_INIT_AUTOMAKE was " .
5418                      "found,\nprobably because aclocal.m4 is missing.\n" .
5419                      "You should run aclocal to create this file, then\n" .
5420                      "run automake again");
5421             }
5422         }
5423     }
5424
5425   locate_aux_dir ();
5426
5427   # Look for some files we need.  Always check for these.  This
5428   # check must be done for every run, even those where we are only
5429   # looking at a subdir Makefile.  We must set relative_dir for
5430   # push_required_file to work.
5431   # Sort the files for stable verbose output.
5432   $relative_dir = '.';
5433   foreach my $file (sort keys %required_aux_file)
5434     {
5435       require_conf_file ($required_aux_file{$file}->get, FOREIGN, $file)
5436     }
5437   err_am "'install.sh' is an anachronism; use 'install-sh' instead"
5438     if -f $config_aux_dir . '/install.sh';
5439
5440   # Preserve dist_common for later.
5441   $configure_dist_common = variable_value ('DIST_COMMON') || '';
5442
5443 }
5444
5445 ################################################################
5446
5447 # Do any extra checking for GNU standards.
5448 sub check_gnu_standards ()
5449 {
5450   if ($relative_dir eq '.')
5451     {
5452       # In top level (or only) directory.
5453       require_file ("$am_file.am", GNU,
5454                     qw/INSTALL NEWS README AUTHORS ChangeLog/);
5455
5456       # Accept one of these three licenses; default to COPYING.
5457       # Make sure we do not overwrite an existing license.
5458       my $license;
5459       foreach (qw /COPYING COPYING.LIB COPYING.LESSER/)
5460         {
5461           if (-f $_)
5462             {
5463               $license = $_;
5464               last;
5465             }
5466         }
5467       require_file ("$am_file.am", GNU, 'COPYING')
5468         unless $license;
5469     }
5470
5471   for my $opt ('no-installman', 'no-installinfo')
5472     {
5473       msg ('error-gnu', option $opt,
5474            "option '$opt' disallowed by GNU standards")
5475         if option $opt;
5476     }
5477 }
5478
5479 # Do any extra checking for GNITS standards.
5480 sub check_gnits_standards ()
5481 {
5482   if ($relative_dir eq '.')
5483     {
5484       # In top level (or only) directory.
5485       require_file ("$am_file.am", GNITS, 'THANKS');
5486     }
5487 }
5488
5489 ################################################################
5490 #
5491 # Functions to handle files of each language.
5492
5493 # Each 'lang_X_rewrite($DIRECTORY, $BASE, $EXT)' function follows a
5494 # simple formula: Return value is LANG_SUBDIR if the resulting object
5495 # file should be in a subdir if the source file is, LANG_PROCESS if
5496 # file is to be dealt with, LANG_IGNORE otherwise.
5497
5498 # Much of the actual processing is handled in
5499 # handle_single_transform.  These functions exist so that
5500 # auxiliary information can be recorded for a later cleanup pass.
5501 # Note that the calls to these functions are computed, so don't bother
5502 # searching for their precise names in the source.
5503
5504 # This is just a convenience function that can be used to determine
5505 # when a subdir object should be used.
5506 sub lang_sub_obj ()
5507 {
5508     return option 'subdir-objects' ? LANG_SUBDIR : LANG_PROCESS;
5509 }
5510
5511 # Rewrite a single header file.
5512 sub lang_header_rewrite
5513 {
5514     # Header files are simply ignored.
5515     return LANG_IGNORE;
5516 }
5517
5518 # Rewrite a single Vala source file.
5519 sub lang_vala_rewrite
5520 {
5521     my ($directory, $base, $ext) = @_;
5522
5523     (my $newext = $ext) =~ s/vala$/c/;
5524     return (LANG_SUBDIR, $newext);
5525 }
5526
5527 # Rewrite a single yacc/yacc++ file.
5528 sub lang_yacc_rewrite
5529 {
5530     my ($directory, $base, $ext) = @_;
5531
5532     my $r = lang_sub_obj;
5533     (my $newext = $ext) =~ tr/y/c/;
5534     return ($r, $newext);
5535 }
5536 sub lang_yaccxx_rewrite { lang_yacc_rewrite (@_); };
5537
5538 # Rewrite a single lex/lex++ file.
5539 sub lang_lex_rewrite
5540 {
5541     my ($directory, $base, $ext) = @_;
5542
5543     my $r = lang_sub_obj;
5544     (my $newext = $ext) =~ tr/l/c/;
5545     return ($r, $newext);
5546 }
5547 sub lang_lexxx_rewrite { lang_lex_rewrite (@_); };
5548
5549 # Rewrite a single Java file.
5550 sub lang_java_rewrite
5551 {
5552     return LANG_SUBDIR;
5553 }
5554
5555 # The lang_X_finish functions are called after all source file
5556 # processing is done.  Each should handle defining rules for the
5557 # language, etc.  A finish function is only called if a source file of
5558 # the appropriate type has been seen.
5559
5560 sub lang_vala_finish_target
5561 {
5562   my ($self, $name) = @_;
5563
5564   my $derived = canonicalize ($name);
5565   my $var = var "${derived}_SOURCES";
5566   return unless $var;
5567
5568   my @vala_sources = grep { /\.(vala|vapi)$/ } ($var->value_as_list_recursive);
5569
5570   # For automake bug#11229.
5571   return unless @vala_sources;
5572
5573   foreach my $vala_file (@vala_sources)
5574     {
5575       my $c_file = $vala_file;
5576       if ($c_file =~ s/(.*)\.vala$/$1.c/)
5577         {
5578           $c_file = "\$(srcdir)/$c_file";
5579           $output_rules .= "$c_file: \$(srcdir)/${derived}_vala.stamp\n"
5580             . "\t\@if test -f \$@; then :; else rm -f \$(srcdir)/${derived}_vala.stamp; fi\n"
5581             . "\t\@if test -f \$@; then :; else \\\n"
5582             . "\t  \$(MAKE) \$(AM_MAKEFLAGS) \$(srcdir)/${derived}_vala.stamp; \\\n"
5583             . "\tfi\n";
5584           $clean_files{$c_file} = MAINTAINER_CLEAN;
5585         }
5586     }
5587
5588   # Add rebuild rules for generated header and vapi files
5589   my $flags = var ($derived . '_VALAFLAGS');
5590   if ($flags)
5591     {
5592       my $lastflag = '';
5593       foreach my $flag ($flags->value_as_list_recursive)
5594         {
5595           if (grep (/$lastflag/, ('-H', '-h', '--header', '--internal-header',
5596                                   '--vapi', '--internal-vapi', '--gir')))
5597             {
5598               my $headerfile = "\$(srcdir)/$flag";
5599               $output_rules .= "$headerfile: \$(srcdir)/${derived}_vala.stamp\n"
5600                 . "\t\@if test -f \$@; then :; else rm -f \$(srcdir)/${derived}_vala.stamp; fi\n"
5601                 . "\t\@if test -f \$@; then :; else \\\n"
5602                 . "\t  \$(MAKE) \$(AM_MAKEFLAGS) \$(srcdir)/${derived}_vala.stamp; \\\n"
5603                 . "\tfi\n";
5604
5605               # valac is not used when building from dist tarballs
5606               # distribute the generated files
5607               push_dist_common ($headerfile);
5608               $clean_files{$headerfile} = MAINTAINER_CLEAN;
5609             }
5610           $lastflag = $flag;
5611         }
5612     }
5613
5614   my $compile = $self->compile;
5615
5616   # Rewrite each occurrence of 'AM_VALAFLAGS' in the compile
5617   # rule into '${derived}_VALAFLAGS' if it exists.
5618   my $val = "${derived}_VALAFLAGS";
5619   $compile =~ s/\(AM_VALAFLAGS\)/\($val\)/
5620     if set_seen ($val);
5621
5622   # VALAFLAGS is a user variable (per GNU Standards),
5623   # it should not be overridden in the Makefile...
5624   check_user_variables 'VALAFLAGS';
5625
5626   my $dirname = dirname ($name);
5627
5628   # Only generate C code, do not run C compiler
5629   $compile .= " -C";
5630
5631   my $verbose = verbose_flag ('VALAC');
5632   my $silent = silent_flag ();
5633   my $stampfile = "\$(srcdir)/${derived}_vala.stamp";
5634
5635   $output_rules .=
5636     "\$(srcdir)/${derived}_vala.stamp: @vala_sources\n".
5637 # Since the C files generated from the vala sources depend on the
5638 # ${derived}_vala.stamp file, we must ensure its timestamp is older than
5639 # those of the C files generated by the valac invocation below (this is
5640 # especially important on systems with sub-second timestamp resolution).
5641 # Thus we need to create the stamp file *before* invoking valac, and to
5642 # move it to its final location only after valac has been invoked.
5643     "\t${silent}rm -f \$\@ && echo stamp > \$\@-t\n".
5644     "\t${verbose}\$(am__cd) \$(srcdir) && $compile @vala_sources\n".
5645     "\t${silent}mv -f \$\@-t \$\@\n";
5646
5647   push_dist_common ($stampfile);
5648
5649   $clean_files{$stampfile} = MAINTAINER_CLEAN;
5650 }
5651
5652 # Add output rules to invoke valac and create stamp file as a witness
5653 # to handle multiple outputs. This function is called after all source
5654 # file processing is done.
5655 sub lang_vala_finish ()
5656 {
5657   my ($self) = @_;
5658
5659   foreach my $prog (keys %known_programs)
5660     {
5661       lang_vala_finish_target ($self, $prog);
5662     }
5663
5664   while (my ($name) = each %known_libraries)
5665     {
5666       lang_vala_finish_target ($self, $name);
5667     }
5668 }
5669
5670 # The built .c files should be cleaned only on maintainer-clean
5671 # as the .c files are distributed. This function is called for each
5672 # .vala source file.
5673 sub lang_vala_target_hook
5674 {
5675   my ($self, $aggregate, $output, $input, %transform) = @_;
5676
5677   $clean_files{$output} = MAINTAINER_CLEAN;
5678 }
5679
5680 # This is a yacc helper which is called whenever we have decided to
5681 # compile a yacc file.
5682 sub lang_yacc_target_hook
5683 {
5684     my ($self, $aggregate, $output, $input, %transform) = @_;
5685
5686     # If some relevant *YFLAGS variable contains the '-d' flag, we'll
5687     # have to to generate special code.
5688     my $yflags_contains_minus_d = 0;
5689
5690     foreach my $pfx ("", "${aggregate}_")
5691       {
5692         my $yflagsvar = var ("${pfx}YFLAGS");
5693         next unless $yflagsvar;
5694         # We cannot work reliably with conditionally-defined YFLAGS.
5695         if ($yflagsvar->has_conditional_contents)
5696           {
5697             msg_var ('unsupported', $yflagsvar,
5698                      "'${pfx}YFLAGS' cannot have conditional contents");
5699           }
5700         else
5701           {
5702             $yflags_contains_minus_d = 1
5703               if grep (/^-d$/, $yflagsvar->value_as_list_recursive);
5704           }
5705       }
5706
5707     if ($yflags_contains_minus_d)
5708       {
5709         # Found a '-d' that applies to the compilation of this file.
5710         # Add a dependency for the generated header file, and arrange
5711         # for that file to be included in the distribution.
5712
5713         # The extension of the output file (e.g., '.c' or '.cxx').
5714         # We'll need it to compute the name of the generated header file.
5715         (my $output_ext = basename ($output)) =~ s/.*(\.[^.]+)$/$1/;
5716
5717         # We know that a yacc input should be turned into either a C or
5718         # C++ output file.  We depend on this fact (here and in yacc.am),
5719         # so check that it really holds.
5720         my $lang = $languages{$extension_map{$output_ext}};
5721         prog_error "invalid output name '$output' for yacc file '$input'"
5722           if (!$lang || ($lang->name ne 'c' && $lang->name ne 'cxx'));
5723
5724         (my $header_ext = $output_ext) =~ s/c/h/g;
5725         # Quote $output_ext in the regexp, so that dots in it are taken
5726         # as literal dots, not as metacharacters.
5727         (my $header = $output) =~ s/\Q$output_ext\E$/$header_ext/;
5728
5729         foreach my $cond (Automake::Rule::define (${header}, 'internal',
5730                                                   RULE_AUTOMAKE, TRUE,
5731                                                   INTERNAL))
5732           {
5733             my $condstr = $cond->subst_string;
5734             $output_rules .=
5735               "$condstr${header}: $output\n"
5736               # Recover from removal of $header
5737               . "$condstr\t\@if test ! -f \$@; then rm -f $output; else :; fi\n"
5738               . "$condstr\t\@if test ! -f \$@; then \$(MAKE) \$(AM_MAKEFLAGS) $output; else :; fi\n";
5739           }
5740         # Distribute the generated file, unless its .y source was
5741         # listed in a nodist_ variable.  (handle_source_transform()
5742         # will set DIST_SOURCE.)
5743         push_dist_common ($header)
5744           if $transform{'DIST_SOURCE'};
5745
5746         # The GNU rules say that yacc/lex output files should be removed
5747         # by maintainer-clean.  However, if the files are not distributed,
5748         # then we want to remove them with "make clean"; otherwise,
5749         # "make distcheck" will fail.
5750         $clean_files{$header} = $transform{'DIST_SOURCE'} ? MAINTAINER_CLEAN : CLEAN;
5751       }
5752     # See the comment above for $HEADER.
5753     $clean_files{$output} = $transform{'DIST_SOURCE'} ? MAINTAINER_CLEAN : CLEAN;
5754 }
5755
5756 # This is a lex helper which is called whenever we have decided to
5757 # compile a lex file.
5758 sub lang_lex_target_hook
5759 {
5760     my ($self, $aggregate, $output, $input, %transform) = @_;
5761     # The GNU rules say that yacc/lex output files should be removed
5762     # by maintainer-clean.  However, if the files are not distributed,
5763     # then we want to remove them with "make clean"; otherwise,
5764     # "make distcheck" will fail.
5765     $clean_files{$output} = $transform{'DIST_SOURCE'} ? MAINTAINER_CLEAN : CLEAN;
5766 }
5767
5768 # This is a helper for both lex and yacc.
5769 sub yacc_lex_finish_helper ()
5770 {
5771   return if defined $language_scratch{'lex-yacc-done'};
5772   $language_scratch{'lex-yacc-done'} = 1;
5773
5774   # FIXME: for now, no line number.
5775   require_conf_file ($configure_ac, FOREIGN, 'ylwrap');
5776   define_variable ('YLWRAP', "$am_config_aux_dir/ylwrap", INTERNAL);
5777 }
5778
5779 sub lang_yacc_finish ()
5780 {
5781   return if defined $language_scratch{'yacc-done'};
5782   $language_scratch{'yacc-done'} = 1;
5783
5784   reject_var 'YACCFLAGS', "'YACCFLAGS' obsolete; use 'YFLAGS' instead";
5785
5786   yacc_lex_finish_helper;
5787 }
5788
5789
5790 sub lang_lex_finish ()
5791 {
5792   return if defined $language_scratch{'lex-done'};
5793   $language_scratch{'lex-done'} = 1;
5794
5795   yacc_lex_finish_helper;
5796 }
5797
5798
5799 # Given a hash table of linker names, pick the name that has the most
5800 # precedence.  This is lame, but something has to have global
5801 # knowledge in order to eliminate the conflict.  Add more linkers as
5802 # required.
5803 sub resolve_linker
5804 {
5805     my (%linkers) = @_;
5806
5807     foreach my $l (qw(GCJLINK OBJCXXLINK CXXLINK F77LINK FCLINK OBJCLINK UPCLINK))
5808     {
5809         return $l if defined $linkers{$l};
5810     }
5811     return 'LINK';
5812 }
5813
5814 # Called to indicate that an extension was used.
5815 sub saw_extension
5816 {
5817     my ($ext) = @_;
5818     $extension_seen{$ext} = 1;
5819 }
5820
5821 # register_language (%ATTRIBUTE)
5822 # ------------------------------
5823 # Register a single language.
5824 # Each %ATTRIBUTE is of the form ATTRIBUTE => VALUE.
5825 sub register_language
5826 {
5827   my (%option) = @_;
5828
5829   # Set the defaults.
5830   $option{'autodep'} = 'no'
5831     unless defined $option{'autodep'};
5832   $option{'linker'} = ''
5833     unless defined $option{'linker'};
5834   $option{'flags'} = []
5835     unless defined $option{'flags'};
5836   $option{'output_extensions'} = sub { return ( '.$(OBJEXT)', '.lo' ) }
5837     unless defined $option{'output_extensions'};
5838   $option{'nodist_specific'} = 0
5839     unless defined $option{'nodist_specific'};
5840
5841   my $lang = new Automake::Language (%option);
5842
5843   # Fill indexes.
5844   $extension_map{$_} = $lang->name foreach @{$lang->extensions};
5845   $languages{$lang->name} = $lang;
5846   my $link = $lang->linker;
5847   if ($link)
5848     {
5849       if (exists $link_languages{$link})
5850         {
5851           prog_error ("'$link' has different definitions in "
5852                       . $lang->name . " and " . $link_languages{$link}->name)
5853             if $lang->link ne $link_languages{$link}->link;
5854         }
5855       else
5856         {
5857           $link_languages{$link} = $lang;
5858         }
5859     }
5860
5861   # Update the pattern of known extensions.
5862   accept_extensions (@{$lang->extensions});
5863
5864   # Update the $suffix_rule map.
5865   foreach my $suffix (@{$lang->extensions})
5866     {
5867       foreach my $dest ($lang->output_extensions->($suffix))
5868         {
5869           register_suffix_rule (INTERNAL, $suffix, $dest);
5870         }
5871     }
5872 }
5873
5874 # derive_suffix ($EXT, $OBJ)
5875 # --------------------------
5876 # This function is used to find a path from a user-specified suffix $EXT
5877 # to $OBJ or to some other suffix we recognize internally, e.g. 'cc'.
5878 sub derive_suffix
5879 {
5880   my ($source_ext, $obj) = @_;
5881
5882   while (! $extension_map{$source_ext}
5883          && $source_ext ne $obj
5884          && exists $suffix_rules->{$source_ext}
5885          && exists $suffix_rules->{$source_ext}{$obj})
5886     {
5887       $source_ext = $suffix_rules->{$source_ext}{$obj}[0];
5888     }
5889
5890   return $source_ext;
5891 }
5892
5893
5894 # Pretty-print something and append to '$output_rules'.
5895 sub pretty_print_rule
5896 {
5897     $output_rules .= makefile_wrap (shift, shift, @_);
5898 }
5899
5900
5901 ################################################################
5902
5903
5904 ## -------------------------------- ##
5905 ## Handling the conditional stack.  ##
5906 ## -------------------------------- ##
5907
5908
5909 # $STRING
5910 # make_conditional_string ($NEGATE, $COND)
5911 # ----------------------------------------
5912 sub make_conditional_string
5913 {
5914   my ($negate, $cond) = @_;
5915   $cond = "${cond}_TRUE"
5916     unless $cond =~ /^TRUE|FALSE$/;
5917   $cond = Automake::Condition::conditional_negate ($cond)
5918     if $negate;
5919   return $cond;
5920 }
5921
5922
5923 my %_am_macro_for_cond =
5924   (
5925   AMDEP => "one of the compiler tests\n"
5926            . "    AC_PROG_CC, AC_PROG_CXX, AC_PROG_OBJC, AC_PROG_OBJCXX,\n"
5927            . "    AM_PROG_AS, AM_PROG_GCJ, AM_PROG_UPC",
5928   am__fastdepCC => 'AC_PROG_CC',
5929   am__fastdepCCAS => 'AM_PROG_AS',
5930   am__fastdepCXX => 'AC_PROG_CXX',
5931   am__fastdepGCJ => 'AM_PROG_GCJ',
5932   am__fastdepOBJC => 'AC_PROG_OBJC',
5933   am__fastdepOBJCXX => 'AC_PROG_OBJCXX',
5934   am__fastdepUPC => 'AM_PROG_UPC'
5935   );
5936
5937 # $COND
5938 # cond_stack_if ($NEGATE, $COND, $WHERE)
5939 # --------------------------------------
5940 sub cond_stack_if
5941 {
5942   my ($negate, $cond, $where) = @_;
5943
5944   if (! $configure_cond{$cond} && $cond !~ /^TRUE|FALSE$/)
5945     {
5946       my $text = "$cond does not appear in AM_CONDITIONAL";
5947       my $scope = US_LOCAL;
5948       if (exists $_am_macro_for_cond{$cond})
5949         {
5950           my $mac = $_am_macro_for_cond{$cond};
5951           $text .= "\n  The usual way to define '$cond' is to add ";
5952           $text .= ($mac =~ / /) ? $mac : "'$mac'";
5953           $text .= "\n  to '$configure_ac' and run 'aclocal' and 'autoconf' again";
5954           # These warnings appear in Automake files (depend2.am),
5955           # so there is no need to display them more than once:
5956           $scope = US_GLOBAL;
5957         }
5958       error $where, $text, uniq_scope => $scope;
5959     }
5960
5961   push (@cond_stack, make_conditional_string ($negate, $cond));
5962
5963   return new Automake::Condition (@cond_stack);
5964 }
5965
5966
5967 # $COND
5968 # cond_stack_else ($NEGATE, $COND, $WHERE)
5969 # ----------------------------------------
5970 sub cond_stack_else
5971 {
5972   my ($negate, $cond, $where) = @_;
5973
5974   if (! @cond_stack)
5975     {
5976       error $where, "else without if";
5977       return FALSE;
5978     }
5979
5980   $cond_stack[$#cond_stack] =
5981     Automake::Condition::conditional_negate ($cond_stack[$#cond_stack]);
5982
5983   # If $COND is given, check against it.
5984   if (defined $cond)
5985     {
5986       $cond = make_conditional_string ($negate, $cond);
5987
5988       error ($where, "else reminder ($negate$cond) incompatible with "
5989              . "current conditional: $cond_stack[$#cond_stack]")
5990         if $cond_stack[$#cond_stack] ne $cond;
5991     }
5992
5993   return new Automake::Condition (@cond_stack);
5994 }
5995
5996
5997 # $COND
5998 # cond_stack_endif ($NEGATE, $COND, $WHERE)
5999 # -----------------------------------------
6000 sub cond_stack_endif
6001 {
6002   my ($negate, $cond, $where) = @_;
6003   my $old_cond;
6004
6005   if (! @cond_stack)
6006     {
6007       error $where, "endif without if";
6008       return TRUE;
6009     }
6010
6011   # If $COND is given, check against it.
6012   if (defined $cond)
6013     {
6014       $cond = make_conditional_string ($negate, $cond);
6015
6016       error ($where, "endif reminder ($negate$cond) incompatible with "
6017              . "current conditional: $cond_stack[$#cond_stack]")
6018         if $cond_stack[$#cond_stack] ne $cond;
6019     }
6020
6021   pop @cond_stack;
6022
6023   return new Automake::Condition (@cond_stack);
6024 }
6025
6026
6027
6028
6029
6030 ## ------------------------ ##
6031 ## Handling the variables.  ##
6032 ## ------------------------ ##
6033
6034
6035 # define_pretty_variable ($VAR, $COND, $WHERE, @VALUE)
6036 # ----------------------------------------------------
6037 # Like define_variable, but the value is a list, and the variable may
6038 # be defined conditionally.  The second argument is the condition
6039 # under which the value should be defined; this should be the empty
6040 # string to define the variable unconditionally.  The third argument
6041 # is a list holding the values to use for the variable.  The value is
6042 # pretty printed in the output file.
6043 sub define_pretty_variable
6044 {
6045     my ($var, $cond, $where, @value) = @_;
6046
6047     if (! vardef ($var, $cond))
6048     {
6049         Automake::Variable::define ($var, VAR_AUTOMAKE, '', $cond, "@value",
6050                                     '', $where, VAR_PRETTY);
6051         rvar ($var)->rdef ($cond)->set_seen;
6052     }
6053 }
6054
6055
6056 # define_variable ($VAR, $VALUE, $WHERE)
6057 # --------------------------------------
6058 # Define a new Automake Makefile variable VAR to VALUE, but only if
6059 # not already defined.
6060 sub define_variable
6061 {
6062     my ($var, $value, $where) = @_;
6063     define_pretty_variable ($var, TRUE, $where, $value);
6064 }
6065
6066
6067 # define_files_variable ($VAR, \@BASENAME, $EXTENSION, $WHERE)
6068 # ------------------------------------------------------------
6069 # Define the $VAR which content is the list of file names composed of
6070 # a @BASENAME and the $EXTENSION.
6071 sub define_files_variable ($\@$$)
6072 {
6073   my ($var, $basename, $extension, $where) = @_;
6074   define_variable ($var,
6075                    join (' ', map { "$_.$extension" } @$basename),
6076                    $where);
6077 }
6078
6079
6080 # Like define_variable, but define a variable to be the configure
6081 # substitution by the same name.
6082 sub define_configure_variable
6083 {
6084   my ($var) = @_;
6085   # Some variables we do not want to output.  For instance it
6086   # would be a bad idea to output `U = @U@` when `@U@` can be
6087   # substituted as `\`.
6088   my $pretty = exists $ignored_configure_vars{$var} ? VAR_SILENT : VAR_ASIS;
6089   Automake::Variable::define ($var, VAR_CONFIGURE, '', TRUE, subst ($var),
6090                               '', $configure_vars{$var}, $pretty);
6091 }
6092
6093
6094 # define_compiler_variable ($LANG)
6095 # --------------------------------
6096 # Define a compiler variable.  We also handle defining the 'LT'
6097 # version of the command when using libtool.
6098 sub define_compiler_variable
6099 {
6100     my ($lang) = @_;
6101
6102     my ($var, $value) = ($lang->compiler, $lang->compile);
6103     my $libtool_tag = '';
6104     $libtool_tag = '--tag=' . $lang->libtool_tag . ' '
6105       if $lang->libtool_tag && exists $libtool_tags{$lang->libtool_tag};
6106     define_variable ($var, $value, INTERNAL);
6107     if (var ('LIBTOOL'))
6108       {
6109         my $verbose = define_verbose_libtool ();
6110         define_variable ("LT$var",
6111                          "\$(LIBTOOL) $verbose $libtool_tag\$(AM_LIBTOOLFLAGS)"
6112                          . " \$(LIBTOOLFLAGS) --mode=compile $value",
6113                          INTERNAL);
6114       }
6115     define_verbose_tagvar ($lang->ccer || 'GEN');
6116 }
6117
6118
6119 sub define_linker_variable
6120 {
6121     my ($lang) = @_;
6122
6123     my $libtool_tag = '';
6124     $libtool_tag = '--tag=' . $lang->libtool_tag . ' '
6125       if $lang->libtool_tag && exists $libtool_tags{$lang->libtool_tag};
6126     # CCLD = $(CC).
6127     define_variable ($lang->lder, $lang->ld, INTERNAL);
6128     # CCLINK = $(CCLD) blah blah...
6129     my $link = '';
6130     if (var ('LIBTOOL'))
6131       {
6132         my $verbose = define_verbose_libtool ();
6133         $link = "\$(LIBTOOL) $verbose $libtool_tag\$(AM_LIBTOOLFLAGS) "
6134                 . "\$(LIBTOOLFLAGS) --mode=link ";
6135       }
6136     define_variable ($lang->linker, $link . $lang->link, INTERNAL);
6137     define_variable ($lang->compiler, $lang, INTERNAL);
6138     define_verbose_tagvar ($lang->lder || 'GEN');
6139 }
6140
6141 sub define_per_target_linker_variable
6142 {
6143   my ($linker, $target) = @_;
6144
6145   # If the user wrote a custom link command, we don't define ours.
6146   return "${target}_LINK"
6147     if set_seen "${target}_LINK";
6148
6149   my $xlink = $linker ? $linker : 'LINK';
6150
6151   my $lang = $link_languages{$xlink};
6152   prog_error "Unknown language for linker variable '$xlink'"
6153     unless $lang;
6154
6155   my $link_command = $lang->link;
6156   if (var 'LIBTOOL')
6157     {
6158       my $libtool_tag = '';
6159       $libtool_tag = '--tag=' . $lang->libtool_tag . ' '
6160         if $lang->libtool_tag && exists $libtool_tags{$lang->libtool_tag};
6161
6162       my $verbose = define_verbose_libtool ();
6163       $link_command =
6164         "\$(LIBTOOL) $verbose $libtool_tag\$(AM_LIBTOOLFLAGS) \$(LIBTOOLFLAGS) "
6165         . "--mode=link " . $link_command;
6166     }
6167
6168   # Rewrite each occurrence of 'AM_$flag' in the link
6169   # command into '${derived}_$flag' if it exists.
6170   my $orig_command = $link_command;
6171   my @flags = (@{$lang->flags}, 'LDFLAGS');
6172   push @flags, 'LIBTOOLFLAGS' if var 'LIBTOOL';
6173   for my $flag (@flags)
6174     {
6175       my $val = "${target}_$flag";
6176       $link_command =~ s/\(AM_$flag\)/\($val\)/
6177         if set_seen ($val);
6178     }
6179
6180   # If the computed command is the same as the generic command, use
6181   # the command linker variable.
6182   return ($lang->linker, $lang->lder)
6183     if $link_command eq $orig_command;
6184
6185   define_variable ("${target}_LINK", $link_command, INTERNAL);
6186   return ("${target}_LINK", $lang->lder);
6187 }
6188
6189 ################################################################
6190
6191 # check_trailing_slash ($WHERE, $LINE)
6192 # ------------------------------------
6193 # Return 1 iff $LINE ends with a slash.
6194 # Might modify $LINE.
6195 sub check_trailing_slash ($\$)
6196 {
6197   my ($where, $line) = @_;
6198
6199   # Ignore '##' lines.
6200   return 0 if $$line =~ /$IGNORE_PATTERN/o;
6201
6202   # Catch and fix a common error.
6203   msg "syntax", $where, "whitespace following trailing backslash"
6204     if $$line =~ s/\\\s+\n$/\\\n/;
6205
6206   return $$line =~ /\\$/;
6207 }
6208
6209
6210 # read_am_file ($AMFILE, $WHERE, $RELDIR)
6211 # ---------------------------------------
6212 # Read Makefile.am and set up %contents.  Simultaneously copy lines
6213 # from Makefile.am into $output_trailer, or define variables as
6214 # appropriate.  NOTE we put rules in the trailer section.  We want
6215 # user rules to come after our generated stuff.
6216 sub read_am_file
6217 {
6218     my ($amfile, $where, $reldir) = @_;
6219     my $canon_reldir = &canonicalize ($reldir);
6220
6221     my $am_file = new Automake::XFile ("< $amfile");
6222     verb "reading $amfile";
6223
6224     # Keep track of the youngest output dependency.
6225     my $mtime = mtime $amfile;
6226     $output_deps_greatest_timestamp = $mtime
6227       if $mtime > $output_deps_greatest_timestamp;
6228
6229     my $spacing = '';
6230     my $comment = '';
6231     my $blank = 0;
6232     my $saw_bk = 0;
6233     my $var_look = VAR_ASIS;
6234
6235     use constant IN_VAR_DEF => 0;
6236     use constant IN_RULE_DEF => 1;
6237     use constant IN_COMMENT => 2;
6238     my $prev_state = IN_RULE_DEF;
6239
6240     while ($_ = $am_file->getline)
6241     {
6242         $where->set ("$amfile:$.");
6243         if (/$IGNORE_PATTERN/o)
6244         {
6245             # Merely delete comments beginning with two hashes.
6246         }
6247         elsif (/$WHITE_PATTERN/o)
6248         {
6249             error $where, "blank line following trailing backslash"
6250               if $saw_bk;
6251             # Stick a single white line before the incoming macro or rule.
6252             $spacing = "\n";
6253             $blank = 1;
6254             # Flush all comments seen so far.
6255             if ($comment ne '')
6256             {
6257                 $output_vars .= $comment;
6258                 $comment = '';
6259             }
6260         }
6261         elsif (/$COMMENT_PATTERN/o)
6262         {
6263             # Stick comments before the incoming macro or rule.  Make
6264             # sure a blank line precedes the first block of comments.
6265             $spacing = "\n" unless $blank;
6266             $blank = 1;
6267             $comment .= $spacing . $_;
6268             $spacing = '';
6269             $prev_state = IN_COMMENT;
6270         }
6271         else
6272         {
6273             last;
6274         }
6275         $saw_bk = check_trailing_slash ($where, $_);
6276     }
6277
6278     # We save the conditional stack on entry, and then check to make
6279     # sure it is the same on exit.  This lets us conditionally include
6280     # other files.
6281     my @saved_cond_stack = @cond_stack;
6282     my $cond = new Automake::Condition (@cond_stack);
6283
6284     my $last_var_name = '';
6285     my $last_var_type = '';
6286     my $last_var_value = '';
6287     my $last_where;
6288     # FIXME: shouldn't use $_ in this loop; it is too big.
6289     while ($_)
6290     {
6291         $where->set ("$amfile:$.");
6292
6293         # Make sure the line is \n-terminated.
6294         chomp;
6295         $_ .= "\n";
6296
6297         # Don't look at MAINTAINER_MODE_TRUE here.  That shouldn't be
6298         # used by users.  @MAINT@ is an anachronism now.
6299         $_ =~ s/\@MAINT\@//g
6300             unless $seen_maint_mode;
6301
6302         my $new_saw_bk = check_trailing_slash ($where, $_);
6303
6304         if ($reldir eq '.')
6305           {
6306             # If present, eat the following '_' or '/', converting
6307             # "%reldir%/foo" and "%canon_reldir%_foo" into plain "foo"
6308             # when $reldir is '.'.
6309             $_ =~ s,%(D|reldir)%/,,g;
6310             $_ =~ s,%(C|canon_reldir)%_,,g;
6311           }
6312         $_ =~ s/%(D|reldir)%/${reldir}/g;
6313         $_ =~ s/%(C|canon_reldir)%/${canon_reldir}/g;
6314
6315         if (/$IGNORE_PATTERN/o)
6316         {
6317             # Merely delete comments beginning with two hashes.
6318
6319             # Keep any backslash from the previous line.
6320             $new_saw_bk = $saw_bk;
6321         }
6322         elsif (/$WHITE_PATTERN/o)
6323         {
6324             # Stick a single white line before the incoming macro or rule.
6325             $spacing = "\n";
6326             error $where, "blank line following trailing backslash"
6327               if $saw_bk;
6328         }
6329         elsif (/$COMMENT_PATTERN/o)
6330         {
6331             error $where, "comment following trailing backslash"
6332               if $saw_bk && $prev_state != IN_COMMENT;
6333
6334             # Stick comments before the incoming macro or rule.
6335             $comment .= $spacing . $_;
6336             $spacing = '';
6337             $prev_state = IN_COMMENT;
6338         }
6339         elsif ($saw_bk)
6340         {
6341             if ($prev_state == IN_RULE_DEF)
6342             {
6343               my $cond = new Automake::Condition @cond_stack;
6344               $output_trailer .= $cond->subst_string;
6345               $output_trailer .= $_;
6346             }
6347             elsif ($prev_state == IN_COMMENT)
6348             {
6349                 # If the line doesn't start with a '#', add it.
6350                 # We do this because a continued comment like
6351                 #   # A = foo \
6352                 #         bar \
6353                 #         baz
6354                 # is not portable.  BSD make doesn't honor
6355                 # escaped newlines in comments.
6356                 s/^#?/#/;
6357                 $comment .= $spacing . $_;
6358             }
6359             else # $prev_state == IN_VAR_DEF
6360             {
6361               $last_var_value .= ' '
6362                 unless $last_var_value =~ /\s$/;
6363               $last_var_value .= $_;
6364
6365               if (!/\\$/)
6366                 {
6367                   Automake::Variable::define ($last_var_name, VAR_MAKEFILE,
6368                                               $last_var_type, $cond,
6369                                               $last_var_value, $comment,
6370                                               $last_where, VAR_ASIS)
6371                     if $cond != FALSE;
6372                   $comment = $spacing = '';
6373                 }
6374             }
6375         }
6376
6377         elsif (/$IF_PATTERN/o)
6378           {
6379             $cond = cond_stack_if ($1, $2, $where);
6380           }
6381         elsif (/$ELSE_PATTERN/o)
6382           {
6383             $cond = cond_stack_else ($1, $2, $where);
6384           }
6385         elsif (/$ENDIF_PATTERN/o)
6386           {
6387             $cond = cond_stack_endif ($1, $2, $where);
6388           }
6389
6390         elsif (/$RULE_PATTERN/o)
6391         {
6392             # Found a rule.
6393             $prev_state = IN_RULE_DEF;
6394
6395             # For now we have to output all definitions of user rules
6396             # and can't diagnose duplicates (see the comment in
6397             # Automake::Rule::define). So we go on and ignore the return value.
6398             Automake::Rule::define ($1, $amfile, RULE_USER, $cond, $where);
6399
6400             check_variable_expansions ($_, $where);
6401
6402             $output_trailer .= $comment . $spacing;
6403             my $cond = new Automake::Condition @cond_stack;
6404             $output_trailer .= $cond->subst_string;
6405             $output_trailer .= $_;
6406             $comment = $spacing = '';
6407         }
6408         elsif (/$ASSIGNMENT_PATTERN/o)
6409         {
6410             # Found a macro definition.
6411             $prev_state = IN_VAR_DEF;
6412             $last_var_name = $1;
6413             $last_var_type = $2;
6414             $last_var_value = $3;
6415             $last_where = $where->clone;
6416             if ($3 ne '' && substr ($3, -1) eq "\\")
6417               {
6418                 # We preserve the '\' because otherwise the long lines
6419                 # that are generated will be truncated by broken
6420                 # 'sed's.
6421                 $last_var_value = $3 . "\n";
6422               }
6423             # Normally we try to output variable definitions in the
6424             # same format they were input.  However, POSIX compliant
6425             # systems are not required to support lines longer than
6426             # 2048 bytes (most notably, some sed implementation are
6427             # limited to 4000 bytes, and sed is used by config.status
6428             # to rewrite Makefile.in into Makefile).  Moreover nobody
6429             # would really write such long lines by hand since it is
6430             # hardly maintainable.  So if a line is longer that 1000
6431             # bytes (an arbitrary limit), assume it has been
6432             # automatically generated by some tools, and flatten the
6433             # variable definition.  Otherwise, keep the variable as it
6434             # as been input.
6435             $var_look = VAR_PRETTY if length ($last_var_value) >= 1000;
6436
6437             if (!/\\$/)
6438               {
6439                 Automake::Variable::define ($last_var_name, VAR_MAKEFILE,
6440                                             $last_var_type, $cond,
6441                                             $last_var_value, $comment,
6442                                             $last_where, $var_look)
6443                   if $cond != FALSE;
6444                 $comment = $spacing = '';
6445                 $var_look = VAR_ASIS;
6446               }
6447         }
6448         elsif (/$INCLUDE_PATTERN/o)
6449         {
6450             my $path = $1;
6451
6452             if ($path =~ s/^\$\(top_srcdir\)\///)
6453               {
6454                 push (@include_stack, "\$\(top_srcdir\)/$path");
6455                 # Distribute any included file.
6456
6457                 # Always use the $(top_srcdir) prefix in DIST_COMMON,
6458                 # otherwise OSF make will implicitly copy the included
6459                 # file in the build tree during "make distdir" to satisfy
6460                 # the dependency.
6461                 # (subdir-am-cond.sh and subdir-ac-cond.sh will fail)
6462                 push_dist_common ("\$\(top_srcdir\)/$path");
6463               }
6464             else
6465               {
6466                 $path =~ s/\$\(srcdir\)\///;
6467                 push (@include_stack, "\$\(srcdir\)/$path");
6468                 # Always use the $(srcdir) prefix in DIST_COMMON,
6469                 # otherwise OSF make will implicitly copy the included
6470                 # file in the build tree during "make distdir" to satisfy
6471                 # the dependency.
6472                 # (subdir-am-cond.sh and subdir-ac-cond.sh will fail)
6473                 push_dist_common ("\$\(srcdir\)/$path");
6474                 $path = $relative_dir . "/" . $path if $relative_dir ne '.';
6475               }
6476             my $new_reldir = File::Spec->abs2rel ($path, $relative_dir);
6477             $new_reldir = '.' if $new_reldir !~ s,/[^/]*$,,;
6478             $where->push_context ("'$path' included from here");
6479             read_am_file ($path, $where, $new_reldir);
6480             $where->pop_context;
6481         }
6482         else
6483         {
6484             # This isn't an error; it is probably a continued rule.
6485             # In fact, this is what we assume.
6486             $prev_state = IN_RULE_DEF;
6487             check_variable_expansions ($_, $where);
6488             $output_trailer .= $comment . $spacing;
6489             my $cond = new Automake::Condition @cond_stack;
6490             $output_trailer .= $cond->subst_string;
6491             $output_trailer .= $_;
6492             $comment = $spacing = '';
6493             error $where, "'#' comment at start of rule is unportable"
6494               if $_ =~ /^\t\s*\#/;
6495         }
6496
6497         $saw_bk = $new_saw_bk;
6498         $_ = $am_file->getline;
6499     }
6500
6501     $output_trailer .= $comment;
6502
6503     error ($where, "trailing backslash on last line")
6504       if $saw_bk;
6505
6506     error ($where, (@cond_stack ? "unterminated conditionals: @cond_stack"
6507                     : "too many conditionals closed in include file"))
6508       if "@saved_cond_stack" ne "@cond_stack";
6509 }
6510
6511
6512 # A helper for read_main_am_file which initializes configure variables
6513 # and variables from header-vars.am.
6514 sub define_standard_variables ()
6515 {
6516   my $saved_output_vars = $output_vars;
6517   my ($comments, undef, $rules) =
6518     file_contents_internal (1, "$libdir/am/header-vars.am",
6519                             new Automake::Location);
6520
6521   foreach my $var (sort keys %configure_vars)
6522     {
6523       define_configure_variable ($var);
6524     }
6525
6526   $output_vars .= $comments . $rules;
6527 }
6528
6529
6530 # read_main_am_file ($MAKEFILE_AM, $MAKEFILE_IN)
6531 # ----------------------------------------------
6532 sub read_main_am_file
6533 {
6534     my ($amfile, $infile) = @_;
6535
6536     # This supports the strange variable tricks we are about to play.
6537     prog_error ("variable defined before read_main_am_file\n" . variables_dump ())
6538       if (scalar (variables) > 0);
6539
6540     # Generate copyright header for generated Makefile.in.
6541     # We do discard the output of predefined variables, handled below.
6542     $output_vars = ("# " . basename ($infile) . " generated by automake "
6543                    . $VERSION . " from " . basename ($amfile) . ".\n");
6544     $output_vars .= '# ' . subst ('configure_input') . "\n";
6545     $output_vars .= $gen_copyright;
6546
6547     # We want to predefine as many variables as possible.  This lets
6548     # the user set them with '+=' in Makefile.am.
6549     define_standard_variables;
6550
6551     # Read user file, which might override some of our values.
6552     read_am_file ($amfile, new Automake::Location, '.');
6553 }
6554
6555
6556
6557 ################################################################
6558
6559 # $STRING
6560 # flatten ($ORIGINAL_STRING)
6561 # --------------------------
6562 sub flatten
6563 {
6564   $_ = shift;
6565
6566   s/\\\n//somg;
6567   s/\s+/ /g;
6568   s/^ //;
6569   s/ $//;
6570
6571   return $_;
6572 }
6573
6574
6575 # transform_token ($TOKEN, \%PAIRS, $KEY)
6576 # ---------------------------------------
6577 # Return the value associated to $KEY in %PAIRS, as used on $TOKEN
6578 # (which should be ?KEY? or any of the special %% requests)..
6579 sub transform_token ($\%$)
6580 {
6581   my ($token, $transform, $key) = @_;
6582   my $res = $transform->{$key};
6583   prog_error "Unknown key '$key' in '$token'" unless defined $res;
6584   return $res;
6585 }
6586
6587
6588 # transform ($TOKEN, \%PAIRS)
6589 # ---------------------------
6590 # If ($TOKEN, $VAL) is in %PAIRS:
6591 #   - replaces %KEY% with $VAL,
6592 #   - enables/disables ?KEY? and ?!KEY?,
6593 #   - replaces %?KEY% with TRUE or FALSE.
6594 sub transform ($\%)
6595 {
6596   my ($token, $transform) = @_;
6597
6598   # %KEY%.
6599   # Must be before the following pattern to exclude the case
6600   # when there is neither IFTRUE nor IFFALSE.
6601   if ($token =~ /^%([\w\-]+)%$/)
6602     {
6603       return transform_token ($token, %$transform, $1);
6604     }
6605   # %?KEY%.
6606   elsif ($token =~ /^%\?([\w\-]+)%$/)
6607     {
6608       return transform_token ($token, %$transform, $1) ? 'TRUE' : 'FALSE';
6609     }
6610   # ?KEY? and ?!KEY?.
6611   elsif ($token =~ /^ \? (!?) ([\w\-]+) \? $/x)
6612     {
6613       my $neg = ($1 eq '!') ? 1 : 0;
6614       my $val = transform_token ($token, %$transform, $2);
6615       return (!!$val == $neg) ? '##%' : '';
6616     }
6617   else
6618     {
6619       prog_error "Unknown request format: $token";
6620     }
6621 }
6622
6623 # $TEXT
6624 # preprocess_file ($MAKEFILE, [%TRANSFORM])
6625 # -----------------------------------------
6626 # Load a $MAKEFILE, apply the %TRANSFORM, and return the result.
6627 # No extra parsing or post-processing is done (i.e., recognition of
6628 # rules declaration or of make variables definitions).
6629 sub preprocess_file
6630 {
6631   my ($file, %transform) = @_;
6632
6633   # Complete %transform with global options.
6634   # Note that %transform goes last, so it overrides global options.
6635   %transform = ( 'MAINTAINER-MODE'
6636                  => $seen_maint_mode ? subst ('MAINTAINER_MODE_TRUE') : '',
6637
6638                  'XZ'          => !! option 'dist-xz',
6639                  'LZIP'        => !! option 'dist-lzip',
6640                  'BZIP2'       => !! option 'dist-bzip2',
6641                  'COMPRESS'    => !! option 'dist-tarZ',
6642                  'GZIP'        =>  ! option 'no-dist-gzip',
6643                  'SHAR'        => !! option 'dist-shar',
6644                  'ZIP'         => !! option 'dist-zip',
6645
6646                  'INSTALL-INFO' =>  ! option 'no-installinfo',
6647                  'INSTALL-MAN'  =>  ! option 'no-installman',
6648                  'CK-NEWS'      => !! option 'check-news',
6649
6650                  'SUBDIRS'      => !! var ('SUBDIRS'),
6651                  'TOPDIR_P'     => $relative_dir eq '.',
6652
6653                  'BUILD'    => ($seen_canonical >= AC_CANONICAL_BUILD),
6654                  'HOST'     => ($seen_canonical >= AC_CANONICAL_HOST),
6655                  'TARGET'   => ($seen_canonical >= AC_CANONICAL_TARGET),
6656
6657                  'LIBTOOL'      => !! var ('LIBTOOL'),
6658                  'NONLIBTOOL'   => 1,
6659                 %transform);
6660
6661   if (! defined ($_ = $am_file_cache{$file}))
6662     {
6663       verb "reading $file";
6664       # Swallow the whole file.
6665       my $fc_file = new Automake::XFile "< $file";
6666       my $saved_dollar_slash = $/;
6667       undef $/;
6668       $_ = $fc_file->getline;
6669       $/ = $saved_dollar_slash;
6670       $fc_file->close;
6671       # Remove ##-comments.
6672       # Besides we don't need more than two consecutive new-lines.
6673       s/(?:$IGNORE_PATTERN|(?<=\n\n)\n+)//gom;
6674       # Remember the contents of the just-read file.
6675       $am_file_cache{$file} = $_;
6676     }
6677
6678   # Substitute Automake template tokens.
6679   s/(?: % \?? [\w\-]+ %
6680       | \? !? [\w\-]+ \?
6681     )/transform($&, %transform)/gex;
6682   # transform() may have added some ##%-comments to strip.
6683   # (we use '##%' instead of '##' so we can distinguish ##%##%##% from
6684   # ####### and do not remove the latter.)
6685   s/^[ \t]*(?:##%)+.*\n//gm;
6686
6687   return $_;
6688 }
6689
6690
6691 # @PARAGRAPHS
6692 # make_paragraphs ($MAKEFILE, [%TRANSFORM])
6693 # -----------------------------------------
6694 # Load a $MAKEFILE, apply the %TRANSFORM, and return it as a list of
6695 # paragraphs.
6696 sub make_paragraphs
6697 {
6698   my ($file, %transform) = @_;
6699   $transform{FIRST} = !$transformed_files{$file};
6700   $transformed_files{$file} = 1;
6701
6702   my @lines = split /(?<!\\)\n/, preprocess_file ($file, %transform);
6703   my @res;
6704
6705   while (defined ($_ = shift @lines))
6706     {
6707       my $paragraph = $_;
6708       # If we are a rule, eat as long as we start with a tab.
6709       if (/$RULE_PATTERN/smo)
6710         {
6711           while (defined ($_ = shift @lines) && $_ =~ /^\t/)
6712             {
6713               $paragraph .= "\n$_";
6714             }
6715           unshift (@lines, $_);
6716         }
6717
6718       # If we are a comments, eat as much comments as you can.
6719       elsif (/$COMMENT_PATTERN/smo)
6720         {
6721           while (defined ($_ = shift @lines)
6722                  && $_ =~ /$COMMENT_PATTERN/smo)
6723             {
6724               $paragraph .= "\n$_";
6725             }
6726           unshift (@lines, $_);
6727         }
6728
6729       push @res, $paragraph;
6730     }
6731
6732   return @res;
6733 }
6734
6735
6736
6737 # ($COMMENT, $VARIABLES, $RULES)
6738 # file_contents_internal ($IS_AM, $FILE, $WHERE, [%TRANSFORM])
6739 # ------------------------------------------------------------
6740 # Return contents of a file from $libdir/am, automatically skipping
6741 # macros or rules which are already known. $IS_AM iff the caller is
6742 # reading an Automake file (as opposed to the user's Makefile.am).
6743 sub file_contents_internal
6744 {
6745     my ($is_am, $file, $where, %transform) = @_;
6746
6747     $where->set ($file);
6748
6749     my $result_vars = '';
6750     my $result_rules = '';
6751     my $comment = '';
6752     my $spacing = '';
6753
6754     # The following flags are used to track rules spanning across
6755     # multiple paragraphs.
6756     my $is_rule = 0;            # 1 if we are processing a rule.
6757     my $discard_rule = 0;       # 1 if the current rule should not be output.
6758
6759     # We save the conditional stack on entry, and then check to make
6760     # sure it is the same on exit.  This lets us conditionally include
6761     # other files.
6762     my @saved_cond_stack = @cond_stack;
6763     my $cond = new Automake::Condition (@cond_stack);
6764
6765     foreach (make_paragraphs ($file, %transform))
6766     {
6767         # FIXME: no line number available.
6768         $where->set ($file);
6769
6770         # Sanity checks.
6771         error $where, "blank line following trailing backslash:\n$_"
6772           if /\\$/;
6773         error $where, "comment following trailing backslash:\n$_"
6774           if /\\#/;
6775
6776         if (/^$/)
6777         {
6778             $is_rule = 0;
6779             # Stick empty line before the incoming macro or rule.
6780             $spacing = "\n";
6781         }
6782         elsif (/$COMMENT_PATTERN/mso)
6783         {
6784             $is_rule = 0;
6785             # Stick comments before the incoming macro or rule.
6786             $comment = "$_\n";
6787         }
6788
6789         # Handle inclusion of other files.
6790         elsif (/$INCLUDE_PATTERN/o)
6791         {
6792             if ($cond != FALSE)
6793               {
6794                 my $file = ($is_am ? "$libdir/am/" : '') . $1;
6795                 $where->push_context ("'$file' included from here");
6796                 # N-ary '.=' fails.
6797                 my ($com, $vars, $rules)
6798                   = file_contents_internal ($is_am, $file, $where, %transform);
6799                 $where->pop_context;
6800                 $comment .= $com;
6801                 $result_vars .= $vars;
6802                 $result_rules .= $rules;
6803               }
6804         }
6805
6806         # Handling the conditionals.
6807         elsif (/$IF_PATTERN/o)
6808           {
6809             $cond = cond_stack_if ($1, $2, $file);
6810           }
6811         elsif (/$ELSE_PATTERN/o)
6812           {
6813             $cond = cond_stack_else ($1, $2, $file);
6814           }
6815         elsif (/$ENDIF_PATTERN/o)
6816           {
6817             $cond = cond_stack_endif ($1, $2, $file);
6818           }
6819
6820         # Handling rules.
6821         elsif (/$RULE_PATTERN/mso)
6822         {
6823           $is_rule = 1;
6824           $discard_rule = 0;
6825           # Separate relationship from optional actions: the first
6826           # `new-line tab" not preceded by backslash (continuation
6827           # line).
6828           my $paragraph = $_;
6829           /^(.*?)(?:(?<!\\)\n(\t.*))?$/s;
6830           my ($relationship, $actions) = ($1, $2 || '');
6831
6832           # Separate targets from dependencies: the first colon.
6833           $relationship =~ /^([^:]+\S+) *: *(.*)$/som;
6834           my ($targets, $dependencies) = ($1, $2);
6835           # Remove the escaped new lines.
6836           # I don't know why, but I have to use a tmp $flat_deps.
6837           my $flat_deps = flatten ($dependencies);
6838           my @deps = split (' ', $flat_deps);
6839
6840           foreach (split (' ', $targets))
6841             {
6842               # FIXME: 1. We are not robust to people defining several targets
6843               # at once, only some of them being in %dependencies.  The
6844               # actions from the targets in %dependencies are usually generated
6845               # from the content of %actions, but if some targets in $targets
6846               # are not in %dependencies the ELSE branch will output
6847               # a rule for all $targets (i.e. the targets which are both
6848               # in %dependencies and $targets will have two rules).
6849
6850               # FIXME: 2. The logic here is not able to output a
6851               # multi-paragraph rule several time (e.g. for each condition
6852               # it is defined for) because it only knows the first paragraph.
6853
6854               # FIXME: 3. We are not robust to people defining a subset
6855               # of a previously defined "multiple-target" rule.  E.g.
6856               # 'foo:' after 'foo bar:'.
6857
6858               # Output only if not in FALSE.
6859               if (defined $dependencies{$_} && $cond != FALSE)
6860                 {
6861                   depend ($_, @deps);
6862                   register_action ($_, $actions);
6863                 }
6864               else
6865                 {
6866                   # Free-lance dependency.  Output the rule for all the
6867                   # targets instead of one by one.
6868                   my @undefined_conds =
6869                     Automake::Rule::define ($targets, $file,
6870                                             $is_am ? RULE_AUTOMAKE : RULE_USER,
6871                                             $cond, $where);
6872                   for my $undefined_cond (@undefined_conds)
6873                     {
6874                       my $condparagraph = $paragraph;
6875                       $condparagraph =~ s/^/$undefined_cond->subst_string/gme;
6876                       $result_rules .= "$spacing$comment$condparagraph\n";
6877                     }
6878                   if (scalar @undefined_conds == 0)
6879                     {
6880                       # Remember to discard next paragraphs
6881                       # if they belong to this rule.
6882                       # (but see also FIXME: #2 above.)
6883                       $discard_rule = 1;
6884                     }
6885                   $comment = $spacing = '';
6886                   last;
6887                 }
6888             }
6889         }
6890
6891         elsif (/$ASSIGNMENT_PATTERN/mso)
6892         {
6893             my ($var, $type, $val) = ($1, $2, $3);
6894             error $where, "variable '$var' with trailing backslash"
6895               if /\\$/;
6896
6897             $is_rule = 0;
6898
6899             Automake::Variable::define ($var,
6900                                         $is_am ? VAR_AUTOMAKE : VAR_MAKEFILE,
6901                                         $type, $cond, $val, $comment, $where,
6902                                         VAR_ASIS)
6903               if $cond != FALSE;
6904
6905             $comment = $spacing = '';
6906         }
6907         else
6908         {
6909             # This isn't an error; it is probably some tokens which
6910             # configure is supposed to replace, such as '@SET-MAKE@',
6911             # or some part of a rule cut by an if/endif.
6912             if (! $cond->false && ! ($is_rule && $discard_rule))
6913               {
6914                 s/^/$cond->subst_string/gme;
6915                 $result_rules .= "$spacing$comment$_\n";
6916               }
6917             $comment = $spacing = '';
6918         }
6919     }
6920
6921     error ($where, @cond_stack ?
6922            "unterminated conditionals: @cond_stack" :
6923            "too many conditionals closed in include file")
6924       if "@saved_cond_stack" ne "@cond_stack";
6925
6926     return ($comment, $result_vars, $result_rules);
6927 }
6928
6929
6930 # $CONTENTS
6931 # file_contents ($BASENAME, $WHERE, [%TRANSFORM])
6932 # -----------------------------------------------
6933 # Return contents of a file from $libdir/am, automatically skipping
6934 # macros or rules which are already known.
6935 sub file_contents
6936 {
6937     my ($basename, $where, %transform) = @_;
6938     my ($comments, $variables, $rules) =
6939       file_contents_internal (1, "$libdir/am/$basename.am", $where,
6940                               %transform);
6941     return "$comments$variables$rules";
6942 }
6943
6944
6945 # @PREFIX
6946 # am_primary_prefixes ($PRIMARY, $CAN_DIST, @PREFIXES)
6947 # ----------------------------------------------------
6948 # Find all variable prefixes that are used for install directories.  A
6949 # prefix 'zar' qualifies iff:
6950 #
6951 # * 'zardir' is a variable.
6952 # * 'zar_PRIMARY' is a variable.
6953 #
6954 # As a side effect, it looks for misspellings.  It is an error to have
6955 # a variable ending in a "reserved" suffix whose prefix is unknown, e.g.
6956 # "bni_PROGRAMS".  However, unusual prefixes are allowed if a variable
6957 # of the same name (with "dir" appended) exists.  For instance, if the
6958 # variable "zardir" is defined, then "zar_PROGRAMS" becomes valid.
6959 # This is to provide a little extra flexibility in those cases which
6960 # need it.
6961 sub am_primary_prefixes
6962 {
6963   my ($primary, $can_dist, @prefixes) = @_;
6964
6965   local $_;
6966   my %valid = map { $_ => 0 } @prefixes;
6967   $valid{'EXTRA'} = 0;
6968   foreach my $var (variables $primary)
6969     {
6970       # Automake is allowed to define variables that look like primaries
6971       # but which aren't.  E.g. INSTALL_sh_DATA.
6972       # Autoconf can also define variables like INSTALL_DATA, so
6973       # ignore all configure variables (at least those which are not
6974       # redefined in Makefile.am).
6975       # FIXME: We should make sure that these variables are not
6976       # conditionally defined (or else adjust the condition below).
6977       my $def = $var->def (TRUE);
6978       next if $def && $def->owner != VAR_MAKEFILE;
6979
6980       my $varname = $var->name;
6981
6982       if ($varname =~ /^(nobase_)?(dist_|nodist_)?(.*)_[[:alnum:]]+$/)
6983         {
6984           my ($base, $dist, $X) = ($1 || '', $2 || '', $3 || '');
6985           if ($dist ne '' && ! $can_dist)
6986             {
6987               err_var ($var,
6988                        "invalid variable '$varname': 'dist' is forbidden");
6989             }
6990           # Standard directories must be explicitly allowed.
6991           elsif (! defined $valid{$X} && exists $standard_prefix{$X})
6992             {
6993               err_var ($var,
6994                        "'${X}dir' is not a legitimate directory " .
6995                        "for '$primary'");
6996             }
6997           # A not explicitly valid directory is allowed if Xdir is defined.
6998           elsif (! defined $valid{$X} &&
6999                  $var->requires_variables ("'$varname' is used", "${X}dir"))
7000             {
7001               # Nothing to do.  Any error message has been output
7002               # by $var->requires_variables.
7003             }
7004           else
7005             {
7006               # Ensure all extended prefixes are actually used.
7007               $valid{"$base$dist$X"} = 1;
7008             }
7009         }
7010       else
7011         {
7012           prog_error "unexpected variable name: $varname";
7013         }
7014     }
7015
7016   # Return only those which are actually defined.
7017   return sort grep { var ($_ . '_' . $primary) } keys %valid;
7018 }
7019
7020
7021 # am_install_var (-OPTION..., file, HOW, where...)
7022 # ------------------------------------------------
7023 #
7024 # Handle 'where_HOW' variable magic.  Does all lookups, generates
7025 # install code, and possibly generates code to define the primary
7026 # variable.  The first argument is the name of the .am file to munge,
7027 # the second argument is the primary variable (e.g. HEADERS), and all
7028 # subsequent arguments are possible installation locations.
7029 #
7030 # Returns list of [$location, $value] pairs, where
7031 # $value's are the values in all where_HOW variable, and $location
7032 # there associated location (the place here their parent variables were
7033 # defined).
7034 #
7035 # FIXME: this should be rewritten to be cleaner.  It should be broken
7036 # up into multiple functions.
7037 #
7038 sub am_install_var
7039 {
7040   my (@args) = @_;
7041
7042   my $do_require = 1;
7043   my $can_dist = 0;
7044   my $default_dist = 0;
7045   while (@args)
7046     {
7047       if ($args[0] eq '-noextra')
7048         {
7049           $do_require = 0;
7050         }
7051       elsif ($args[0] eq '-candist')
7052         {
7053           $can_dist = 1;
7054         }
7055       elsif ($args[0] eq '-defaultdist')
7056         {
7057           $default_dist = 1;
7058           $can_dist = 1;
7059         }
7060       elsif ($args[0] !~ /^-/)
7061         {
7062           last;
7063         }
7064       shift (@args);
7065     }
7066
7067   my ($file, $primary, @prefix) = @args;
7068
7069   # Now that configure substitutions are allowed in where_HOW
7070   # variables, it is an error to actually define the primary.  We
7071   # allow 'JAVA', as it is customarily used to mean the Java
7072   # interpreter.  This is but one of several Java hacks.  Similarly,
7073   # 'PYTHON' is customarily used to mean the Python interpreter.
7074   reject_var $primary, "'$primary' is an anachronism"
7075     unless $primary eq 'JAVA' || $primary eq 'PYTHON';
7076
7077   # Get the prefixes which are valid and actually used.
7078   @prefix = am_primary_prefixes ($primary, $can_dist, @prefix);
7079
7080   # If a primary includes a configure substitution, then the EXTRA_
7081   # form is required.  Otherwise we can't properly do our job.
7082   my $require_extra;
7083
7084   my @used = ();
7085   my @result = ();
7086
7087   foreach my $X (@prefix)
7088     {
7089       my $nodir_name = $X;
7090       my $one_name = $X . '_' . $primary;
7091       my $one_var = var $one_name;
7092
7093       my $strip_subdir = 1;
7094       # If subdir prefix should be preserved, do so.
7095       if ($nodir_name =~ /^nobase_/)
7096         {
7097           $strip_subdir = 0;
7098           $nodir_name =~ s/^nobase_//;
7099         }
7100
7101       # If files should be distributed, do so.
7102       my $dist_p = 0;
7103       if ($can_dist)
7104         {
7105           $dist_p = (($default_dist && $nodir_name !~ /^nodist_/)
7106                      || (! $default_dist && $nodir_name =~ /^dist_/));
7107           $nodir_name =~ s/^(dist|nodist)_//;
7108         }
7109
7110
7111       # Use the location of the currently processed variable.
7112       # We are not processing a particular condition, so pick the first
7113       # available.
7114       my $tmpcond = $one_var->conditions->one_cond;
7115       my $where = $one_var->rdef ($tmpcond)->location->clone;
7116
7117       # Append actual contents of where_PRIMARY variable to
7118       # @result, skipping @substitutions@.
7119       foreach my $locvals ($one_var->value_as_list_recursive (location => 1))
7120         {
7121           my ($loc, $value) = @$locvals;
7122           # Skip configure substitutions.
7123           if ($value =~ /^\@.*\@$/)
7124             {
7125               if ($nodir_name eq 'EXTRA')
7126                 {
7127                   error ($where,
7128                          "'$one_name' contains configure substitution, "
7129                          . "but shouldn't");
7130                 }
7131               # Check here to make sure variables defined in
7132               # configure.ac do not imply that EXTRA_PRIMARY
7133               # must be defined.
7134               elsif (! defined $configure_vars{$one_name})
7135                 {
7136                   $require_extra = $one_name
7137                     if $do_require;
7138                 }
7139             }
7140           else
7141             {
7142               # Strip any $(EXEEXT) suffix the user might have added,
7143               # or this will confuse handle_source_transform() and
7144               # check_canonical_spelling().
7145               # We'll add $(EXEEXT) back later anyway.
7146               # Do it here rather than in handle_programs so the
7147               # uniquifying at the end of this function works.
7148               ${$locvals}[1] =~ s/\$\(EXEEXT\)$//
7149                 if $primary eq 'PROGRAMS';
7150
7151               push (@result, $locvals);
7152             }
7153         }
7154       # A blatant hack: we rewrite each _PROGRAMS primary to include
7155       # EXEEXT.
7156       append_exeext { 1 } $one_name
7157         if $primary eq 'PROGRAMS';
7158       # "EXTRA" shouldn't be used when generating clean targets,
7159       # all, or install targets.  We used to warn if EXTRA_FOO was
7160       # defined uselessly, but this was annoying.
7161       next
7162         if $nodir_name eq 'EXTRA';
7163
7164       if ($nodir_name eq 'check')
7165         {
7166           push (@check, '$(' . $one_name . ')');
7167         }
7168       else
7169         {
7170           push (@used, '$(' . $one_name . ')');
7171         }
7172
7173       # Is this to be installed?
7174       my $install_p = $nodir_name ne 'noinst' && $nodir_name ne 'check';
7175
7176       # If so, with install-exec? (or install-data?).
7177       my $exec_p = ($nodir_name =~ /$EXEC_DIR_PATTERN/o);
7178
7179       my $check_options_p = $install_p && !! option 'std-options';
7180
7181       # Use the location of the currently processed variable as context.
7182       $where->push_context ("while processing '$one_name'");
7183
7184       # The variable containing all files to distribute.
7185       my $distvar = "\$($one_name)";
7186       $distvar = shadow_unconditionally ($one_name, $where)
7187         if ($dist_p && $one_var->has_conditional_contents);
7188
7189       # Singular form of $PRIMARY.
7190       (my $one_primary = $primary) =~ s/S$//;
7191       $output_rules .= file_contents ($file, $where,
7192                                       PRIMARY     => $primary,
7193                                       ONE_PRIMARY => $one_primary,
7194                                       DIR         => $X,
7195                                       NDIR        => $nodir_name,
7196                                       BASE        => $strip_subdir,
7197                                       EXEC        => $exec_p,
7198                                       INSTALL     => $install_p,
7199                                       DIST        => $dist_p,
7200                                       DISTVAR     => $distvar,
7201                                       'CK-OPTS'   => $check_options_p);
7202     }
7203
7204   # The JAVA variable is used as the name of the Java interpreter.
7205   # The PYTHON variable is used as the name of the Python interpreter.
7206   if (@used && $primary ne 'JAVA' && $primary ne 'PYTHON')
7207     {
7208       # Define it.
7209       define_pretty_variable ($primary, TRUE, INTERNAL, @used);
7210       $output_vars .= "\n";
7211     }
7212
7213   err_var ($require_extra,
7214            "'$require_extra' contains configure substitution,\n"
7215            . "but 'EXTRA_$primary' not defined")
7216     if ($require_extra && ! var ('EXTRA_' . $primary));
7217
7218   # Push here because PRIMARY might be configure time determined.
7219   push (@all, '$(' . $primary . ')')
7220     if @used && $primary ne 'JAVA' && $primary ne 'PYTHON';
7221
7222   # Make the result unique.  This lets the user use conditionals in
7223   # a natural way, but still lets us program lazily -- we don't have
7224   # to worry about handling a particular object more than once.
7225   # We will keep only one location per object.
7226   my %result = ();
7227   for my $pair (@result)
7228     {
7229       my ($loc, $val) = @$pair;
7230       $result{$val} = $loc;
7231     }
7232   my @l = sort keys %result;
7233   return map { [$result{$_}->clone, $_] } @l;
7234 }
7235
7236
7237 ################################################################
7238
7239 # Each key in this hash is the name of a directory holding a
7240 # Makefile.in.  These variables are local to 'is_make_dir'.
7241 my %make_dirs = ();
7242 my $make_dirs_set = 0;
7243
7244 # is_make_dir ($DIRECTORY)
7245 # ------------------------
7246 sub is_make_dir
7247 {
7248     my ($dir) = @_;
7249     if (! $make_dirs_set)
7250     {
7251         foreach my $iter (@configure_input_files)
7252         {
7253             $make_dirs{dirname ($iter)} = 1;
7254         }
7255         # We also want to notice Makefile.in's.
7256         foreach my $iter (@other_input_files)
7257         {
7258             if ($iter =~ /Makefile\.in$/)
7259             {
7260                 $make_dirs{dirname ($iter)} = 1;
7261             }
7262         }
7263         $make_dirs_set = 1;
7264     }
7265     return defined $make_dirs{$dir};
7266 }
7267
7268 ################################################################
7269
7270 # Find the aux dir.  This should match the algorithm used by
7271 # ./configure. (See the Autoconf documentation for for
7272 # AC_CONFIG_AUX_DIR.)
7273 sub locate_aux_dir ()
7274 {
7275   if (! $config_aux_dir_set_in_configure_ac)
7276     {
7277       # The default auxiliary directory is the first
7278       # of ., .., or ../.. that contains install-sh.
7279       # Assume . if install-sh doesn't exist yet.
7280       for my $dir (qw (. .. ../..))
7281         {
7282           if (-f "$dir/install-sh")
7283             {
7284               $config_aux_dir = $dir;
7285               last;
7286             }
7287         }
7288       $config_aux_dir = '.' unless $config_aux_dir;
7289     }
7290   # Avoid unsightly '/.'s.
7291   $am_config_aux_dir =
7292     '$(top_srcdir)' . ($config_aux_dir eq '.' ? "" : "/$config_aux_dir");
7293   $am_config_aux_dir =~ s,/*$,,;
7294 }
7295
7296
7297 # push_required_file ($DIR, $FILE, $FULLFILE)
7298 # -------------------------------------------
7299 # Push the given file onto DIST_COMMON.
7300 sub push_required_file
7301 {
7302   my ($dir, $file, $fullfile) = @_;
7303
7304   # If the file to be distributed is in the same directory of the
7305   # currently processed Makefile.am, then we want to distribute it
7306   # from this same Makefile.am.
7307   if ($dir eq $relative_dir)
7308     {
7309       push_dist_common ($file);
7310     }
7311   # This is needed to allow a construct in a non-top-level Makefile.am
7312   # to require a file in the build-aux directory (see at least the test
7313   # script 'test-driver-is-distributed.sh').  This is related to the
7314   # automake bug#9546.  Note that the use of $config_aux_dir instead
7315   # of $am_config_aux_dir here is deliberate and necessary.
7316   elsif ($dir eq $config_aux_dir)
7317     {
7318       push_dist_common ("$am_config_aux_dir/$file");
7319     }
7320   # FIXME: another spacial case, for AC_LIBOBJ/AC_LIBSOURCE support.
7321   # We probably need some refactoring of this function and its callers,
7322   # to have a more explicit and systematic handling of all the special
7323   # cases; but, since there are only two of them, this is low-priority
7324   # ATM.
7325   elsif ($config_libobj_dir && $dir eq $config_libobj_dir)
7326     {
7327       # Avoid unsightly '/.'s.
7328       my $am_config_libobj_dir =
7329         '$(top_srcdir)' .
7330         ($config_libobj_dir eq '.' ? "" : "/$config_libobj_dir");
7331       $am_config_libobj_dir =~ s|/*$||;
7332       push_dist_common ("$am_config_libobj_dir/$file");
7333     }
7334   elsif ($relative_dir eq '.' && ! is_make_dir ($dir))
7335     {
7336       # If we are doing the topmost directory, and the file is in a
7337       # subdir which does not have a Makefile, then we distribute it
7338       # here.
7339
7340       # If a required file is above the source tree, it is important
7341       # to prefix it with '$(srcdir)' so that no VPATH search is
7342       # performed.  Otherwise problems occur with Make implementations
7343       # that rewrite and simplify rules whose dependencies are found in a
7344       # VPATH location.  Here is an example with OSF1/Tru64 Make.
7345       #
7346       #   % cat Makefile
7347       #   VPATH = sub
7348       #   distdir: ../a
7349       #           echo ../a
7350       #   % ls
7351       #   Makefile a
7352       #   % make
7353       #   echo a
7354       #   a
7355       #
7356       # Dependency '../a' was found in 'sub/../a', but this make
7357       # implementation simplified it as 'a'.  (Note that the sub/
7358       # directory does not even exist.)
7359       #
7360       # This kind of VPATH rewriting seems hard to cancel.  The
7361       # distdir.am hack against VPATH rewriting works only when no
7362       # simplification is done, i.e., for dependencies which are in
7363       # subdirectories, not in enclosing directories.  Hence, in
7364       # the latter case we use a full path to make sure no VPATH
7365       # search occurs.
7366       $fullfile = '$(srcdir)/' . $fullfile
7367         if $dir =~ m,^\.\.(?:$|/),;
7368
7369       push_dist_common ($fullfile);
7370     }
7371   else
7372     {
7373       prog_error "a Makefile in relative directory $relative_dir " .
7374                  "can't add files in directory $dir to DIST_COMMON";
7375     }
7376 }
7377
7378
7379 # If a file name appears as a key in this hash, then it has already
7380 # been checked for.  This allows us not to report the same error more
7381 # than once.
7382 my %required_file_not_found = ();
7383
7384 # required_file_check_or_copy ($WHERE, $DIRECTORY, $FILE)
7385 # -------------------------------------------------------
7386 # Verify that the file must exist in $DIRECTORY, or install it.
7387 sub required_file_check_or_copy
7388 {
7389   my ($where, $dir, $file) = @_;
7390
7391   my $fullfile = "$dir/$file";
7392   my $found_it = 0;
7393   my $dangling_sym = 0;
7394
7395   if (-l $fullfile && ! -f $fullfile)
7396     {
7397       $dangling_sym = 1;
7398     }
7399   elsif (dir_has_case_matching_file ($dir, $file))
7400     {
7401       $found_it = 1;
7402     }
7403
7404   # '--force-missing' only has an effect if '--add-missing' is
7405   # specified.
7406   return
7407     if $found_it && (! $add_missing || ! $force_missing);
7408
7409   # If we've already looked for it, we're done.  You might
7410   # wonder why we don't do this before searching for the
7411   # file.  If we do that, then something like
7412   # AC_OUTPUT(subdir/foo foo) will fail to put foo.in into
7413   # DIST_COMMON.
7414   if (! $found_it)
7415     {
7416       return if defined $required_file_not_found{$fullfile};
7417       $required_file_not_found{$fullfile} = 1;
7418     }
7419   if ($dangling_sym && $add_missing)
7420     {
7421       unlink ($fullfile);
7422     }
7423
7424   my $trailer = '';
7425   my $trailer2 = '';
7426   my $suppress = 0;
7427
7428   # Only install missing files according to our desired
7429   # strictness level.
7430   my $message = "required file '$fullfile' not found";
7431   if ($add_missing)
7432     {
7433       if (-f "$libdir/$file")
7434         {
7435           $suppress = 1;
7436
7437           # Install the missing file.  Symlink if we
7438           # can, copy if we must.  Note: delete the file
7439           # first, in case it is a dangling symlink.
7440           $message = "installing '$fullfile'";
7441
7442           # The license file should not be volatile.
7443           if ($file eq "COPYING")
7444             {
7445               $message .= " using GNU General Public License v3 file";
7446               $trailer2 = "\n    Consider adding the COPYING file"
7447                         . " to the version control system"
7448                         . "\n    for your code, to avoid questions"
7449                         . " about which license your project uses";
7450             }
7451
7452           # Windows Perl will hang if we try to delete a
7453           # file that doesn't exist.
7454           unlink ($fullfile) if -f $fullfile;
7455           if ($symlink_exists && ! $copy_missing)
7456             {
7457               if (! symlink ("$libdir/$file", $fullfile)
7458                   || ! -e $fullfile)
7459                 {
7460                   $suppress = 0;
7461                   $trailer = "; error while making link: $!";
7462                 }
7463             }
7464           elsif (system ('cp', "$libdir/$file", $fullfile))
7465             {
7466               $suppress = 0;
7467               $trailer = "\n    error while copying";
7468             }
7469           set_dir_cache_file ($dir, $file);
7470         }
7471     }
7472   else
7473     {
7474       $trailer = "\n  'automake --add-missing' can install '$file'"
7475         if -f "$libdir/$file";
7476     }
7477
7478   # If --force-missing was specified, and we have
7479   # actually found the file, then do nothing.
7480   return
7481     if $found_it && $force_missing;
7482
7483   # If we couldn't install the file, but it is a target in
7484   # the Makefile, don't print anything.  This allows files
7485   # like README, AUTHORS, or THANKS to be generated.
7486   return
7487     if !$suppress && rule $file;
7488
7489   msg ($suppress ? 'note' : 'error', $where, "$message$trailer$trailer2");
7490 }
7491
7492
7493 # require_file_internal ($WHERE, $MYSTRICT, $DIRECTORY, $QUEUE, @FILES)
7494 # ---------------------------------------------------------------------
7495 # Verify that the file must exist in $DIRECTORY, or install it.
7496 # $MYSTRICT is the strictness level at which this file becomes required.
7497 # Worker threads may queue up the action to be serialized by the master,
7498 # if $QUEUE is true
7499 sub require_file_internal
7500 {
7501   my ($where, $mystrict, $dir, $queue, @files) = @_;
7502
7503   return
7504     unless $strictness >= $mystrict;
7505
7506   foreach my $file (@files)
7507     {
7508       push_required_file ($dir, $file, "$dir/$file");
7509       if ($queue)
7510         {
7511           queue_required_file_check_or_copy ($required_conf_file_queue,
7512                                              QUEUE_CONF_FILE, $relative_dir,
7513                                              $where, $mystrict, @files);
7514         }
7515       else
7516         {
7517           required_file_check_or_copy ($where, $dir, $file);
7518         }
7519     }
7520 }
7521
7522 # require_file ($WHERE, $MYSTRICT, @FILES)
7523 # ----------------------------------------
7524 sub require_file
7525 {
7526     my ($where, $mystrict, @files) = @_;
7527     require_file_internal ($where, $mystrict, $relative_dir, 0, @files);
7528 }
7529
7530 # require_file_with_macro ($COND, $MACRO, $MYSTRICT, @FILES)
7531 # ----------------------------------------------------------
7532 sub require_file_with_macro
7533 {
7534     my ($cond, $macro, $mystrict, @files) = @_;
7535     $macro = rvar ($macro) unless ref $macro;
7536     require_file ($macro->rdef ($cond)->location, $mystrict, @files);
7537 }
7538
7539 # require_libsource_with_macro ($COND, $MACRO, $MYSTRICT, @FILES)
7540 # ---------------------------------------------------------------
7541 # Require an AC_LIBSOURCEd file.  If AC_CONFIG_LIBOBJ_DIR was called, it
7542 # must be in that directory.  Otherwise expect it in the current directory.
7543 sub require_libsource_with_macro
7544 {
7545     my ($cond, $macro, $mystrict, @files) = @_;
7546     $macro = rvar ($macro) unless ref $macro;
7547     if ($config_libobj_dir)
7548       {
7549         require_file_internal ($macro->rdef ($cond)->location, $mystrict,
7550                                $config_libobj_dir, 0, @files);
7551       }
7552     else
7553       {
7554         require_file ($macro->rdef ($cond)->location, $mystrict, @files);
7555       }
7556 }
7557
7558 # queue_required_file_check_or_copy ($QUEUE, $KEY, $DIR, $WHERE,
7559 #                                    $MYSTRICT, @FILES)
7560 # --------------------------------------------------------------
7561 sub queue_required_file_check_or_copy
7562 {
7563     my ($queue, $key, $dir, $where, $mystrict, @files) = @_;
7564     my @serial_loc;
7565     if (ref $where)
7566       {
7567         @serial_loc = (QUEUE_LOCATION, $where->serialize ());
7568       }
7569     else
7570       {
7571         @serial_loc = (QUEUE_STRING, $where);
7572       }
7573     $queue->enqueue ($key, $dir, @serial_loc, $mystrict, 0 + @files, @files);
7574 }
7575
7576 # require_queued_file_check_or_copy ($QUEUE)
7577 # ------------------------------------------
7578 sub require_queued_file_check_or_copy
7579 {
7580     my ($queue) = @_;
7581     my $where;
7582     my $dir = $queue->dequeue ();
7583     my $loc_key = $queue->dequeue ();
7584     if ($loc_key eq QUEUE_LOCATION)
7585       {
7586         $where = Automake::Location::deserialize ($queue);
7587       }
7588     elsif ($loc_key eq QUEUE_STRING)
7589       {
7590         $where = $queue->dequeue ();
7591       }
7592     else
7593       {
7594         prog_error "unexpected key $loc_key";
7595       }
7596     my $mystrict = $queue->dequeue ();
7597     my $nfiles = $queue->dequeue ();
7598     my @files;
7599     push @files, $queue->dequeue ()
7600       foreach (1 .. $nfiles);
7601     return
7602       unless $strictness >= $mystrict;
7603     foreach my $file (@files)
7604       {
7605         required_file_check_or_copy ($where, $config_aux_dir, $file);
7606       }
7607 }
7608
7609 # require_conf_file ($WHERE, $MYSTRICT, @FILES)
7610 # ---------------------------------------------
7611 # Looks in configuration path, as specified by AC_CONFIG_AUX_DIR.
7612 sub require_conf_file
7613 {
7614     my ($where, $mystrict, @files) = @_;
7615     my $queue = defined $required_conf_file_queue ? 1 : 0;
7616     require_file_internal ($where, $mystrict, $config_aux_dir,
7617                            $queue, @files);
7618 }
7619
7620
7621 # require_conf_file_with_macro ($COND, $MACRO, $MYSTRICT, @FILES)
7622 # ---------------------------------------------------------------
7623 sub require_conf_file_with_macro
7624 {
7625     my ($cond, $macro, $mystrict, @files) = @_;
7626     require_conf_file (rvar ($macro)->rdef ($cond)->location,
7627                        $mystrict, @files);
7628 }
7629
7630 ################################################################
7631
7632 # require_build_directory ($DIRECTORY)
7633 # ------------------------------------
7634 # Emit rules to create $DIRECTORY if needed, and return
7635 # the file that any target requiring this directory should be made
7636 # dependent upon.
7637 # We don't want to emit the rule twice, and want to reuse it
7638 # for directories with equivalent names (e.g., 'foo/bar' and './foo//bar').
7639 sub require_build_directory
7640 {
7641   my $directory = shift;
7642
7643   return $directory_map{$directory} if exists $directory_map{$directory};
7644
7645   my $cdir = File::Spec->canonpath ($directory);
7646
7647   if (exists $directory_map{$cdir})
7648     {
7649       my $stamp = $directory_map{$cdir};
7650       $directory_map{$directory} = $stamp;
7651       return $stamp;
7652     }
7653
7654   my $dirstamp = "$cdir/\$(am__dirstamp)";
7655
7656   $directory_map{$directory} = $dirstamp;
7657   $directory_map{$cdir} = $dirstamp;
7658
7659   # Set a variable for the dirstamp basename.
7660   define_pretty_variable ('am__dirstamp', TRUE, INTERNAL,
7661                           '$(am__leading_dot)dirstamp');
7662
7663   # Directory must be removed by 'make distclean'.
7664   $clean_files{$dirstamp} = DIST_CLEAN;
7665
7666   $output_rules .= ("$dirstamp:\n"
7667                     . "\t\@\$(MKDIR_P) $directory\n"
7668                     . "\t\@: > $dirstamp\n");
7669
7670   return $dirstamp;
7671 }
7672
7673 # require_build_directory_maybe ($FILE)
7674 # -------------------------------------
7675 # If $FILE lies in a subdirectory, emit a rule to create this
7676 # directory and return the file that $FILE should be made
7677 # dependent upon.  Otherwise, just return the empty string.
7678 sub require_build_directory_maybe
7679 {
7680     my $file = shift;
7681     my $directory = dirname ($file);
7682
7683     if ($directory ne '.')
7684     {
7685         return require_build_directory ($directory);
7686     }
7687     else
7688     {
7689         return '';
7690     }
7691 }
7692
7693 ################################################################
7694
7695 # Push a list of files onto '@dist_common'.
7696 sub push_dist_common
7697 {
7698   prog_error "push_dist_common run after handle_dist"
7699     if $handle_dist_run;
7700   Automake::Variable::define ('DIST_COMMON', VAR_AUTOMAKE, '+', TRUE, "@_",
7701                               '', INTERNAL, VAR_PRETTY);
7702 }
7703
7704
7705 ################################################################
7706
7707 # generate_makefile ($MAKEFILE_AM, $MAKEFILE_IN)
7708 # ----------------------------------------------
7709 # Generate a Makefile.in given the name of the corresponding Makefile and
7710 # the name of the file output by config.status.
7711 sub generate_makefile
7712 {
7713   my ($makefile_am, $makefile_in) = @_;
7714
7715   # Reset all the Makefile.am related variables.
7716   initialize_per_input;
7717
7718   # AUTOMAKE_OPTIONS can contains -W flags to disable or enable
7719   # warnings for this file.  So hold any warning issued before
7720   # we have processed AUTOMAKE_OPTIONS.
7721   buffer_messages ('warning');
7722
7723   # $OUTPUT is encoded.  If it contains a ":" then the first element
7724   # is the real output file, and all remaining elements are input
7725   # files.  We don't scan or otherwise deal with these input files,
7726   # other than to mark them as dependencies.  See the subroutine
7727   # 'scan_autoconf_files' for details.
7728   my ($makefile, @inputs) = split (/:/, $output_files{$makefile_in});
7729
7730   $relative_dir = dirname ($makefile);
7731
7732   read_main_am_file ($makefile_am, $makefile_in);
7733   if (not handle_options)
7734     {
7735       # Process buffered warnings.
7736       flush_messages;
7737       # Fatal error.  Just return, so we can continue with next file.
7738       return;
7739     }
7740   # Process buffered warnings.
7741   flush_messages;
7742
7743   # There are a few install-related variables that you should not define.
7744   foreach my $var ('PRE_INSTALL', 'POST_INSTALL', 'NORMAL_INSTALL')
7745     {
7746       my $v = var $var;
7747       if ($v)
7748         {
7749           my $def = $v->def (TRUE);
7750           prog_error "$var not defined in condition TRUE"
7751             unless $def;
7752           reject_var $var, "'$var' should not be defined"
7753             if $def->owner != VAR_AUTOMAKE;
7754         }
7755     }
7756
7757   # Catch some obsolete variables.
7758   msg_var ('obsolete', 'INCLUDES',
7759            "'INCLUDES' is the old name for 'AM_CPPFLAGS' (or '*_CPPFLAGS')")
7760     if var ('INCLUDES');
7761
7762   # Must do this after reading .am file.
7763   define_variable ('subdir', $relative_dir, INTERNAL);
7764
7765   # If DIST_SUBDIRS is defined, make sure SUBDIRS is, so that
7766   # recursive rules are enabled.
7767   define_pretty_variable ('SUBDIRS', TRUE, INTERNAL, '')
7768     if var 'DIST_SUBDIRS' && ! var 'SUBDIRS';
7769
7770   # Check first, because we might modify some state.
7771   check_gnu_standards;
7772   check_gnits_standards;
7773
7774   handle_configure ($makefile_am, $makefile_in, $makefile, @inputs);
7775   handle_gettext;
7776   handle_libraries;
7777   handle_ltlibraries;
7778   handle_programs;
7779   handle_scripts;
7780
7781   handle_silent;
7782
7783   # These must be run after all the sources are scanned.  They use
7784   # variables defined by handle_libraries(), handle_ltlibraries(),
7785   # or handle_programs().
7786   handle_compile;
7787   handle_languages;
7788   handle_libtool;
7789
7790   # Variables used by distdir.am and tags.am.
7791   define_pretty_variable ('SOURCES', TRUE, INTERNAL, @sources);
7792   if (! option 'no-dist')
7793     {
7794       define_pretty_variable ('DIST_SOURCES', TRUE, INTERNAL, @dist_sources);
7795     }
7796
7797   handle_texinfo;
7798   handle_emacs_lisp;
7799   handle_python;
7800   handle_java;
7801   handle_man_pages;
7802   handle_data;
7803   handle_headers;
7804   handle_subdirs;
7805   handle_user_recursion;
7806   handle_tags;
7807   handle_minor_options;
7808   # Must come after handle_programs so that %known_programs is up-to-date.
7809   handle_tests;
7810
7811   # This must come after most other rules.
7812   handle_dist;
7813
7814   handle_footer;
7815   do_check_merge_target;
7816   handle_all ($makefile);
7817
7818   # FIXME: Gross!
7819   if (var ('lib_LTLIBRARIES') && var ('bin_PROGRAMS'))
7820     {
7821       $output_rules .= "install-binPROGRAMS: install-libLTLIBRARIES\n\n";
7822     }
7823   if (var ('nobase_lib_LTLIBRARIES') && var ('bin_PROGRAMS'))
7824     {
7825       $output_rules .= "install-binPROGRAMS: install-nobase_libLTLIBRARIES\n\n";
7826     }
7827
7828   handle_install;
7829   handle_clean ($makefile);
7830   handle_factored_dependencies;
7831
7832   # Comes last, because all the above procedures may have
7833   # defined or overridden variables.
7834   $output_vars .= output_variables;
7835
7836   check_typos;
7837
7838   if ($exit_code != 0)
7839     {
7840       verb "not writing $makefile_in because of earlier errors";
7841       return;
7842     }
7843
7844   my $am_relative_dir = dirname ($makefile_am);
7845   mkdir ($am_relative_dir, 0755) if ! -d $am_relative_dir;
7846
7847   # We make sure that 'all:' is the first target.
7848   my $output =
7849     "$output_vars$output_all$output_header$output_rules$output_trailer";
7850
7851   # Decide whether we must update the output file or not.
7852   # We have to update in the following situations.
7853   #  * $force_generation is set.
7854   #  * any of the output dependencies is younger than the output
7855   #  * the contents of the output is different (this can happen
7856   #    if the project has been populated with a file listed in
7857   #    @common_files since the last run).
7858   # Output's dependencies are split in two sets:
7859   #  * dependencies which are also configure dependencies
7860   #    These do not change between each Makefile.am
7861   #  * other dependencies, specific to the Makefile.am being processed
7862   #    (such as the Makefile.am itself, or any Makefile fragment
7863   #    it includes).
7864   my $timestamp = mtime $makefile_in;
7865   if (! $force_generation
7866       && $configure_deps_greatest_timestamp < $timestamp
7867       && $output_deps_greatest_timestamp < $timestamp
7868       && $output eq contents ($makefile_in))
7869     {
7870       verb "$makefile_in unchanged";
7871       # No need to update.
7872       return;
7873     }
7874
7875   if (-e $makefile_in)
7876     {
7877       unlink ($makefile_in)
7878         or fatal "cannot remove $makefile_in: $!";
7879     }
7880
7881   my $gm_file = new Automake::XFile "> $makefile_in";
7882   verb "creating $makefile_in";
7883   print $gm_file $output;
7884 }
7885
7886
7887 ################################################################
7888
7889
7890 # Helper function for usage().
7891 sub print_autodist_files
7892 {
7893   # NOTE: we need to call our 'uniq' function with the leading '&'
7894   # here, because otherwise perl complains that "Unquoted string
7895   # 'uniq' may clash with future reserved word".
7896   my @lcomm = sort (&uniq (@_));
7897
7898   my @four;
7899   format USAGE_FORMAT =
7900   @<<<<<<<<<<<<<<<<   @<<<<<<<<<<<<<<<<   @<<<<<<<<<<<<<<<<   @<<<<<<<<<<<<<<<<
7901   $four[0],           $four[1],           $four[2],           $four[3]
7902 .
7903   local $~ = "USAGE_FORMAT";
7904
7905   my $cols = 4;
7906   my $rows = int(@lcomm / $cols);
7907   my $rest = @lcomm % $cols;
7908
7909   if ($rest)
7910     {
7911       $rows++;
7912     }
7913   else
7914     {
7915       $rest = $cols;
7916     }
7917
7918   for (my $y = 0; $y < $rows; $y++)
7919     {
7920       @four = ("", "", "", "");
7921       for (my $x = 0; $x < $cols; $x++)
7922         {
7923           last if $y + 1 == $rows && $x == $rest;
7924
7925           my $idx = (($x > $rest)
7926                ?  ($rows * $rest + ($rows - 1) * ($x - $rest))
7927                : ($rows * $x));
7928
7929           $idx += $y;
7930           $four[$x] = $lcomm[$idx];
7931         }
7932       write;
7933     }
7934 }
7935
7936
7937 sub usage ()
7938 {
7939     print "Usage: $0 [OPTION]... [Makefile]...
7940
7941 Generate Makefile.in for configure from Makefile.am.
7942
7943 Operation modes:
7944       --help               print this help, then exit
7945       --version            print version number, then exit
7946   -v, --verbose            verbosely list files processed
7947       --no-force           only update Makefile.in's that are out of date
7948   -W, --warnings=CATEGORY  report the warnings falling in CATEGORY
7949
7950 Dependency tracking:
7951   -i, --ignore-deps      disable dependency tracking code
7952       --include-deps     enable dependency tracking code
7953
7954 Flavors:
7955       --foreign          set strictness to foreign
7956       --gnits            set strictness to gnits
7957       --gnu              set strictness to gnu
7958
7959 Library files:
7960   -a, --add-missing      add missing standard files to package
7961       --libdir=DIR       set directory storing library files
7962       --print-libdir     print directory storing library files
7963   -c, --copy             with -a, copy missing files (default is symlink)
7964   -f, --force-missing    force update of standard files
7965
7966 ";
7967     Automake::ChannelDefs::usage;
7968
7969     print "\nFiles automatically distributed if found " .
7970           "(always):\n";
7971     print_autodist_files @common_files;
7972     print "\nFiles automatically distributed if found " .
7973           "(under certain conditions):\n";
7974     print_autodist_files @common_sometimes;
7975
7976     print '
7977 Report bugs to <@PACKAGE_BUGREPORT@>.
7978 GNU Automake home page: <@PACKAGE_URL@>.
7979 General help using GNU software: <http://www.gnu.org/gethelp/>.
7980 ';
7981
7982     # --help always returns 0 per GNU standards.
7983     exit 0;
7984 }
7985
7986
7987 sub version ()
7988 {
7989   print <<EOF;
7990 automake (GNU $PACKAGE) $VERSION
7991 Copyright (C) $RELEASE_YEAR Free Software Foundation, Inc.
7992 License GPLv2+: GNU GPL version 2 or later <http://gnu.org/licenses/gpl-2.0.html>
7993 This is free software: you are free to change and redistribute it.
7994 There is NO WARRANTY, to the extent permitted by law.
7995
7996 Written by Tom Tromey <tromey\@redhat.com>
7997        and Alexandre Duret-Lutz <adl\@gnu.org>.
7998 EOF
7999   # --version always returns 0 per GNU standards.
8000   exit 0;
8001 }
8002
8003 ################################################################
8004
8005 # Parse command line.
8006 sub parse_arguments ()
8007 {
8008   my $strict = 'gnu';
8009   my $ignore_deps = 0;
8010   my @warnings = ();
8011
8012   my %cli_options =
8013     (
8014      'version' => \&version,
8015      'help'    => \&usage,
8016      'libdir=s' => \$libdir,
8017      'print-libdir'     => sub { print "$libdir\n"; exit 0; },
8018      'gnu'              => sub { $strict = 'gnu'; },
8019      'gnits'            => sub { $strict = 'gnits'; },
8020      'foreign'          => sub { $strict = 'foreign'; },
8021      'include-deps'     => sub { $ignore_deps = 0; },
8022      'i|ignore-deps'    => sub { $ignore_deps = 1; },
8023      'no-force' => sub { $force_generation = 0; },
8024      'f|force-missing'  => \$force_missing,
8025      'a|add-missing'    => \$add_missing,
8026      'c|copy'           => \$copy_missing,
8027      'v|verbose'        => sub { setup_channel 'verb', silent => 0; },
8028      'W|warnings=s'     => \@warnings,
8029      );
8030
8031   use Automake::Getopt ();
8032   Automake::Getopt::parse_options %cli_options;
8033
8034   set_strictness ($strict);
8035   my $cli_where = new Automake::Location;
8036   set_global_option ('no-dependencies', $cli_where) if $ignore_deps;
8037   for my $warning (@warnings)
8038     {
8039       parse_warnings ('-W', $warning);
8040     }
8041
8042   return unless @ARGV;
8043
8044   my $errspec = 0;
8045   foreach my $arg (@ARGV)
8046     {
8047       fatal ("empty argument\nTry '$0 --help' for more information")
8048         if ($arg eq '');
8049
8050       # Handle $local:$input syntax.
8051       my ($local, @rest) = split (/:/, $arg);
8052       @rest = ("$local.in",) unless @rest;
8053       my $input = locate_am @rest;
8054       if ($input)
8055         {
8056           push @input_files, $input;
8057           $output_files{$input} = join (':', ($local, @rest));
8058         }
8059       else
8060         {
8061           error "no Automake input file found for '$arg'";
8062           $errspec = 1;
8063         }
8064     }
8065   fatal "no input file found among supplied arguments"
8066     if $errspec && ! @input_files;
8067 }
8068
8069
8070 # handle_makefile ($MAKEFILE)
8071 # ---------------------------
8072 sub handle_makefile
8073 {
8074   my ($file) =  @_;
8075   ($am_file = $file) =~ s/\.in$//;
8076   if (! -f ($am_file . '.am'))
8077     {
8078       error "'$am_file.am' does not exist";
8079     }
8080   else
8081     {
8082       # Any warning setting now local to this Makefile.am.
8083       dup_channel_setup;
8084
8085       generate_makefile ($am_file . '.am', $file);
8086
8087       # Back out any warning setting.
8088       drop_channel_setup;
8089     }
8090 }
8091
8092 # Deal with all makefiles, without threads.
8093 sub handle_makefiles_serial ()
8094 {
8095   foreach my $file (@input_files)
8096     {
8097       handle_makefile ($file);
8098     }
8099 }
8100
8101 # Logic for deciding how many worker threads to use.
8102 sub get_number_of_threads ()
8103 {
8104   my $nthreads = $ENV{'AUTOMAKE_JOBS'} || 0;
8105
8106   $nthreads = 0
8107     unless $nthreads =~ /^[0-9]+$/;
8108
8109   # It doesn't make sense to use more threads than makefiles,
8110   my $max_threads = @input_files;
8111
8112   if ($nthreads > $max_threads)
8113     {
8114       $nthreads = $max_threads;
8115     }
8116   return $nthreads;
8117 }
8118
8119 # handle_makefiles_threaded ($NTHREADS)
8120 # -------------------------------------
8121 # Deal with all makefiles, using threads.  The general strategy is to
8122 # spawn NTHREADS worker threads, dispatch makefiles to them, and let the
8123 # worker threads push back everything that needs serialization:
8124 # * warning and (normal) error messages, for stable stderr output
8125 #   order and content (avoiding duplicates, for example),
8126 # * races when installing aux files (and respective messages),
8127 # * races when collecting aux files for distribution.
8128 #
8129 # The latter requires that the makefile that deals with the aux dir
8130 # files be handled last, done by the master thread.
8131 sub handle_makefiles_threaded
8132 {
8133   my ($nthreads) = @_;
8134
8135   # The file queue distributes all makefiles, the message queues
8136   # collect all serializations needed for respective files.
8137   my $file_queue = Thread::Queue->new;
8138   my %msg_queues;
8139   foreach my $file (@input_files)
8140     {
8141       $msg_queues{$file} = Thread::Queue->new;
8142     }
8143
8144   verb "spawning $nthreads worker threads";
8145   my @threads = (1 .. $nthreads);
8146   foreach my $t (@threads)
8147     {
8148       $t = threads->new (sub
8149         {
8150           while (my $file = $file_queue->dequeue)
8151             {
8152               verb "handling $file";
8153               my $queue = $msg_queues{$file};
8154               setup_channel_queue ($queue, QUEUE_MESSAGE);
8155               $required_conf_file_queue = $queue;
8156               handle_makefile ($file);
8157               $queue->enqueue (undef);
8158               setup_channel_queue (undef, undef);
8159               $required_conf_file_queue = undef;
8160             }
8161           return $exit_code;
8162         });
8163     }
8164
8165   # Queue all makefiles.
8166   verb "queuing " . @input_files . " input files";
8167   $file_queue->enqueue (@input_files, (undef) x @threads);
8168
8169   # Collect and process serializations.
8170   foreach my $file (@input_files)
8171     {
8172       verb "dequeuing messages for " . $file;
8173       reset_local_duplicates ();
8174       my $queue = $msg_queues{$file};
8175       while (my $key = $queue->dequeue)
8176         {
8177           if ($key eq QUEUE_MESSAGE)
8178             {
8179               pop_channel_queue ($queue);
8180             }
8181           elsif ($key eq QUEUE_CONF_FILE)
8182             {
8183               require_queued_file_check_or_copy ($queue);
8184             }
8185           else
8186             {
8187               prog_error "unexpected key $key";
8188             }
8189         }
8190     }
8191
8192   foreach my $t (@threads)
8193     {
8194       my @exit_thread = $t->join;
8195       $exit_code = $exit_thread[0]
8196         if ($exit_thread[0] > $exit_code);
8197     }
8198 }
8199
8200 ################################################################
8201
8202 # Parse the WARNINGS environment variable.
8203 parse_WARNINGS;
8204
8205 # Parse command line.
8206 parse_arguments;
8207
8208 $configure_ac = require_configure_ac;
8209
8210 # Do configure.ac scan only once.
8211 scan_autoconf_files;
8212
8213 if (! @input_files)
8214   {
8215     my $msg = '';
8216     $msg = "\nDid you forget AC_CONFIG_FILES([Makefile]) in $configure_ac?"
8217       if -f 'Makefile.am';
8218     fatal ("no 'Makefile.am' found for any configure output$msg");
8219   }
8220
8221 my $nthreads = get_number_of_threads ();
8222
8223 if ($perl_threads && $nthreads >= 1)
8224   {
8225     handle_makefiles_threaded ($nthreads);
8226   }
8227 else
8228   {
8229     handle_makefiles_serial ();
8230   }
8231
8232 exit $exit_code;
8233
8234
8235 ### Setup "GNU" style for perl-mode and cperl-mode.
8236 ## Local Variables:
8237 ## perl-indent-level: 2
8238 ## perl-continued-statement-offset: 2
8239 ## perl-continued-brace-offset: 0
8240 ## perl-brace-offset: 0
8241 ## perl-brace-imaginary-offset: 0
8242 ## perl-label-offset: -2
8243 ## cperl-indent-level: 2
8244 ## cperl-brace-offset: 0
8245 ## cperl-continued-brace-offset: 0
8246 ## cperl-label-offset: -2
8247 ## cperl-extra-newline-before-brace: t
8248 ## cperl-merge-trailing-else: nil
8249 ## cperl-continued-statement-offset: 2
8250 ## End: