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