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