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