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