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