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