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