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