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