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