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