Merge branch 'msvc'
[platform/upstream/automake.git] / lib / Automake / Variable.pm
1 # Copyright (C) 2003, 2004, 2005, 2006, 2008, 2009, 2010 Free Software
2 # Foundation, Inc.
3
4 # This program is free software; you can redistribute it and/or modify
5 # it under the terms of the GNU General Public License as published by
6 # the Free Software Foundation; either version 2, or (at your option)
7 # any later version.
8
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12 # GNU General Public License for more details.
13
14 # You should have received a copy of the GNU General Public License
15 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
16
17 package Automake::Variable;
18 use strict;
19 use Carp;
20
21 use Automake::Channels;
22 use Automake::ChannelDefs;
23 use Automake::Configure_ac;
24 use Automake::Item;
25 use Automake::VarDef;
26 use Automake::Condition qw (TRUE FALSE);
27 use Automake::DisjConditions;
28 use Automake::General 'uniq';
29 use Automake::Wrap 'makefile_wrap';
30
31 require Exporter;
32 use vars '@ISA', '@EXPORT', '@EXPORT_OK';
33 @ISA = qw/Automake::Item Exporter/;
34 @EXPORT = qw (err_var msg_var msg_cond_var reject_var
35               var rvar vardef rvardef
36               variables
37               scan_variable_expansions check_variable_expansions
38               variable_delete
39               variables_dump
40               set_seen
41               require_variables
42               variable_value
43               output_variables
44               transform_variable_recursively);
45
46 =head1 NAME
47
48 Automake::Variable - support for variable definitions
49
50 =head1 SYNOPSIS
51
52   use Automake::Variable;
53   use Automake::VarDef;
54
55   # Defining a variable.
56   Automake::Variable::define($varname, $owner, $type,
57                              $cond, $value, $comment,
58                              $where, $pretty)
59
60   # Looking up a variable.
61   my $var = var $varname;
62   if ($var)
63     {
64       ...
65     }
66
67   # Looking up a variable that is assumed to exist.
68   my $var = rvar $varname;
69
70   # The list of conditions where $var has been defined.
71   # ($var->conditions is an Automake::DisjConditions,
72   # $var->conditions->conds is a list of Automake::Condition.)
73   my @conds = $var->conditions->conds
74
75   # Access to the definition in Condition $cond.
76   # $def is an Automake::VarDef.
77   my $def = $var->def ($cond);
78   if ($def)
79     {
80       ...
81     }
82
83   # When the conditional definition is assumed to exist, use
84   my $def = $var->rdef ($cond);
85
86
87 =head1 DESCRIPTION
88
89 This package provides support for Makefile variable definitions.
90
91 An C<Automake::Variable> is a variable name associated to possibly
92 many conditional definitions.  These definitions are instances
93 of C<Automake::VarDef>.
94
95 Therefore obtaining the value of a variable under a given
96 condition involves two lookups.  One to look up the variable,
97 and one to look up the conditional definition:
98
99   my $var = var $name;
100   if ($var)
101     {
102       my $def = $var->def ($cond);
103       if ($def)
104         {
105           return $def->value;
106         }
107       ...
108     }
109   ...
110
111 When it is known that the variable and the definition
112 being looked up exist, the above can be simplified to
113
114   return var ($name)->def ($cond)->value; # Do not write this.
115
116 but is better written
117
118   return rvar ($name)->rdef ($cond)->value;
119
120 or even
121
122   return rvardef ($name, $cond)->value;
123
124 The I<r> variants of the C<var>, C<def>, and C<vardef> methods add an
125 extra test to ensure that the lookup succeeded, and will diagnose
126 failures as internal errors (with a message which is much more
127 informative than Perl's warning about calling a method on a
128 non-object).
129
130 =cut
131
132 my $_VARIABLE_CHARACTERS = '[.A-Za-z0-9_@]+';
133 my $_VARIABLE_PATTERN = '^' . $_VARIABLE_CHARACTERS . "\$";
134 my $_VARIABLE_RECURSIVE_PATTERN =
135     '^([.A-Za-z0-9_@]|\$[({]' . $_VARIABLE_CHARACTERS . '[})]?)+' . "\$";
136
137 # The order in which variables should be output.  (May contain
138 # duplicates -- only the first occurrence matters.)
139 my @_var_order;
140
141 # This keeps track of all variables defined by &_gen_varname.
142 # $_gen_varname{$base} is a hash for all variables defined with
143 # prefix `$base'.  Values stored in this hash are the variable names.
144 # Keys have the form "(COND1)VAL1(COND2)VAL2..." where VAL1 and VAL2
145 # are the values of the variable for condition COND1 and COND2.
146 my %_gen_varname = ();
147 # $_gen_varname_n{$base} is the number of variables generated by
148 # _gen_varname() for $base.  This is not the same as keys
149 # %{$_gen_varname{$base}} because %_gen_varname may also contain
150 # variables not generated by _gen_varname.
151 my %_gen_varname_n = ();
152
153 # Declare the macros that define known variables, so we can
154 # hint the user if she try to use one of these variables.
155
156 # Macros accessible via aclocal.
157 my %_am_macro_for_var =
158   (
159    ANSI2KNR => 'AM_C_PROTOTYPES',
160    CCAS => 'AM_PROG_AS',
161    CCASFLAGS => 'AM_PROG_AS',
162    EMACS => 'AM_PATH_LISPDIR',
163    GCJ => 'AM_PROG_GCJ',
164    LEX => 'AM_PROG_LEX',
165    LIBTOOL => 'AC_PROG_LIBTOOL',
166    lispdir => 'AM_PATH_LISPDIR',
167    pkgpyexecdir => 'AM_PATH_PYTHON',
168    pkgpythondir => 'AM_PATH_PYTHON',
169    pyexecdir => 'AM_PATH_PYTHON',
170    PYTHON => 'AM_PATH_PYTHON',
171    pythondir => 'AM_PATH_PYTHON',
172    U => 'AM_C_PROTOTYPES',
173    );
174
175 # Macros shipped with Autoconf.
176 my %_ac_macro_for_var =
177   (
178    ALLOCA => 'AC_FUNC_ALLOCA',
179    CC => 'AC_PROG_CC',
180    CFLAGS => 'AC_PROG_CC',
181    CXX => 'AC_PROG_CXX',
182    CXXFLAGS => 'AC_PROG_CXX',
183    F77 => 'AC_PROG_F77',
184    F77FLAGS => 'AC_PROG_F77',
185    FC => 'AC_PROG_FC',
186    FCFLAGS => 'AC_PROG_FC',
187    OBJC => 'AC_PROG_OBJC',
188    OBJCFLAGS => 'AC_PROG_OBJC',
189    RANLIB => 'AC_PROG_RANLIB',
190    UPC => 'AM_PROG_UPC',
191    UPCFLAGS => 'AM_PROG_UPC',
192    YACC => 'AC_PROG_YACC',
193    );
194
195 # The name of the configure.ac file.
196 my $configure_ac;
197
198 # Variables that can be overridden without complaint from -Woverride
199 my %_silent_variable_override =
200   (AM_MAKEINFOHTMLFLAGS => 1,
201    AR => 1,
202    ARFLAGS => 1,
203    DEJATOOL => 1,
204    JAVAC => 1,
205    JAVAROOT => 1);
206
207 # Count of helper variables used to implement conditional '+='.
208 my $_appendvar;
209
210 # Each call to C<Automake::Variable::traverse_recursively> gets an
211 # unique label. This is used to detect recursively defined variables.
212 my $_traversal = 0;
213
214
215 =head2 Error reporting functions
216
217 In these functions, C<$var> can be either a variable name, or
218 an instance of C<Automake::Variable>.
219
220 =over 4
221
222 =item C<err_var ($var, $message, [%options])>
223
224 Uncategorized errors about variables.
225
226 =cut
227
228 sub err_var ($$;%)
229 {
230   msg_var ('error', @_);
231 }
232
233 =item C<msg_cond_var ($channel, $cond, $var, $message, [%options])>
234
235 Messages about conditional variable.
236
237 =cut
238
239 sub msg_cond_var ($$$$;%)
240 {
241   my ($channel, $cond, $var, $msg, %opts) = @_;
242   my $v = ref ($var) ? $var : rvar ($var);
243   msg $channel, $v->rdef ($cond)->location, $msg, %opts;
244 }
245
246 =item C<msg_var ($channel, $var, $message, [%options])>
247
248 Messages about variables.
249
250 =cut
251
252 sub msg_var ($$$;%)
253 {
254   my ($channel, $var, $msg, %opts) = @_;
255   my $v = ref ($var) ? $var : rvar ($var);
256   # Don't know which condition is concerned.  Pick any.
257   my $cond = $v->conditions->one_cond;
258   msg_cond_var $channel, $cond, $v, $msg, %opts;
259 }
260
261 =item C<$bool = reject_var ($varname, $error_msg)>
262
263 Bail out with C<$error_msg> if a variable with name C<$varname> has
264 been defined.
265
266 Return true iff C<$varname> is defined.
267
268 =cut
269
270 sub reject_var ($$)
271 {
272   my ($var, $msg) = @_;
273   my $v = var ($var);
274   if ($v)
275     {
276       err_var $v, $msg;
277       return 1;
278     }
279   return 0;
280 }
281
282 =back
283
284 =head2 Administrative functions
285
286 =over 4
287
288 =item C<Automake::Variable::hook ($varname, $fun)>
289
290 Declare a function to be called whenever a variable
291 named C<$varname> is defined or redefined.
292
293 C<$fun> should take two arguments: C<$type> and C<$value>.
294 When type is C<''> or <':'>, C<$value> is the value being
295 assigned to C<$varname>.  When C<$type> is C<'+'>, C<$value>
296 is the value being appended to  C<$varname>.
297
298 =cut
299
300 use vars '%_hooks';
301 sub hook ($$)
302 {
303   my ($var, $fun) = @_;
304   $_hooks{$var} = $fun;
305 }
306
307 =item C<variables ([$suffix])>
308
309 Returns the list of all L<Automake::Variable> instances.  (I.e., all
310 variables defined so far.)  If C<$suffix> is supplied, return only
311 the L<Automake::Variable> instances that ends with C<_$suffix>.
312
313 =cut
314
315 use vars '%_variable_dict', '%_primary_dict';
316 sub variables (;$)
317 {
318   my ($suffix) = @_;
319   if ($suffix)
320     {
321       if (exists $_primary_dict{$suffix})
322         {
323           return values %{$_primary_dict{$suffix}};
324         }
325       else
326         {
327           return ();
328         }
329     }
330   else
331     {
332       return values %_variable_dict;
333     }
334 }
335
336 =item C<Automake::Variable::reset>
337
338 The I<forget all> function.  Clears all know variables and reset some
339 other internal data.
340
341 =cut
342
343 sub reset ()
344 {
345   %_variable_dict = ();
346   %_primary_dict = ();
347   $_appendvar = 0;
348   @_var_order = ();
349   %_gen_varname = ();
350   %_gen_varname_n = ();
351   $_traversal = 0;
352 }
353
354 =item C<var ($varname)>
355
356 Return the C<Automake::Variable> object for the variable
357 named C<$varname> if defined.   Return 0 otherwise.
358
359 =cut
360
361 sub var ($)
362 {
363   my ($name) = @_;
364   return $_variable_dict{$name} if exists $_variable_dict{$name};
365   return 0;
366 }
367
368 =item C<vardef ($varname, $cond)>
369
370 Return the C<Automake::VarDef> object for the variable named
371 C<$varname> if defined in condition C<$cond>.  Return false
372 if the condition or the variable does not exist.
373
374 =cut
375
376 sub vardef ($$)
377 {
378   my ($name, $cond) = @_;
379   my $var = var $name;
380   return $var && $var->def ($cond);
381 }
382
383 # Create the variable if it does not exist.
384 # This is used only by other functions in this package.
385 sub _cvar ($)
386 {
387   my ($name) = @_;
388   my $v = var $name;
389   return $v if $v;
390   return _new Automake::Variable $name;
391 }
392
393 =item C<rvar ($varname)>
394
395 Return the C<Automake::Variable> object for the variable named
396 C<$varname>.  Abort with an internal error if the variable was not
397 defined.
398
399 The I<r> in front of C<var> stands for I<required>.  One
400 should call C<rvar> to assert the variable's existence.
401
402 =cut
403
404 sub rvar ($)
405 {
406   my ($name) = @_;
407   my $v = var $name;
408   prog_error ("undefined variable $name\n" . &variables_dump)
409     unless $v;
410   return $v;
411 }
412
413 =item C<rvardef ($varname, $cond)>
414
415 Return the C<Automake::VarDef> object for the variable named
416 C<$varname> if defined in condition C<$cond>.  Abort with an internal
417 error if the condition or the variable does not exist.
418
419 =cut
420
421 sub rvardef ($$)
422 {
423   my ($name, $cond) = @_;
424   return rvar ($name)->rdef ($cond);
425 }
426
427 =back
428
429 =head2 Methods
430
431 C<Automake::Variable> is a subclass of C<Automake::Item>.  See
432 that package for inherited methods.
433
434 Here are the methods specific to the C<Automake::Variable> instances.
435 Use the C<define> function, described latter, to create such objects.
436
437 =over 4
438
439 =cut
440
441 # Create Automake::Variable objects.  This is used
442 # only in this file.  Other users should use
443 # the "define" function.
444 sub _new ($$)
445 {
446   my ($class, $name) = @_;
447   my $self = Automake::Item::new ($class, $name);
448   $self->{'scanned'} = 0;
449   $self->{'last-append'} = []; # helper variable for last conditional append.
450   $_variable_dict{$name} = $self;
451   if ($name =~ /_([[:alnum:]]+)$/)
452     {
453       $_primary_dict{$1}{$name} = $self;
454     }
455   return $self;
456 }
457
458 # _check_ambiguous_condition ($SELF, $COND, $WHERE)
459 # -------------------------------------------------
460 # Check for an ambiguous conditional.  This is called when a variable
461 # is being defined conditionally.  If we already know about a
462 # definition that is true under the same conditions, then we have an
463 # ambiguity.
464 sub _check_ambiguous_condition ($$$)
465 {
466   my ($self, $cond, $where) = @_;
467   my $var = $self->name;
468   my ($message, $ambig_cond) = $self->conditions->ambiguous_p ($var, $cond);
469
470   # We allow silent variables to be overridden silently,
471   # by either silent or non-silent variables.
472   my $def = $self->def ($ambig_cond);
473   if ($message && $def->pretty != VAR_SILENT)
474     {
475       msg 'syntax', $where, "$message ...", partial => 1;
476       msg_var ('syntax', $var, "... `$var' previously defined here");
477       verb ($self->dump);
478     }
479 }
480
481 =item C<$bool = $var-E<gt>check_defined_unconditionally ([$parent, $parent_cond])>
482
483 Warn if the variable is conditionally defined.  C<$parent> is the name
484 of the parent variable, and C<$parent_cond> the condition of the parent
485 definition.  These two variables are used to display diagnostics.
486
487 =cut
488
489 sub check_defined_unconditionally ($;$$)
490 {
491   my ($self, $parent, $parent_cond) = @_;
492
493   if (!$self->conditions->true)
494     {
495       if ($parent)
496         {
497           msg_cond_var ('unsupported', $parent_cond, $parent,
498                         "automake does not support conditional definition of "
499                         . $self->name . " in $parent");
500         }
501       else
502         {
503           msg_var ('unsupported', $self,
504                    "automake does not support " . $self->name
505                    . " being defined conditionally");
506         }
507     }
508 }
509
510 =item C<$str = $var-E<gt>output ([@conds])>
511
512 Format all the definitions of C<$var> if C<@cond> is not specified,
513 else only that corresponding to C<@cond>.
514
515 =cut
516
517 sub output ($@)
518 {
519   my ($self, @conds) = @_;
520
521   @conds = $self->conditions->conds
522     unless @conds;
523
524   my $res = '';
525   my $name = $self->name;
526
527   foreach my $cond (@conds)
528     {
529       my $def = $self->def ($cond);
530       prog_error ("unknown condition `" . $cond->human . "' for `"
531                   . $self->name . "'")
532         unless $def;
533
534       next
535         if $def->pretty == VAR_SILENT;
536
537       $res .= $def->comment;
538
539       my $val = $def->raw_value;
540       my $equals = $def->type eq ':' ? ':=' : '=';
541       my $str = $cond->subst_string;
542
543
544       if ($def->pretty == VAR_ASIS)
545         {
546           my $output_var = "$name $equals $val";
547           $output_var =~ s/^/$str/meg;
548           $res .= "$output_var\n";
549         }
550       elsif ($def->pretty == VAR_PRETTY)
551         {
552           # Suppress escaped new lines.  &makefile_wrap will
553           # add them back, maybe at other places.
554           $val =~ s/\\$//mg;
555           my $wrap = makefile_wrap ("$str$name $equals", "$str\t",
556                                     split (' ', $val));
557
558           # If the last line of the definition is made only of
559           # @substitutions@, append an empty variable to make sure it
560           # cannot be substituted as a blank line (that would confuse
561           # HP-UX Make).
562           $wrap = makefile_wrap ("$str$name $equals", "$str\t",
563                                  split (' ', $val), '$(am__empty)')
564             if $wrap =~ /\n(\s*@\w+@)+\s*$/;
565
566           $res .= $wrap;
567         }
568       else # ($def->pretty == VAR_SORTED)
569         {
570           # Suppress escaped new lines.  &makefile_wrap will
571           # add them back, maybe at other places.
572           $val =~ s/\\$//mg;
573           $res .= makefile_wrap ("$str$name $equals", "$str\t",
574                                  sort (split (' ' , $val)));
575         }
576     }
577   return $res;
578 }
579
580 =item C<@values = $var-E<gt>value_as_list ($cond, [$parent, $parent_cond])>
581
582 Get the value of C<$var> as a list, given a specified condition,
583 without recursing through any subvariables.
584
585 C<$cond> is the condition of interest.  C<$var> does not need
586 to be defined for condition C<$cond> exactly, but it needs
587 to be defined for at most one condition implied by C<$cond>.
588
589 C<$parent> and C<$parent_cond> designate the name and the condition
590 of the parent variable, i.e., the variable in which C<$var> is
591 being expanded.  These are used in diagnostics.
592
593 For example, if C<A> is defined as "C<foo $(B) bar>" in condition
594 C<TRUE>, calling C<rvar ('A')->value_as_list (TRUE)> will return
595 C<("foo", "$(B)", "bar")>.
596
597 =cut
598
599 sub value_as_list ($$;$$)
600 {
601   my ($self, $cond, $parent, $parent_cond) = @_;
602   my @result;
603
604   # Get value for given condition
605   my $onceflag;
606   foreach my $vcond ($self->conditions->conds)
607     {
608       if ($vcond->true_when ($cond))
609         {
610           # If there is more than one definitions of $var matching
611           # $cond then we are in trouble: tell the user we need a
612           # paddle.  Continue by merging results from all conditions,
613           # although it doesn't make much sense.
614           $self->check_defined_unconditionally ($parent, $parent_cond)
615             if $onceflag;
616           $onceflag = 1;
617
618           my $val = $self->rdef ($vcond)->value;
619           push @result, split (' ', $val);
620         }
621     }
622   return @result;
623 }
624
625 =item C<@values = $var-E<gt>value_as_list_recursive ([%options])>
626
627 Return the contents of C<$var> as a list, split on whitespace.  This
628 will recursively follow C<$(...)> and C<${...}> inclusions.  It
629 preserves C<@...@> substitutions.
630
631 C<%options> is a list of option for C<Variable::traverse_recursively>
632 (see this method).  The most useful is C<cond_filter>:
633
634   $var->value_as_list_recursive (cond_filter => $cond)
635
636 will return the contents of C<$var> and any subvariable in all
637 conditions implied by C<$cond>.
638
639 C<%options> can also carry options specific to C<value_as_list_recursive>.
640 Presently, the only such option is C<location =E<gt> 1> which instructs
641 C<value_as_list_recursive> to return a list of C<[$location, @values]> pairs.
642
643 =cut
644
645 sub value_as_list_recursive ($;%)
646 {
647   my ($var, %options) = @_;
648
649   return $var->traverse_recursively
650     (# Construct [$location, $value] pairs if requested.
651      sub {
652        my ($var, $val, $cond, $full_cond) = @_;
653        return [$var->rdef ($cond)->location, $val] if $options{'location'};
654        return $val;
655      },
656      # Collect results.
657      sub {
658        my ($var, $parent_cond, @allresults) = @_;
659        return map { my ($cond, @vals) = @$_; @vals } @allresults;
660      },
661      %options);
662 }
663
664
665 =item C<$bool = $var-E<gt>has_conditional_contents>
666
667 Return 1 if C<$var> or one of its subvariable was conditionally
668 defined.  Return 0 otherwise.
669
670 =cut
671
672 sub has_conditional_contents ($)
673 {
674   my ($self) = @_;
675
676   # Traverse the variable recursively until we
677   # find a variable defined conditionally.
678   # Use `die' to abort the traversal, and pass it `$full_cond'
679   # to we can find easily whether the `eval' block aborted
680   # because we found a condition, or for some other error.
681   eval
682     {
683       $self->traverse_recursively
684         (sub
685          {
686            my ($subvar, $val, $cond, $full_cond) = @_;
687            die $full_cond if ! $full_cond->true;
688            return ();
689          },
690          sub { return (); });
691     };
692   if ($@)
693     {
694       return 1 if ref ($@) && $@->isa ("Automake::Condition");
695       # Propagate other errors.
696       die;
697     }
698   return 0;
699 }
700
701
702 =item C<$string = $var-E<gt>dump>
703
704 Return a string describing all we know about C<$var>.
705 For debugging.
706
707 =cut
708
709 sub dump ($)
710 {
711   my ($self) = @_;
712
713   my $text = $self->name . ": \n  {\n";
714   foreach my $vcond ($self->conditions->conds)
715     {
716       $text .= "    " . $vcond->human . " => " . $self->rdef ($vcond)->dump;
717     }
718   $text .= "  }\n";
719   return $text;
720 }
721
722
723 =back
724
725 =head2 Utility functions
726
727 =over 4
728
729 =item C<@list = scan_variable_expansions ($text)>
730
731 Return the list of variable names expanded in C<$text>.  Note that
732 unlike some other functions, C<$text> is not split on spaces before we
733 check for subvariables.
734
735 =cut
736
737 sub scan_variable_expansions ($)
738 {
739   my ($text) = @_;
740   my @result = ();
741
742   # Strip comments.
743   $text =~ s/#.*$//;
744
745   # Record each use of ${stuff} or $(stuff) that does not follow a $.
746   while ($text =~ /(?<!\$)\$(?:\{([^\}]*)\}|\(([^\)]*)\))/g)
747     {
748       my $var = $1 || $2;
749       # The occurrence may look like $(string1[:subst1=[subst2]]) but
750       # we want only `string1'.
751       $var =~ s/:[^:=]*=[^=]*$//;
752       push @result, $var;
753     }
754
755   return @result;
756 }
757
758 =item C<check_variable_expansions ($text, $where)>
759
760 Check variable expansions in C<$text> and warn about any name that
761 does not conform to POSIX.  C<$where> is the location of C<$text>
762 for the error message.
763
764 =cut
765
766 sub check_variable_expansions ($$)
767 {
768   my ($text, $where) = @_;
769   # Catch expansion of variables whose name does not conform to POSIX.
770   foreach my $var (scan_variable_expansions ($text))
771     {
772       if ($var !~ /$_VARIABLE_PATTERN/o)
773         {
774           # If the variable name contains a space, it's likely
775           # to be a GNU make extension (such as $(addsuffix ...)).
776           # Mention this in the diagnostic.
777           my $gnuext = "";
778           $gnuext = "\n(probably a GNU make extension)" if $var =~ / /;
779           # Accept recursive variable expansions if so desired
780           # (we hope they are rather portable in practice).
781           if ($var =~ /$_VARIABLE_RECURSIVE_PATTERN/o)
782             {
783               msg ('portability-recursive', $where,
784                    "$var: non-POSIX recursive variable expansion$gnuext");
785             }
786           else
787             {
788               msg ('portability', $where, "$var: non-POSIX variable name$gnuext");
789             }
790         }
791     }
792 }
793
794
795
796 =item C<Automake::Variable::define($varname, $owner, $type, $cond, $value, $comment, $where, $pretty)>
797
798 Define or append to a new variable.
799
800 C<$varname>: the name of the variable being defined.
801
802 C<$owner>: owner of the variable (one of C<VAR_MAKEFILE>,
803 C<VAR_CONFIGURE>, or C<VAR_AUTOMAKE>, defined by L<Automake::VarDef>).
804 Variables can be overridden, provided the new owner is not weaker
805 (C<VAR_AUTOMAKE> < C<VAR_CONFIGURE> < C<VAR_MAKEFILE>).
806
807 C<$type>: the type of the assignment (C<''> for C<FOO = bar>,
808 C<':'> for C<FOO := bar>, and C<'+'> for C<'FOO += bar'>).
809
810 C<$cond>: the C<Condition> in which C<$var> is being defined.
811
812 C<$value>: the value assigned to C<$var> in condition C<$cond>.
813
814 C<$comment>: any comment (C<'# bla.'>) associated with the assignment.
815 Comments from C<+=> assignments stack with comments from the last C<=>
816 assignment.
817
818 C<$where>: the C<Location> of the assignment.
819
820 C<$pretty>: whether C<$value> should be pretty printed (one of
821 C<VAR_ASIS>, C<VAR_PRETTY>, C<VAR_SILENT>, or C<VAR_SORTED>, defined
822 by by L<Automake::VarDef>).  C<$pretty> applies only to real
823 assignments.  I.e., it does not apply to a C<+=> assignment (except
824 when part of it is being done as a conditional C<=> assignment).
825
826 This function will all run any hook registered with the C<hook>
827 function.
828
829 =cut
830
831 sub define ($$$$$$$$)
832 {
833   my ($var, $owner, $type, $cond, $value, $comment, $where, $pretty) = @_;
834
835   prog_error "$cond is not a reference"
836     unless ref $cond;
837
838   prog_error "$where is not a reference"
839     unless ref $where;
840
841   prog_error "pretty argument missing"
842     unless defined $pretty && ($pretty == VAR_ASIS
843                                || $pretty == VAR_PRETTY
844                                || $pretty == VAR_SILENT
845                                || $pretty == VAR_SORTED);
846
847   error $where, "bad characters in variable name `$var'"
848     if $var !~ /$_VARIABLE_PATTERN/o;
849
850   # `:='-style assignments are not acknowledged by POSIX.  Moreover it
851   # has multiple meanings.  In GNU make or BSD make it means "assign
852   # with immediate expansion", while in OSF make it is used for
853   # conditional assignments.
854   msg ('portability', $where, "`:='-style assignments are not portable")
855     if $type eq ':';
856
857   check_variable_expansions ($value, $where);
858
859   # If there's a comment, make sure it is \n-terminated.
860   if ($comment)
861     {
862       chomp $comment;
863       $comment .= "\n";
864     }
865   else
866     {
867       $comment = '';
868     }
869
870   my $self = _cvar $var;
871
872   my $def = $self->def ($cond);
873   my $new_var = $def ? 0 : 1;
874
875   # Additional checks for Automake definitions.
876   if ($owner == VAR_AUTOMAKE && ! $new_var)
877     {
878       # An Automake variable must be consistently defined with the same
879       # sign by Automake.
880       if ($def->type ne $type && $def->owner == VAR_AUTOMAKE)
881         {
882           error ($def->location,
883                  "Automake variable `$var' was set with `"
884                  . $def->type . "=' here ...", partial => 1);
885           error ($where, "... and is now set with `$type=' here.");
886           prog_error ("Automake variable assignments should be consistently\n"
887                       . "defined with the same sign");
888         }
889
890       # If Automake tries to override a value specified by the user,
891       # just don't let it do.
892       if ($def->owner != VAR_AUTOMAKE)
893         {
894           if (! exists $_silent_variable_override{$var})
895             {
896               my $condmsg = ($cond == TRUE
897                              ? '' : (" in condition `" . $cond->human . "'"));
898               msg_cond_var ('override', $cond, $var,
899                             "user variable `$var' defined here$condmsg ...",
900                             partial => 1);
901               msg ('override', $where,
902                    "... overrides Automake variable `$var' defined here");
903             }
904           verb ("refusing to override the user definition of:\n"
905                 . $self->dump ."with `" . $cond->human . "' => `$value'");
906           return;
907         }
908     }
909
910   # Differentiate assignment types.
911
912   # 1. append (+=) to a variable defined for current condition
913   if ($type eq '+' && ! $new_var)
914     {
915       $def->append ($value, $comment);
916       $self->{'last-append'} = [];
917
918       # Only increase owners.  A VAR_CONFIGURE variable augmented in a
919       # Makefile.am becomes a VAR_MAKEFILE variable.
920       $def->set_owner ($owner, $where->clone)
921         if $owner > $def->owner;
922     }
923   # 2. append (+=) to a variable defined for *another* condition
924   elsif ($type eq '+' && ! $self->conditions->false)
925     {
926       # * Generally, $cond is not TRUE.  For instance:
927       #     FOO = foo
928       #     if COND
929       #       FOO += bar
930       #     endif
931       #   In this case, we declare an helper variable conditionally,
932       #   and append it to FOO:
933       #     FOO = foo $(am__append_1)
934       #     @COND_TRUE@am__append_1 = bar
935       #   Of course if FOO is defined under several conditions, we add
936       #   $(am__append_1) to each definitions.
937       #
938       # * If $cond is TRUE, we don't need the helper variable.  E.g., in
939       #     if COND1
940       #       FOO = foo1
941       #     else
942       #       FOO = foo2
943       #     endif
944       #     FOO += bar
945       #   we can add bar directly to all definition of FOO, and output
946       #     @COND_TRUE@FOO = foo1 bar
947       #     @COND_FALSE@FOO = foo2 bar
948
949       my $lastappend = [];
950       # Do we need an helper variable?
951       if ($cond != TRUE)
952         {
953           # Can we reuse the helper variable created for the previous
954           # append?  (We cannot reuse older helper variables because
955           # we must preserve the order of items appended to the
956           # variable.)
957           my $condstr = $cond->string;
958           my $key = "$var:$condstr";
959           my ($appendvar, $appendvarcond) = @{$self->{'last-append'}};
960           if ($appendvar && $condstr eq $appendvarcond)
961             {
962               # Yes, let's simply append to it.
963               $var = $appendvar;
964               $owner = VAR_AUTOMAKE;
965               $self = var ($var);
966               $def = $self->rdef ($cond);
967               $new_var = 0;
968             }
969           else
970             {
971               # No, create it.
972               my $num = ++$_appendvar;
973               my $hvar = "am__append_$num";
974               $lastappend = [$hvar, $condstr];
975               &define ($hvar, VAR_AUTOMAKE, '+',
976                        $cond, $value, $comment, $where, $pretty);
977
978               # Now HVAR is to be added to VAR.
979               $comment = '';
980               $value = "\$($hvar)";
981             }
982         }
983
984       # Add VALUE to all definitions of SELF.
985       foreach my $vcond ($self->conditions->conds)
986         {
987           # We have a bit of error detection to do here.
988           # This:
989           #   if COND1
990           #     X = Y
991           #   endif
992           #   X += Z
993           # should be rejected because X is not defined for all conditions
994           # where `+=' applies.
995           my $undef_cond = $self->not_always_defined_in_cond ($cond);
996           if (! $undef_cond->false)
997             {
998               error ($where,
999                      "cannot apply `+=' because `$var' is not defined "
1000                      . "in\nthe following conditions:\n  "
1001                      . join ("\n  ", map { $_->human } $undef_cond->conds)
1002                      . "\neither define `$var' in these conditions,"
1003                      . " or use\n`+=' in the same conditions as"
1004                      . " the definitions.");
1005             }
1006           else
1007             {
1008               &define ($var, $owner, '+', $vcond, $value, $comment,
1009                        $where, $pretty);
1010             }
1011         }
1012       $self->{'last-append'} = $lastappend;
1013     }
1014   # 3. first assignment (=, :=, or +=)
1015   else
1016     {
1017       # There must be no previous value unless the user is redefining
1018       # an Automake variable or an AC_SUBST variable for an existing
1019       # condition.
1020       _check_ambiguous_condition ($self, $cond, $where)
1021         unless (!$new_var
1022                 && (($def->owner == VAR_AUTOMAKE && $owner != VAR_AUTOMAKE)
1023                     || $def->owner == VAR_CONFIGURE));
1024
1025       # Never decrease an owner.
1026       $owner = $def->owner
1027         if ! $new_var && $owner < $def->owner;
1028
1029       # Assignments to a macro set its location.  We don't adjust
1030       # locations for `+='.  Ideally I suppose we would associate
1031       # line numbers with random bits of text.
1032       $def = new Automake::VarDef ($var, $value, $comment, $where->clone,
1033                                    $type, $owner, $pretty);
1034       $self->set ($cond, $def);
1035       push @_var_order, $var;
1036     }
1037
1038   # Call any defined hook.  This helps to update some internal state
1039   # *while* parsing the file.  For instance the handling of SUFFIXES
1040   # requires this (see var_SUFFIXES_trigger).
1041   &{$_hooks{$var}}($type, $value) if exists $_hooks{$var};
1042 }
1043
1044 =item C<variable_delete ($varname, [@conds])>
1045
1046 Forget about C<$varname> under the conditions C<@conds>, or completely
1047 if C<@conds> is empty.
1048
1049 =cut
1050
1051 sub variable_delete ($@)
1052 {
1053   my ($var, @conds) = @_;
1054
1055   if (!@conds)
1056     {
1057       delete $_variable_dict{$var};
1058     }
1059   else
1060     {
1061       for my $cond (@conds)
1062         {
1063           delete $_variable_dict{$var}{'defs'}{$cond};
1064         }
1065     }
1066   if ($var =~ /_([[:alnum:]]+)$/)
1067     {
1068       delete $_primary_dict{$1}{$var};
1069     }
1070 }
1071
1072 =item C<$str = variables_dump>
1073
1074 Return a string describing all we know about all variables.
1075 For debugging.
1076
1077 =cut
1078
1079 sub variables_dump ()
1080 {
1081   my $text = "all variables:\n{\n";
1082   foreach my $var (sort { $a->name cmp $b->name } variables)
1083     {
1084       $text .= $var->dump;
1085     }
1086   $text .= "}\n";
1087   return $text;
1088 }
1089
1090
1091 =item C<$var = set_seen ($varname)>
1092
1093 =item C<$var = $var-E<gt>set_seen>
1094
1095 Mark all definitions of this variable as examined, if the variable
1096 exists.  See L<Automake::VarDef::set_seen>.
1097
1098 Return the C<Variable> object if the variable exists, or 0
1099 otherwise (i.e., as the C<var> function).
1100
1101 =cut
1102
1103 sub set_seen ($)
1104 {
1105   my ($self) = @_;
1106   $self = ref $self ? $self : var $self;
1107
1108   return 0 unless $self;
1109
1110   for my $c ($self->conditions->conds)
1111     {
1112       $self->rdef ($c)->set_seen;
1113     }
1114
1115   return $self;
1116 }
1117
1118
1119 =item C<$count = require_variables ($where, $reason, $cond, @variables)>
1120
1121 Make sure that each supplied variable is defined in C<$cond>.
1122 Otherwise, issue a warning showing C<$reason> (C<$reason> should be
1123 the reason why these variables are required, for instance C<'option foo
1124 used'>).  If we know which macro can define this variable, hint the
1125 user.  Return the number of undefined variables.
1126
1127 =cut
1128
1129 sub require_variables ($$$@)
1130 {
1131   my ($where, $reason, $cond, @vars) = @_;
1132   my $res = 0;
1133   $reason .= ' but ' unless $reason eq '';
1134
1135   $configure_ac = find_configure_ac
1136     unless defined $configure_ac;
1137
1138  VARIABLE:
1139   foreach my $var (@vars)
1140     {
1141       # Nothing to do if the variable exists.
1142       next VARIABLE
1143         if vardef ($var, $cond);
1144
1145       my $text = "$reason`$var' is undefined\n";
1146       my $v = var $var;
1147       if ($v)
1148         {
1149           my $undef_cond = $v->not_always_defined_in_cond ($cond);
1150           next VARIABLE
1151             if $undef_cond->false;
1152           $text .= ("in the following conditions:\n  "
1153                     . join ("\n  ", map { $_->human } $undef_cond->conds)
1154                     . "\n");
1155         }
1156
1157       ++$res;
1158
1159       if (exists $_am_macro_for_var{$var})
1160         {
1161           my $mac = $_am_macro_for_var{$var};
1162           $text .= "  The usual way to define `$var' is to add "
1163             . "`$mac'\n  to `$configure_ac' and run `aclocal' and "
1164             . "`autoconf' again.";
1165           # aclocal will not warn about undefined macros unless it
1166           # starts with AM_.
1167           $text .= "\n  If `$mac' is in `$configure_ac', make sure\n"
1168             . "  its definition is in aclocal's search path."
1169             unless $mac =~ /^AM_/;
1170         }
1171       elsif (exists $_ac_macro_for_var{$var})
1172         {
1173           $text .= "  The usual way to define `$var' is to add "
1174             . "`$_ac_macro_for_var{$var}'\n  to `$configure_ac' and "
1175             . "run `autoconf' again.";
1176         }
1177
1178       error $where, $text, uniq_scope => US_GLOBAL;
1179     }
1180   return $res;
1181 }
1182
1183 =item C<$count = $var->requires_variables ($reason, @variables)>
1184
1185 Same as C<require_variables>, but a method of Automake::Variable.
1186 C<@variables> should be defined in the same conditions as C<$var> is
1187 defined.
1188
1189 =cut
1190
1191 sub requires_variables ($$@)
1192 {
1193   my ($var, $reason, @args) = @_;
1194   my $res = 0;
1195   for my $cond ($var->conditions->conds)
1196     {
1197       $res += require_variables ($var->rdef ($cond)->location, $reason,
1198                                  $cond, @args);
1199     }
1200   return $res;
1201 }
1202
1203
1204 =item C<variable_value ($var)>
1205
1206 Get the C<TRUE> value of a variable, warn if the variable is
1207 conditionally defined.  C<$var> can be either a variable name
1208 or a C<Automake::Variable> instance (this allows calls such
1209 as C<$var-E<gt>variable_value>).
1210
1211 =cut
1212
1213 sub variable_value ($)
1214 {
1215     my ($var) = @_;
1216     my $v = ref ($var) ? $var : var ($var);
1217     return () unless $v;
1218     $v->check_defined_unconditionally;
1219     my $d = $v->def (TRUE);
1220     return $d ? $d->value : "";
1221 }
1222
1223 =item C<$str = output_variables>
1224
1225 Format definitions for all variables.
1226
1227 =cut
1228
1229 sub output_variables ()
1230 {
1231   my $res = '';
1232   # We output variables it in the same order in which they were
1233   # defined (skipping duplicates).
1234   my @vars = uniq @_var_order;
1235
1236   # Output all the Automake variables.  If the user changed one,
1237   # then it is now marked as VAR_CONFIGURE or VAR_MAKEFILE.
1238   foreach my $var (@vars)
1239     {
1240       my $v = rvar $var;
1241       foreach my $cond ($v->conditions->conds)
1242         {
1243           $res .= $v->output ($cond)
1244             if $v->rdef ($cond)->owner == VAR_AUTOMAKE;
1245         }
1246     }
1247
1248   # Now dump the user variables that were defined.
1249   foreach my $var (@vars)
1250     {
1251       my $v = rvar $var;
1252       foreach my $cond ($v->conditions->conds)
1253         {
1254           $res .= $v->output ($cond)
1255             if $v->rdef ($cond)->owner != VAR_AUTOMAKE;
1256         }
1257     }
1258   return $res;
1259 }
1260
1261 =item C<$var-E<gt>traverse_recursively (&fun_item, &fun_collect, [cond_filter =E<gt> $cond_filter], [inner_expand =E<gt> 1], [skip_ac_subst =E<gt> 1])>
1262
1263 Split the value of the Automake::Variable C<$var> on space, and
1264 traverse its components recursively.
1265
1266 If C<$cond_filter> is an C<Automake::Condition>, process any
1267 conditions which are true when C<$cond_filter> is true.  Otherwise,
1268 process all conditions.
1269
1270 We distinguish two kinds of items in the content of C<$var>.
1271 Terms that look like C<$(foo)> or C<${foo}> are subvariables
1272 and cause recursion.  Other terms are assumed to be filenames.
1273
1274 Each time a filename is encountered, C<&fun_item> is called with the
1275 following arguments:
1276
1277   ($var,        -- the Automake::Variable we are currently
1278                    traversing
1279    $val,        -- the item (i.e., filename) to process
1280    $cond,       -- the Condition for the $var definition we are
1281                    examining (ignoring the recursion context)
1282    $full_cond)  -- the full Condition, taking into account
1283                    conditions inherited from parent variables
1284                    during recursion
1285
1286 If C<inner_expand> is set, variable references occurring in filename
1287 (as in C<$(BASE).ext>) are expanded before the filename is passed to
1288 C<&fun_item>.
1289
1290 If C<skip_ac_subst> is set, Autoconf @substitutions@ will be skipped,
1291 i.e., C<&fun_item> will never be called for them.
1292
1293 C<&fun_item> may return a list of items, they will be passed to
1294 C<&fun_store> later on.  Define C<&fun_item> or @<&fun_store> as
1295 C<undef> when they serve no purpose.
1296
1297 Once all items of a variable have been processed, the result (of the
1298 calls to C<&fun_items>, or of recursive traversals of subvariables)
1299 are passed to C<&fun_collect>.  C<&fun_collect> receives three
1300 arguments:
1301
1302   ($var,         -- the variable being traversed
1303    $parent_cond, -- the Condition inherited from parent
1304                     variables during recursion
1305    @condlist)    -- a list of [$cond, @results] pairs
1306                     where each $cond appear only once, and @result
1307                     are all the results for this condition.
1308
1309 Typically you should do C<$cond->merge ($parent_cond)> to recompute
1310 the C<$full_cond> associated to C<@result>.  C<&fun_collect> may
1311 return a list of items, that will be used as the result of
1312 C<Automake::Variable::traverse_recursively> (the top-level, or its
1313 recursive calls).
1314
1315 =cut
1316
1317 # Contains a stack of `from' and `to' parts of variable
1318 # substitutions currently in force.
1319 my @_substfroms;
1320 my @_substtos;
1321 sub traverse_recursively ($&&;%)
1322 {
1323   ++$_traversal;
1324   @_substfroms = ();
1325   @_substtos = ();
1326   my ($var, $fun_item, $fun_collect, %options) = @_;
1327   my $cond_filter = $options{'cond_filter'};
1328   my $inner_expand = $options{'inner_expand'};
1329   my $skip_ac_subst = $options{'skip_ac_subst'};
1330   return $var->_do_recursive_traversal ($var,
1331                                         $fun_item, $fun_collect,
1332                                         $cond_filter, TRUE, $inner_expand,
1333                                         $skip_ac_subst)
1334 }
1335
1336 # The guts of Automake::Variable::traverse_recursively.
1337 sub _do_recursive_traversal ($$&&$$$$)
1338 {
1339   my ($var, $parent, $fun_item, $fun_collect, $cond_filter, $parent_cond,
1340       $inner_expand, $skip_ac_subst) = @_;
1341
1342   $var->set_seen;
1343
1344   if ($var->{'scanned'} == $_traversal)
1345     {
1346       err_var $var, "variable `" . $var->name() . "' recursively defined";
1347       return ();
1348     }
1349   $var->{'scanned'} = $_traversal;
1350
1351   my @allresults = ();
1352   my $cond_once = 0;
1353   foreach my $cond ($var->conditions->conds)
1354     {
1355       if (ref $cond_filter)
1356         {
1357           # Ignore conditions that don't match $cond_filter.
1358           next if ! $cond->true_when ($cond_filter);
1359           # If we found out several definitions of $var
1360           # match $cond_filter then we are in trouble.
1361           # Tell the user we don't support this.
1362           $var->check_defined_unconditionally ($parent, $parent_cond)
1363             if $cond_once;
1364           $cond_once = 1;
1365         }
1366       my @result = ();
1367       my $full_cond = $cond->merge ($parent_cond);
1368
1369       my @to_process = $var->value_as_list ($cond, $parent, $parent_cond);
1370       while (@to_process)
1371         {
1372           my $val = shift @to_process;
1373           # If $val is a variable (i.e. ${foo} or $(bar), not a filename),
1374           # handle the sub variable recursively.
1375           # (Backslashes before `}' and `)' within brackets are here to
1376           # please Emacs's indentation.)
1377           if ($val =~ /^\$\{([^\}]*)\}$/ || $val =~ /^\$\(([^\)]*)\)$/)
1378             {
1379               my $subvarname = $1;
1380
1381               # If the user uses a losing variable name, just ignore it.
1382               # This isn't ideal, but people have requested it.
1383               next if ($subvarname =~ /\@.*\@/);
1384
1385               # See if the variable is actually a substitution reference
1386               my ($from, $to);
1387               # This handles substitution references like ${foo:.a=.b}.
1388               if ($subvarname =~ /^([^:]*):([^=]*)=(.*)$/o)
1389                 {
1390                   $subvarname = $1;
1391                   $to = $3;
1392                   $from = quotemeta $2;
1393                 }
1394
1395               my $subvar = var ($subvarname);
1396               # Don't recurse into undefined variables.
1397               next unless $subvar;
1398
1399               push @_substfroms, $from;
1400               push @_substtos, $to;
1401
1402               my @res = $subvar->_do_recursive_traversal ($parent,
1403                                                           $fun_item,
1404                                                           $fun_collect,
1405                                                           $cond_filter,
1406                                                           $full_cond,
1407                                                           $inner_expand,
1408                                                           $skip_ac_subst);
1409               push (@result, @res);
1410
1411               pop @_substfroms;
1412               pop @_substtos;
1413
1414               next;
1415             }
1416           # Try to expand variable references inside filenames such as
1417           # `$(NAME).txt'.  We do not handle `:.foo=.bar'
1418           # substitutions, but it would make little sense to use this
1419           # here anyway.
1420           elsif ($inner_expand
1421                  && ($val =~ /\$\{([^\}]*)\}/ || $val =~ /\$\(([^\)]*)\)/))
1422             {
1423               my $subvarname = $1;
1424               my $subvar = var $subvarname;
1425               if ($subvar)
1426                 {
1427                   # Replace the reference by its value, and reschedule
1428                   # for expansion.
1429                   foreach my $c ($subvar->conditions->conds)
1430                     {
1431                       if (ref $cond_filter)
1432                         {
1433                           # Ignore conditions that don't match $cond_filter.
1434                           next if ! $c->true_when ($cond_filter);
1435                           # If we found out several definitions of $var
1436                           # match $cond_filter then we are in trouble.
1437                           # Tell the user we don't support this.
1438                           $subvar->check_defined_unconditionally ($var,
1439                                                                   $full_cond)
1440                             if $cond_once;
1441                           $cond_once = 1;
1442                         }
1443                       my $subval = $subvar->rdef ($c)->value;
1444                       $val =~ s/\$\{$subvarname\}/$subval/g;
1445                       $val =~ s/\$\($subvarname\)/$subval/g;
1446                       unshift @to_process, split (' ', $val);
1447                     }
1448                   next;
1449                 }
1450               # We do not know any variable with this name.  Fall through
1451               # to filename processing.
1452             }
1453           elsif ($skip_ac_subst && $val =~ /^\@.+\@$/)
1454             {
1455               next;
1456             }
1457
1458           if ($fun_item) # $var is a filename we must process
1459             {
1460               my $substnum=$#_substfroms;
1461               while ($substnum >= 0)
1462                 {
1463                   $val =~ s/$_substfroms[$substnum]$/$_substtos[$substnum]/
1464                     if defined $_substfroms[$substnum];
1465                   $substnum -= 1;
1466                 }
1467
1468               # Make sure you update the doc of
1469               # Automake::Variable::traverse_recursively
1470               # if you change the prototype of &fun_item.
1471               my @transformed = &$fun_item ($var, $val, $cond, $full_cond);
1472               push (@result, @transformed);
1473             }
1474         }
1475       push (@allresults, [$cond, @result]) if @result;
1476     }
1477
1478   # We only care about _recursive_ variable definitions.  The user
1479   # is free to use the same variable several times in the same definition.
1480   $var->{'scanned'} = -1;
1481
1482   return ()
1483     unless $fun_collect;
1484   # Make sure you update the doc of Automake::Variable::traverse_recursively
1485   # if you change the prototype of &fun_collect.
1486   return &$fun_collect ($var, $parent_cond, @allresults);
1487 }
1488
1489 # _hash_varname ($VAR)
1490 # --------------------
1491 # Compute the key associated $VAR in %_gen_varname.
1492 # See _gen_varname() below.
1493 sub _hash_varname ($)
1494 {
1495   my ($var) = @_;
1496   my $key = '';
1497   foreach my $cond ($var->conditions->conds)
1498     {
1499       my @values = $var->value_as_list ($cond);
1500       $key .= "($cond)@values";
1501     }
1502   return $key;
1503 }
1504
1505 # _hash_values (@VALUES)
1506 # ----------------------
1507 # Hash @VALUES for %_gen_varname.  @VALUES should be a list
1508 # of pairs: ([$cond, @values], [$cond, @values], ...).
1509 # See _gen_varname() below.
1510 sub _hash_values (@)
1511 {
1512   my $key = '';
1513   foreach my $pair (@_)
1514     {
1515       my ($cond, @values) = @$pair;
1516       $key .= "($cond)@values";
1517     }
1518   return $key;
1519 }
1520 # ($VARNAME, $GENERATED)
1521 # _gen_varname ($BASE, @DEFINITIONS)
1522 # ----------------------------------
1523 # Return a variable name starting with $BASE, that will be
1524 # used to store definitions @DEFINITIONS.
1525 # @DEFINITIONS is a list of pair [$COND, @OBJECTS].
1526 #
1527 # If we already have a $BASE-variable containing @DEFINITIONS, reuse
1528 # it and set $GENERATED to 0.  Otherwise construct a new name and set
1529 # $GENERATED to 1.
1530 #
1531 # This way, we avoid combinatorial explosion of the generated
1532 # variables.  Especially, in a Makefile such as:
1533 #
1534 # | if FOO1
1535 # | A1=1
1536 # | endif
1537 # |
1538 # | if FOO2
1539 # | A2=2
1540 # | endif
1541 # |
1542 # | ...
1543 # |
1544 # | if FOON
1545 # | AN=N
1546 # | endif
1547 # |
1548 # | B=$(A1) $(A2) ... $(AN)
1549 # |
1550 # | c_SOURCES=$(B)
1551 # | d_SOURCES=$(B)
1552 #
1553 # The generated c_OBJECTS and d_OBJECTS will share the same variable
1554 # definitions.
1555 #
1556 # This setup can be the case of a testsuite containing lots (>100) of
1557 # small C programs, all testing the same set of source files.
1558 sub _gen_varname ($@)
1559 {
1560   my $base = shift;
1561   my $key = _hash_values @_;
1562
1563   return ($_gen_varname{$base}{$key}, 0)
1564     if exists $_gen_varname{$base}{$key};
1565
1566   my $num = 1 + ($_gen_varname_n{$base} || 0);
1567   $_gen_varname_n{$base} = $num;
1568   my $name = "${base}_${num}";
1569   $_gen_varname{$base}{$key} = $name;
1570
1571   return ($name, 1);
1572 }
1573
1574 =item C<$resvar = transform_variable_recursively ($var, $resvar, $base, $nodefine, $where, &fun_item, [%options])>
1575
1576 =item C<$resvar = $var-E<gt>transform_variable_recursively ($resvar, $base, $nodefine, $where, &fun_item, [%options])>
1577
1578 Traverse C<$var> recursively, and create a C<$resvar> variable in
1579 which each filename in C<$var> have been transformed using
1580 C<&fun_item>.  (C<$var> may be a variable name in the first syntax.
1581 It must be an C<Automake::Variable> otherwise.)
1582
1583 Helper variables (corresponding to sub-variables of C<$var>) are
1584 created as needed, using C<$base> as prefix.
1585
1586 Arguments are:
1587   $var       source variable to traverse
1588   $resvar    resulting variable to define
1589   $base      prefix to use when naming subvariables of $resvar
1590   $nodefine  if true, traverse $var but do not define any variable
1591              (this assumes &fun_item has some useful side-effect)
1592   $where     context into which variable definitions are done
1593   &fun_item  a transformation function -- see the documentation
1594              of &fun_item in Automake::Variable::traverse_recursively.
1595
1596 This returns the string C<"\$($RESVAR)">.
1597
1598 C<%options> is a list of options to pass to
1599 C<Variable::traverse_recursively> (see this method).
1600
1601 =cut
1602
1603 sub transform_variable_recursively ($$$$$&;%)
1604 {
1605   my ($var, $resvar, $base, $nodefine, $where, $fun_item, %options) = @_;
1606
1607   $var = ref $var ? $var : rvar $var;
1608
1609   my $res = $var->traverse_recursively
1610     ($fun_item,
1611      # The code that defines the variable holding the result
1612      # of the recursive transformation of a subvariable.
1613      sub {
1614        my ($subvar, $parent_cond, @allresults) = @_;
1615        # If no definition is required, return anything: the result is
1616        # not expected to be used, only the side effect of $fun_item
1617        # should matter.
1618        return 'report-me' if $nodefine;
1619        # Cache $subvar, so that we reuse it if @allresults is the same.
1620        my $key = _hash_varname $subvar;
1621        $_gen_varname{$base}{$key} = $subvar->name;
1622
1623        # Find a name for the variable, unless this is the top-variable
1624        # for which we want to use $resvar.
1625        my ($varname, $generated) =
1626          ($var != $subvar) ? _gen_varname ($base, @allresults) : ($resvar, 1);
1627
1628        # Define the variable if we are not reusing a previously
1629        # defined variable.  At the top-level, we can also avoid redefining
1630        # the variable if it already contains the same values.
1631        if ($generated
1632            && !($varname eq $var->name && $key eq _hash_values @allresults))
1633          {
1634            # If the new variable is the source variable, we assume
1635            # we are trying to override a user variable.  Delete
1636            # the old variable first.
1637            variable_delete ($varname) if $varname eq $var->name;
1638            # Define an empty variable in condition TRUE if there is no
1639            # result.
1640            @allresults = ([TRUE, '']) unless @allresults;
1641            # Define the rewritten variable in all conditions not
1642            # already covered by user definitions.
1643            foreach my $pair (@allresults)
1644              {
1645                my ($cond, @result) = @$pair;
1646                my $var = var $varname;
1647                my @conds = ($var
1648                             ? $var->not_always_defined_in_cond ($cond)->conds
1649                             : $cond);
1650
1651                foreach (@conds)
1652                  {
1653                    define ($varname, VAR_AUTOMAKE, '', $_, "@result",
1654                            '', $where, VAR_PRETTY);
1655                  }
1656              }
1657          }
1658        set_seen $varname;
1659        return "\$($varname)";
1660      },
1661      %options);
1662   return $res;
1663 }
1664
1665
1666 =back
1667
1668 =head1 SEE ALSO
1669
1670 L<Automake::VarDef>, L<Automake::Condition>,
1671 L<Automake::DisjConditions>, L<Automake::Location>.
1672
1673 =cut
1674
1675 1;
1676
1677 ### Setup "GNU" style for perl-mode and cperl-mode.
1678 ## Local Variables:
1679 ## perl-indent-level: 2
1680 ## perl-continued-statement-offset: 2
1681 ## perl-continued-brace-offset: 0
1682 ## perl-brace-offset: 0
1683 ## perl-brace-imaginary-offset: 0
1684 ## perl-label-offset: -2
1685 ## cperl-indent-level: 2
1686 ## cperl-brace-offset: 0
1687 ## cperl-continued-brace-offset: 0
1688 ## cperl-label-offset: -2
1689 ## cperl-extra-newline-before-brace: t
1690 ## cperl-merge-trailing-else: nil
1691 ## cperl-continued-statement-offset: 2
1692 ## End: