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