File Coverage

File:/usr/local/share/automake-1.11/Automake/Variable.pm
Coverage:11.7%

linestmtbrancondsubpodtimecode
1# Copyright (C) 2003, 2004, 2005, 2006, 2008, 2009 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
16package Automake::Variable;
17
1
1
1
5
1
5
use strict;
18
1
1
1
4
1
3
use Carp;
19
20
1
1
1
4
1
2
use Automake::Channels;
21
1
1
1
4
1
2
use Automake::ChannelDefs;
22
1
1
1
4
1
3
use Automake::Configure_ac;
23
1
1
1
10
1
7
use Automake::Item;
24
1
1
1
12
1
7
use Automake::VarDef;
25
1
1
1
4
1
4
use Automake::Condition qw (TRUE FALSE);
26
1
1
1
4
1
2
use Automake::DisjConditions;
27
1
1
1
4
1
6
use Automake::General 'uniq';
28
1
1
1
11
1
6
use Automake::Wrap 'makefile_wrap';
29
30require Exporter;
31
1
1
1
4
1
2
use vars '@ISA', '@EXPORT', '@EXPORT_OK';
32@ISA = qw/Automake::Item Exporter/;
33@EXPORT = qw (err_var msg_var msg_cond_var reject_var
34              var rvar vardef rvardef
35              variables
36              scan_variable_expansions check_variable_expansions
37              variable_delete
38              variables_dump
39              set_seen
40              require_variables
41              variable_value
42              output_variables
43              transform_variable_recursively);
44
45 - 129
=head1 NAME

Automake::Variable - support for variable definitions

=head1 SYNOPSIS

  use Automake::Variable;
  use Automake::VarDef;

  # Defining a variable.
  Automake::Variable::define($varname, $owner, $type,
                             $cond, $value, $comment,
                             $where, $pretty)

  # Looking up a variable.
  my $var = var $varname;
  if ($var)
    {
      ...
    }

  # Looking up a variable that is assumed to exist.
  my $var = rvar $varname;

  # The list of conditions where $var has been defined.
  # ($var->conditions is an Automake::DisjConditions,
  # $var->conditions->conds is a list of Automake::Condition.)
  my @conds = $var->conditions->conds

  # Access to the definition in Condition $cond.
  # $def is an Automake::VarDef.
  my $def = $var->def ($cond);
  if ($def)
    {
      ...
    }

  # When the conditional definition is assumed to exist, use
  my $def = $var->rdef ($cond);


=head1 DESCRIPTION

This package provides support for Makefile variable definitions.

An C<Automake::Variable> is a variable name associated to possibly
many conditional definitions.  These definitions are instances
of C<Automake::VarDef>.

Therefore obtaining the value of a variable under a given
condition involves two lookups.  One to look up the variable,
and one to look up the conditional definition:

  my $var = var $name;
  if ($var)
    {
      my $def = $var->def ($cond);
      if ($def)
        {
          return $def->value;
        }
      ...
    }
  ...

When it is known that the variable and the definition
being looked up exist, the above can be simplified to

  return var ($name)->def ($cond)->value; # Do not write this.

but is better written

  return rvar ($name)->rdef ($cond)->value;

or even

  return rvardef ($name, $cond)->value;

The I<r> variants of the C<var>, C<def>, and C<vardef> methods add an
extra test to ensure that the lookup succeeded, and will diagnose
failures as internal errors (with a message which is much more
informative than Perl's warning about calling a method on a
non-object).

=cut
130
131my $_VARIABLE_CHARACTERS = '[.A-Za-z0-9_@]+';
132my $_VARIABLE_PATTERN = '^' . $_VARIABLE_CHARACTERS . "\$";
133my $_VARIABLE_RECURSIVE_PATTERN =
134    '^([.A-Za-z0-9_@]|\$[({]' . $_VARIABLE_CHARACTERS . '[})]?)+' . "\$";
135
136# The order in which variables should be output. (May contain
137# duplicates -- only the first occurrence matters.)
138my @_var_order;
139
140# This keeps track of all variables defined by &_gen_varname.
141# $_gen_varname{$base} is a hash for all variables defined with
142# prefix `$base'. Values stored in this hash are the variable names.
143# Keys have the form "(COND1)VAL1(COND2)VAL2..." where VAL1 and VAL2
144# are the values of the variable for condition COND1 and COND2.
145my %_gen_varname = ();
146# $_gen_varname_n{$base} is the number of variables generated by
147# _gen_varname() for $base. This is not the same as keys
148# %{$_gen_varname{$base}} because %_gen_varname may also contain
149# variables not generated by _gen_varname.
150my %_gen_varname_n = ();
151
152# Declare the macros that define known variables, so we can
153# hint the user if she try to use one of these variables.
154
155# Macros accessible via aclocal.
156my %_am_macro_for_var =
157  (
158   ANSI2KNR => 'AM_C_PROTOTYPES',
159   CCAS => 'AM_PROG_AS',
160   CCASFLAGS => 'AM_PROG_AS',
161   EMACS => 'AM_PATH_LISPDIR',
162   GCJ => 'AM_PROG_GCJ',
163   LEX => 'AM_PROG_LEX',
164   LIBTOOL => 'AC_PROG_LIBTOOL',
165   lispdir => 'AM_PATH_LISPDIR',
166   pkgpyexecdir => 'AM_PATH_PYTHON',
167   pkgpythondir => 'AM_PATH_PYTHON',
168   pyexecdir => 'AM_PATH_PYTHON',
169   PYTHON => 'AM_PATH_PYTHON',
170   pythondir => 'AM_PATH_PYTHON',
171   U => 'AM_C_PROTOTYPES',
172   );
173
174# Macros shipped with Autoconf.
175my %_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   F77FLAGS => 'AC_PROG_F77',
184   FC => 'AC_PROG_FC',
185   FCFLAGS => 'AC_PROG_FC',
186   OBJC => 'AC_PROG_OBJC',
187   OBJCFLAGS => 'AC_PROG_OBJC',
188   RANLIB => 'AC_PROG_RANLIB',
189   UPC => 'AM_PROG_UPC',
190   UPCFLAGS => 'AM_PROG_UPC',
191   YACC => 'AC_PROG_YACC',
192   );
193
194# The name of the configure.ac file.
195my $configure_ac = find_configure_ac;
196
197# Variables that can be overridden without complaint from -Woverride
198my %_silent_variable_override =
199  (AM_MAKEINFOHTMLFLAGS => 1,
200   AR => 1,
201   ARFLAGS => 1,
202   DEJATOOL => 1,
203   JAVAC => 1,
204   JAVAROOT => 1);
205
206# Count of helper variables used to implement conditional '+='.
207my $_appendvar;
208
209# Each call to C<Automake::Variable::traverse_recursively> gets an
210# unique label. This is used to detect recursively defined variables.
211my $_traversal = 0;
212
213
214 - 225
=head2 Error reporting functions

In these functions, C<$var> can be either a variable name, or
an instance of C<Automake::Variable>.

=over 4

=item C<err_var ($var, $message, [%options])>

Uncategorized errors about variables.

=cut
226
227sub err_var ($$;%)
228{
229
0
1
0
  msg_var ('error', @_);
230}
231
232 - 236
=item C<msg_cond_var ($channel, $cond, $var, $message, [%options])>

Messages about conditional variable.

=cut
237
238sub msg_cond_var ($$$$;%)
239{
240
0
1
0
  my ($channel, $cond, $var, $msg, %opts) = @_;
241
0
0
  my $v = ref ($var) ? $var : rvar ($var);
242
0
0
  msg $channel, $v->rdef ($cond)->location, $msg, %opts;
243}
244
245 - 249
=item C<msg_var ($channel, $var, $message, [%options])>

Messages about variables.

=cut
250
251sub msg_var ($$$;%)
252{
253
0
1
0
  my ($channel, $var, $msg, %opts) = @_;
254
0
0
  my $v = ref ($var) ? $var : rvar ($var);
255  # Don't know which condition is concerned. Pick any.
256
0
0
  my $cond = $v->conditions->one_cond;
257
0
0
  msg_cond_var $channel, $cond, $v, $msg, %opts;
258}
259
260 - 267
=item C<$bool = reject_var ($varname, $error_msg)>

Bail out with C<$error_msg> if a variable with name C<$varname> has
been defined.

Return true iff C<$varname> is defined.

=cut
268
269sub reject_var ($$)
270{
271
0
1
0
  my ($var, $msg) = @_;
272
0
0
  my $v = var ($var);
273
0
0
  if ($v)
274    {
275
0
0
      err_var $v, $msg;
276
0
0
      return 1;
277    }
278
0
0
  return 0;
279}
280
281=back
282
283 - 297
=head2 Administrative functions

=over 4

=item C<Automake::Variable::hook ($varname, $fun)>

Declare a function to be called whenever a variable
named C<$varname> is defined or redefined.

C<$fun> should take two arguments: C<$type> and C<$value>.
When type is C<''> or <':'>, C<$value> is the value being
assigned to C<$varname>.  When C<$type> is C<'+'>, C<$value>
is the value being appended to  C<$varname>.

=cut
298
299
1
1
1
4
1
3
use vars '%_hooks';
300sub hook ($$)
301{
302
1
1
3
  my ($var, $fun) = @_;
303
1
3
  $_hooks{$var} = $fun;
304}
305
306 - 312
=item C<variables ([$suffix])>

Returns the list of all L<Automake::Variable> instances.  (I.e., all
variables defined so far.)  If C<$suffix> is supplied, return only
the L<Automake::Variable> instances that ends with C<_$suffix>.

=cut
313
314
1
1
1
4
1
6
use vars '%_variable_dict', '%_primary_dict';
315sub variables (;$)
316{
317
0
1
  my ($suffix) = @_;
318
0
  if ($suffix)
319    {
320
0
      if (exists $_primary_dict{$suffix})
321        {
322
0
0
          return values %{$_primary_dict{$suffix}};
323        }
324      else
325        {
326
0
          return ();
327        }
328    }
329  else
330    {
331
0
      return values %_variable_dict;
332    }
333}
334
335 - 340
=item C<Automake::Variable::reset>

The I<forget all> function.  Clears all know variables and reset some
other internal data.

=cut
341
342sub reset ()
343{
344
0
1
  %_variable_dict = ();
345
0
  %_primary_dict = ();
346
0
  $_appendvar = 0;
347
0
  @_var_order = ();
348
0
  %_gen_varname = ();
349
0
  %_gen_varname_n = ();
350
0
  $_traversal = 0;
351}
352
353 - 358
=item C<var ($varname)>

Return the C<Automake::Variable> object for the variable
named C<$varname> if defined.   Return 0 otherwise.

=cut
359
360sub var ($)
361{
362
0
1
  my ($name) = @_;
363
0
  return $_variable_dict{$name} if exists $_variable_dict{$name};
364
0
  return 0;
365}
366
367 - 373
=item C<vardef ($varname, $cond)>

Return the C<Automake::VarDef> object for the variable named
C<$varname> if defined in condition C<$cond>.  Return false
if the condition or the variable does not exist.

=cut
374
375sub vardef ($$)
376{
377
0
1
  my ($name, $cond) = @_;
378
0
  my $var = var $name;
379
0
  return $var && $var->def ($cond);
380}
381
382# Create the variable if it does not exist.
383# This is used only by other functions in this package.
384sub _cvar ($)
385{
386
0
  my ($name) = @_;
387
0
  my $v = var $name;
388
0
  return $v if $v;
389
0
  return _new Automake::Variable $name;
390}
391
392 - 401
=item C<rvar ($varname)>

Return the C<Automake::Variable> object for the variable named
C<$varname>.  Abort with an internal error if the variable was not
defined.

The I<r> in front of C<var> stands for I<required>.  One
should call C<rvar> to assert the variable's existence.

=cut
402
403sub rvar ($)
404{
405
0
1
  my ($name) = @_;
406
0
  my $v = var $name;
407
0
  prog_error ("undefined variable $name\n" . &variables_dump)
408    unless $v;
409
0
  return $v;
410}
411
412 - 418
=item C<rvardef ($varname, $cond)>

Return the C<Automake::VarDef> object for the variable named
C<$varname> if defined in condition C<$cond>.  Abort with an internal
error if the condition or the variable does not exist.

=cut
419
420sub rvardef ($$)
421{
422
0
1
  my ($name, $cond) = @_;
423
0
  return rvar ($name)->rdef ($cond);
424}
425
426=back
427
428 - 438
=head2 Methods

C<Automake::Variable> is a subclass of C<Automake::Item>.  See
that package for inherited methods.

Here are the methods specific to the C<Automake::Variable> instances.
Use the C<define> function, described latter, to create such objects.

=over 4

=cut
439
440# Create Automake::Variable objects. This is used
441# only in this file. Other users should use
442# the "define" function.
443sub _new ($$)
444{
445
0
  my ($class, $name) = @_;
446
0
  my $self = Automake::Item::new ($class, $name);
447
0
  $self->{'scanned'} = 0;
448
0
  $self->{'last-append'} = []; # helper variable for last conditional append.
449
0
  $_variable_dict{$name} = $self;
450
0
  if ($name =~ /_([[:alnum:]]+)$/)
451    {
452
0
      $_primary_dict{$1}{$name} = $self;
453    }
454
0
  return $self;
455}
456
457# _check_ambiguous_condition ($SELF, $COND, $WHERE)
458# -------------------------------------------------
459# Check for an ambiguous conditional. This is called when a variable
460# is being defined conditionally. If we already know about a
461# definition that is true under the same conditions, then we have an
462# ambiguity.
463sub _check_ambiguous_condition ($$$)
464{
465
0
  my ($self, $cond, $where) = @_;
466
0
  my $var = $self->name;
467
0
  my ($message, $ambig_cond) = $self->conditions->ambiguous_p ($var, $cond);
468
469  # We allow silent variables to be overridden silently,
470  # by either silent or non-silent variables.
471
0
  my $def = $self->def ($ambig_cond);
472
0
  if ($message && !($def && $def->pretty == VAR_SILENT))
473    {
474
0
      msg 'syntax', $where, "$message ...", partial => 1;
475
0
      msg_var ('syntax', $var, "... `$var' previously defined here");
476
0
      verb ($self->dump);
477    }
478}
479
480 - 486
=item C<$bool = $var-E<gt>check_defined_unconditionally ([$parent, $parent_cond])>

Warn if the variable is conditionally defined.  C<$parent> is the name
of the parent variable, and C<$parent_cond> the condition of the parent
definition.  These two variables are used to display diagnostics.

=cut
487
488sub check_defined_unconditionally ($;$$)
489{
490
0
1
  my ($self, $parent, $parent_cond) = @_;
491
492
0
  if (!$self->conditions->true)
493    {
494
0
      if ($parent)
495        {
496
0
          msg_cond_var ('unsupported', $parent_cond, $parent,
497                        "automake does not support conditional definition of "
498                        . $self->name . " in $parent");
499        }
500      else
501        {
502
0
          msg_var ('unsupported', $self,
503                   "automake does not support " . $self->name
504                   . " being defined conditionally");
505        }
506    }
507}
508
509 - 514
=item C<$str = $var-E<gt>output ([@conds])>

Format all the definitions of C<$var> if C<@cond> is not specified,
else only that corresponding to C<@cond>.

=cut
515
516sub output ($@)
517{
518
0
1
  my ($self, @conds) = @_;
519
520
0
  @conds = $self->conditions->conds
521    unless @conds;
522
523
0
  my $res = '';
524
0
  my $name = $self->name;
525
526
0
  foreach my $cond (@conds)
527    {
528
0
      my $def = $self->def ($cond);
529
0
      prog_error ("unknown condition `" . $cond->human . "' for `"
530                  . $self->name . "'")
531        unless $def;
532
533      next
534
0
        if $def->pretty == VAR_SILENT;
535
536
0
      $res .= $def->comment;
537
538
0
      my $val = $def->raw_value;
539
0
      my $equals = $def->type eq ':' ? ':=' : '=';
540
0
      my $str = $cond->subst_string;
541
542
543
0
      if ($def->pretty == VAR_ASIS)
544        {
545
0
          my $output_var = "$name $equals $val";
546
0
0
          $output_var =~ s/^/$str/meg;
547
0
          $res .= "$output_var\n";
548        }
549      elsif ($def->pretty == VAR_PRETTY)
550        {
551          # Suppress escaped new lines. &makefile_wrap will
552          # add them back, maybe at other places.
553
0
          $val =~ s/\\$//mg;
554
0
          my $wrap = makefile_wrap ("$str$name $equals", "$str\t",
555                                    split (' ', $val));
556
557          # If the last line of the definition is made only of
558          # @substitutions@, append an empty variable to make sure it
559          # cannot be substituted as a blank line (that would confuse
560          # HP-UX Make).
561
0
          $wrap = makefile_wrap ("$str$name $equals", "$str\t",
562                                 split (' ', $val), '$(am__empty)')
563            if $wrap =~ /\n(\s*@\w+@)+\s*$/;
564
565
0
          $res .= $wrap;
566        }
567      else # ($def->pretty == VAR_SORTED)
568        {
569          # Suppress escaped new lines. &makefile_wrap will
570          # add them back, maybe at other places.
571
0
          $val =~ s/\\$//mg;
572
0
          $res .= makefile_wrap ("$str$name $equals", "$str\t",
573                                 sort (split (' ' , $val)));
574        }
575    }
576
0
  return $res;
577}
578
579 - 596
=item C<@values = $var-E<gt>value_as_list ($cond, [$parent, $parent_cond])>

Get the value of C<$var> as a list, given a specified condition,
without recursing through any subvariables.

C<$cond> is the condition of interest.  C<$var> does not need
to be defined for condition C<$cond> exactly, but it needs
to be defined for at most one condition implied by C<$cond>.

C<$parent> and C<$parent_cond> designate the name and the condition
of the parent variable, i.e., the variable in which C<$var> is
being expanded.  These are used in diagnostics.

For example, if C<A> is defined as "C<foo $(B) bar>" in condition
C<TRUE>, calling C<rvar ('A')->value_as_list (TRUE)> will return
C<("foo", "$(B)", "bar")>.

=cut
597
598sub value_as_list ($$;$$)
599{
600
0
1
  my ($self, $cond, $parent, $parent_cond) = @_;
601
0
  my @result;
602
603  # Get value for given condition
604
0
  my $onceflag;
605
0
  foreach my $vcond ($self->conditions->conds)
606    {
607
0
      if ($vcond->true_when ($cond))
608        {
609          # If there is more than one definitions of $var matching
610          # $cond then we are in trouble: tell the user we need a
611          # paddle. Continue by merging results from all conditions,
612          # although it doesn't make much sense.
613
0
          $self->check_defined_unconditionally ($parent, $parent_cond)
614            if $onceflag;
615
0
          $onceflag = 1;
616
617
0
          my $val = $self->rdef ($vcond)->value;
618
0
          push @result, split (' ', $val);
619        }
620    }
621
0
  return @result;
622}
623
624 - 642
=item C<@values = $var-E<gt>value_as_list_recursive ([%options])>

Return the contents of C<$var> as a list, split on whitespace.  This
will recursively follow C<$(...)> and C<${...}> inclusions.  It
preserves C<@...@> substitutions.

C<%options> is a list of option for C<Variable::traverse_recursively>
(see this method).  The most useful is C<cond_filter>:

  $var->value_as_list_recursive (cond_filter => $cond)

will return the contents of C<$var> and any subvariable in all
conditions implied by C<$cond>.

C<%options> can also carry options specific to C<value_as_list_recursive>.
Presently, the only such option is C<location =E<gt> 1> which instructs
C<value_as_list_recursive> to return a list of C<[$location, @values]> pairs.

=cut
643
644sub value_as_list_recursive ($;%)
645{
646
0
1
  my ($var, %options) = @_;
647
648  return $var->traverse_recursively
649    (# Construct [$location, $value] pairs if requested.
650     sub {
651
0
       my ($var, $val, $cond, $full_cond) = @_;
652
0
       return [$var->rdef ($cond)->location, $val] if $options{'location'};
653
0
       return $val;
654     },
655     # Collect results.
656     sub {
657
0
       my ($var, $parent_cond, @allresults) = @_;
658
0
0
0
       return map { my ($cond, @vals) = @$_; @vals } @allresults;
659     },
660
0
     %options);
661}
662
663
664 - 669
=item C<$bool = $var-E<gt>has_conditional_contents>

Return 1 if C<$var> or one of its subvariable was conditionally
defined.  Return 0 otherwise.

=cut
670
671sub has_conditional_contents ($)
672{
673
0
1
  my ($self) = @_;
674
675  # Traverse the variable recursively until we
676  # find a variable defined conditionally.
677  # Use `die' to abort the traversal, and pass it `$full_cond'
678  # to we can find easily whether the `eval' block aborted
679  # because we found a condition, or for some other error.
680  eval
681
0
    {
682      $self->traverse_recursively
683        (sub
684         {
685
0
           my ($subvar, $val, $cond, $full_cond) = @_;
686
0
           die $full_cond if ! $full_cond->true;
687
0
           return ();
688         },
689
0
0
         sub { return (); });
690    };
691
0
  if ($@)
692    {
693
0
      return 1 if ref ($@) && $@->isa ("Automake::Condition");
694      # Propagate other errors.
695
0
      die;
696    }
697
0
  return 0;
698}
699
700
701 - 706
=item C<$string = $var-E<gt>dump>

Return a string describing all we know about C<$var>.
For debugging.

=cut
707
708sub dump ($)
709{
710
0
1
  my ($self) = @_;
711
712
0
  my $text = $self->name . ": \n {\n";
713
0
  foreach my $vcond ($self->conditions->conds)
714    {
715
0
      $text .= " " . $vcond->human . " => " . $self->rdef ($vcond)->dump;
716    }
717
0
  $text .= " }\n";
718
0
  return $text;
719}
720
721
722=back
723
724 - 734
=head2 Utility functions

=over 4

=item C<@list = scan_variable_expansions ($text)>

Return the list of variable names expanded in C<$text>.  Note that
unlike some other functions, C<$text> is not split on spaces before we
check for subvariables.

=cut
735
736sub scan_variable_expansions ($)
737{
738
0
1
  my ($text) = @_;
739
0
  my @result = ();
740
741  # Strip comments.
742
0
  $text =~ s/#.*$//;
743
744  # Record each use of ${stuff} or $(stuff) that does not follow a $.
745
0
  while ($text =~ /(?<!\$)\$(?:\{([^\}]*)\}|\(([^\)]*)\))/g)
746    {
747
0
      my $var = $1 || $2;
748      # The occurrence may look like $(string1[:subst1=[subst2]]) but
749      # we want only `string1'.
750
0
      $var =~ s/:[^:=]*=[^=]*$//;
751
0
      push @result, $var;
752    }
753
754
0
  return @result;
755}
756
757 - 763
=item C<check_variable_expansions ($text, $where)>

Check variable expansions in C<$text> and warn about any name that
does not conform to POSIX.  C<$where> is the location of C<$text>
for the error message.

=cut
764
765sub check_variable_expansions ($$)
766{
767
0
1
  my ($text, $where) = @_;
768  # Catch expansion of variables whose name does not conform to POSIX.
769
0
  foreach my $var (scan_variable_expansions ($text))
770    {
771
0
      if ($var !~ /$_VARIABLE_PATTERN/o)
772        {
773          # If the variable name contains a space, it's likely
774          # to be a GNU make extension (such as $(addsuffix ...)).
775          # Mention this in the diagnostic.
776
0
          my $gnuext = "";
777
0
          $gnuext = "\n(probably a GNU make extension)" if $var =~ / /;
778          # Accept recursive variable expansions if so desired
779          # (we hope they are rather portable in practice).
780
0
          if ($var =~ /$_VARIABLE_RECURSIVE_PATTERN/o)
781            {
782
0
              msg ('portability-recursive', $where,
783                   "$var: non-POSIX recursive variable expansion$gnuext");
784            }
785          else
786            {
787
0
              msg ('portability', $where, "$var: non-POSIX variable name$gnuext");
788            }
789        }
790    }
791}
792
793
794
795 - 828
=item C<Automake::Variable::define($varname, $owner, $type, $cond, $value, $comment, $where, $pretty)>

Define or append to a new variable.

C<$varname>: the name of the variable being defined.

C<$owner>: owner of the variable (one of C<VAR_MAKEFILE>,
C<VAR_CONFIGURE>, or C<VAR_AUTOMAKE>, defined by L<Automake::VarDef>).
Variables can be overridden, provided the new owner is not weaker
(C<VAR_AUTOMAKE> < C<VAR_CONFIGURE> < C<VAR_MAKEFILE>).

C<$type>: the type of the assignment (C<''> for C<FOO = bar>,
C<':'> for C<FOO := bar>, and C<'+'> for C<'FOO += bar'>).

C<$cond>: the C<Condition> in which C<$var> is being defined.

C<$value>: the value assigned to C<$var> in condition C<$cond>.

C<$comment>: any comment (C<'# bla.'>) associated with the assignment.
Comments from C<+=> assignments stack with comments from the last C<=>
assignment.

C<$where>: the C<Location> of the assignment.

C<$pretty>: whether C<$value> should be pretty printed (one of
C<VAR_ASIS>, C<VAR_PRETTY>, C<VAR_SILENT>, or C<VAR_SORTED>, defined
by by L<Automake::VarDef>).  C<$pretty> applies only to real
assignments.  I.e., it does not apply to a C<+=> assignment (except
when part of it is being done as a conditional C<=> assignment).

This function will all run any hook registered with the C<hook>
function.

=cut
829
830sub define ($$$$$$$$)
831{
832
0
1
  my ($var, $owner, $type, $cond, $value, $comment, $where, $pretty) = @_;
833
834
0
  prog_error "$cond is not a reference"
835    unless ref $cond;
836
837
0
  prog_error "$where is not a reference"
838    unless ref $where;
839
840
0
  prog_error "pretty argument missing"
841    unless defined $pretty && ($pretty == VAR_ASIS
842                               || $pretty == VAR_PRETTY
843                               || $pretty == VAR_SILENT
844                               || $pretty == VAR_SORTED);
845
846
0
  error $where, "bad characters in variable name `$var'"
847    if $var !~ /$_VARIABLE_PATTERN/o;
848
849  # `:='-style assignments are not acknowledged by POSIX. Moreover it
850  # has multiple meanings. In GNU make or BSD make it means "assign
851  # with immediate expansion", while in OSF make it is used for
852  # conditional assignments.
853
0
  msg ('portability', $where, "`:='-style assignments are not portable")
854    if $type eq ':';
855
856
0
  check_variable_expansions ($value, $where);
857
858  # If there's a comment, make sure it is \n-terminated.
859
0
  if ($comment)
860    {
861
0
      chomp $comment;
862
0
      $comment .= "\n";
863    }
864  else
865    {
866
0
      $comment = '';
867    }
868
869
0
  my $self = _cvar $var;
870
871
0
  my $def = $self->def ($cond);
872
0
  my $new_var = $def ? 0 : 1;
873
874  # Additional checks for Automake definitions.
875
0
  if ($owner == VAR_AUTOMAKE && ! $new_var)
876    {
877      # An Automake variable must be consistently defined with the same
878      # sign by Automake.
879
0
      if ($def->type ne $type && $def->owner == VAR_AUTOMAKE)
880        {
881
0
          error ($def->location,
882                 "Automake variable `$var' was set with `"
883                 . $def->type . "=' here...", partial => 1);
884
0
          error ($where, "... and is now set with `$type=' here.");
885
0
          prog_error ("Automake variable assignments should be consistently\n"
886                      . "defined with the same sign.");
887        }
888
889      # If Automake tries to override a value specified by the user,
890      # just don't let it do.
891
0
      if ($def->owner != VAR_AUTOMAKE)
892        {
893
0
          if (! exists $_silent_variable_override{$var})
894            {
895
0
              my $condmsg = ($cond == TRUE
896                             ? '' : (" in condition `" . $cond->human . "'"));
897
0
              msg_cond_var ('override', $cond, $var,
898                            "user variable `$var' defined here$condmsg...",
899                            partial => 1);
900
0
              msg ('override', $where,
901                   "... overrides Automake variable `$var' defined here");
902            }
903
0
          verb ("refusing to override the user definition of:\n"
904                . $self->dump ."with `" . $cond->human . "' => `$value'");
905
0
          return;
906        }
907    }
908
909  # Differentiate assignment types.
910
911  # 1. append (+=) to a variable defined for current condition
912
0
  if ($type eq '+' && ! $new_var)
913    {
914
0
      $def->append ($value, $comment);
915
0
      $self->{'last-append'} = [];
916
917      # Only increase owners. A VAR_CONFIGURE variable augmented in a
918      # Makefile.am becomes a VAR_MAKEFILE variable.
919
0
      $def->set_owner ($owner, $where->clone)
920        if $owner > $def->owner;
921    }
922  # 2. append (+=) to a variable defined for *another* condition
923  elsif ($type eq '+' && ! $self->conditions->false)
924    {
925      # * Generally, $cond is not TRUE. For instance:
926      # FOO = foo
927      # if COND
928      # FOO += bar
929      # endif
930      # In this case, we declare an helper variable conditionally,
931      # and append it to FOO:
932      # FOO = foo $(am__append_1)
933      # @COND_TRUE@am__append_1 = bar
934      # Of course if FOO is defined under several conditions, we add
935      # $(am__append_1) to each definitions.
936      #
937      # * If $cond is TRUE, we don't need the helper variable. E.g., in
938      # if COND1
939      # FOO = foo1
940      # else
941      # FOO = foo2
942      # endif
943      # FOO += bar
944      # we can add bar directly to all definition of FOO, and output
945      # @COND_TRUE@FOO = foo1 bar
946      # @COND_FALSE@FOO = foo2 bar
947
948
0
      my $lastappend = [];
949      # Do we need an helper variable?
950
0
      if ($cond != TRUE)
951        {
952          # Can we reuse the helper variable created for the previous
953          # append? (We cannot reuse older helper variables because
954          # we must preserve the order of items appended to the
955          # variable.)
956
0
          my $condstr = $cond->string;
957
0
          my $key = "$var:$condstr";
958
0
0
          my ($appendvar, $appendvarcond) = @{$self->{'last-append'}};
959
0
          if ($appendvar && $condstr eq $appendvarcond)
960            {
961              # Yes, let's simply append to it.
962
0
              $var = $appendvar;
963
0
              $owner = VAR_AUTOMAKE;
964
0
              $self = var ($var);
965
0
              $def = $self->rdef ($cond);
966
0
              $new_var = 0;
967            }
968          else
969            {
970              # No, create it.
971
0
              my $num = ++$_appendvar;
972
0
              my $hvar = "am__append_$num";
973
0
              $lastappend = [$hvar, $condstr];
974
0
              &define ($hvar, VAR_AUTOMAKE, '+',
975                       $cond, $value, $comment, $where, $pretty);
976
977              # Now HVAR is to be added to VAR.
978
0
              $comment = '';
979
0
              $value = "\$($hvar)";
980            }
981        }
982
983      # Add VALUE to all definitions of SELF.
984
0
      foreach my $vcond ($self->conditions->conds)
985        {
986          # We have a bit of error detection to do here.
987          # This:
988          # if COND1
989          # X = Y
990          # endif
991          # X += Z
992          # should be rejected because X is not defined for all conditions
993          # where `+=' applies.
994
0
          my $undef_cond = $self->not_always_defined_in_cond ($cond);
995
0
          if (! $undef_cond->false)
996            {
997
0
              error ($where,
998                     "Cannot apply `+=' because `$var' is not defined "
999                     . "in\nthe following conditions:\n "
1000
0
                     . join ("\n ", map { $_->human } $undef_cond->conds)
1001                     . "\nEither define `$var' in these conditions,"
1002                     . " or use\n`+=' in the same conditions as"
1003                     . " the definitions.");
1004            }
1005          else
1006            {
1007
0
              &define ($var, $owner, '+', $vcond, $value, $comment,
1008                       $where, $pretty);
1009            }
1010        }
1011
0
      $self->{'last-append'} = $lastappend;
1012    }
1013  # 3. first assignment (=, :=, or +=)
1014  else
1015    {
1016      # There must be no previous value unless the user is redefining
1017      # an Automake variable or an AC_SUBST variable for an existing
1018      # condition.
1019
0
      _check_ambiguous_condition ($self, $cond, $where)
1020        unless (!$new_var
1021                && (($def->owner == VAR_AUTOMAKE && $owner != VAR_AUTOMAKE)
1022                    || $def->owner == VAR_CONFIGURE));
1023
1024      # Never decrease an owner.
1025
0
      $owner = $def->owner
1026        if ! $new_var && $owner < $def->owner;
1027
1028      # Assignments to a macro set its location. We don't adjust
1029      # locations for `+='. Ideally I suppose we would associate
1030      # line numbers with random bits of text.
1031
0
      $def = new Automake::VarDef ($var, $value, $comment, $where->clone,
1032                                   $type, $owner, $pretty);
1033
0
      $self->set ($cond, $def);
1034
0
      push @_var_order, $var;
1035    }
1036
1037  # Call any defined hook. This helps to update some internal state
1038  # *while* parsing the file. For instance the handling of SUFFIXES
1039  # requires this (see var_SUFFIXES_trigger).
1040
0
0
  &{$_hooks{$var}}($type, $value) if exists $_hooks{$var};
1041}
1042
1043 - 1048
=item C<variable_delete ($varname, [@conds])>

Forget about C<$varname> under the conditions C<@conds>, or completely
if C<@conds> is empty.

=cut
1049
1050sub variable_delete ($@)
1051{
1052
0
1
  my ($var, @conds) = @_;
1053
1054
0
  if (!@conds)
1055    {
1056
0
      delete $_variable_dict{$var};
1057    }
1058  else
1059    {
1060
0
      for my $cond (@conds)
1061        {
1062
0
          delete $_variable_dict{$var}{'defs'}{$cond};
1063        }
1064    }
1065
0
  if ($var =~ /_([[:alnum:]]+)$/)
1066    {
1067
0
      delete $_primary_dict{$1}{$var};
1068    }
1069}
1070
1071 - 1076
=item C<$str = variables_dump>

Return a string describing all we know about all variables.
For debugging.

=cut
1077
1078sub variables_dump ()
1079{
1080
0
1
  my $text = "All variables:\n{\n";
1081
0
0
  foreach my $var (sort { $a->name cmp $b->name } variables)
1082    {
1083
0
      $text .= $var->dump;
1084    }
1085
0
  $text .= "}\n";
1086
0
  return $text;
1087}
1088
1089
1090 - 1100
=item C<$var = set_seen ($varname)>

=item C<$var = $var-E<gt>set_seen>

Mark all definitions of this variable as examined, if the variable
exists.  See L<Automake::VarDef::set_seen>.

Return the C<Variable> object if the variable exists, or 0
otherwise (i.e., as the C<var> function).

=cut
1101
1102sub set_seen ($)
1103{
1104
0
1
  my ($self) = @_;
1105
0
  $self = ref $self ? $self : var $self;
1106
1107
0
  return 0 unless $self;
1108
1109
0
  for my $c ($self->conditions->conds)
1110    {
1111
0
      $self->rdef ($c)->set_seen;
1112    }
1113
1114
0
  return $self;
1115}
1116
1117
1118 - 1126
=item C<$count = require_variables ($where, $reason, $cond, @variables)>

Make sure that each supplied variable is defined in C<$cond>.
Otherwise, issue a warning showing C<$reason> (C<$reason> should be
the reason why these variables are required, for instance C<'option foo
used'>).  If we know which macro can define this variable, hint the
user.  Return the number of undefined variables.

=cut
1127
1128sub require_variables ($$$@)
1129{
1130
0
1
  my ($where, $reason, $cond, @vars) = @_;
1131
0
  my $res = 0;
1132
0
  $reason .= ' but ' unless $reason eq '';
1133
1134 VARIABLE:
1135
0
  foreach my $var (@vars)
1136    {
1137      # Nothing to do if the variable exists.
1138      next VARIABLE
1139
0
        if vardef ($var, $cond);
1140
1141
0
      my $text = "$reason`$var' is undefined\n";
1142
0
      my $v = var $var;
1143
0
      if ($v)
1144        {
1145
0
          my $undef_cond = $v->not_always_defined_in_cond ($cond);
1146          next VARIABLE
1147
0
            if $undef_cond->false;
1148
0
          $text .= ("in the following conditions:\n "
1149
0
                    . join ("\n ", map { $_->human } $undef_cond->conds)
1150                    . "\n");
1151        }
1152
1153
0
      ++$res;
1154
1155
0
      if (exists $_am_macro_for_var{$var})
1156        {
1157
0
          my $mac = $_am_macro_for_var{$var};
1158
0
          $text .= " The usual way to define `$var' is to add "
1159            . "`$mac'\n to `$configure_ac' and run `aclocal' and "
1160            . "`autoconf' again.";
1161          # aclocal will not warn about undefined macros unless it
1162          # starts with AM_.
1163
0
          $text .= "\n If `$mac' is in `$configure_ac', make sure\n"
1164            . " its definition is in aclocal's search path."
1165            unless $mac =~ /^AM_/;
1166        }
1167      elsif (exists $_ac_macro_for_var{$var})
1168        {
1169
0
          $text .= " The usual way to define `$var' is to add "
1170            . "`$_ac_macro_for_var{$var}'\n to `$configure_ac' and "
1171            . "run `autoconf' again.";
1172        }
1173
1174
0
      error $where, $text, uniq_scope => US_GLOBAL;
1175    }
1176
0
  return $res;
1177}
1178
1179 - 1185
=item C<$count = $var->requires_variables ($reason, @variables)>

Same as C<require_variables>, but a method of Automake::Variable.
C<@variables> should be defined in the same conditions as C<$var> is
defined.

=cut
1186
1187sub requires_variables ($$@)
1188{
1189
0
1
  my ($var, $reason, @args) = @_;
1190
0
  my $res = 0;
1191
0
  for my $cond ($var->conditions->conds)
1192    {
1193
0
      $res += require_variables ($var->rdef ($cond)->location, $reason,
1194                                 $cond, @args);
1195    }
1196
0
  return $res;
1197}
1198
1199
1200 - 1207
=item C<variable_value ($var)>

Get the C<TRUE> value of a variable, warn if the variable is
conditionally defined.  C<$var> can be either a variable name
or a C<Automake::Variable> instance (this allows calls such
as C<$var-E<gt>variable_value>).

=cut
1208
1209sub variable_value ($)
1210{
1211
0
1
    my ($var) = @_;
1212
0
    my $v = ref ($var) ? $var : var ($var);
1213
0
    return () unless $v;
1214
0
    $v->check_defined_unconditionally;
1215
0
    my $d = $v->def (TRUE);
1216
0
    return $d ? $d->value : "";
1217}
1218
1219 - 1223
=item C<$str = output_variables>

Format definitions for all variables.

=cut
1224
1225sub output_variables ()
1226{
1227
0
1
  my $res = '';
1228  # We output variables it in the same order in which they were
1229  # defined (skipping duplicates).
1230
0
  my @vars = uniq @_var_order;
1231
1232  # Output all the Automake variables. If the user changed one,
1233  # then it is now marked as VAR_CONFIGURE or VAR_MAKEFILE.
1234
0
  foreach my $var (@vars)
1235    {
1236
0
      my $v = rvar $var;
1237
0
      foreach my $cond ($v->conditions->conds)
1238        {
1239
0
          $res .= $v->output ($cond)
1240            if $v->rdef ($cond)->owner == VAR_AUTOMAKE;
1241        }
1242    }
1243
1244  # Now dump the user variables that were defined.
1245
0
  foreach my $var (@vars)
1246    {
1247
0
      my $v = rvar $var;
1248
0
      foreach my $cond ($v->conditions->conds)
1249        {
1250
0
          $res .= $v->output ($cond)
1251            if $v->rdef ($cond)->owner != VAR_AUTOMAKE;
1252        }
1253    }
1254
0
  return $res;
1255}
1256
1257 - 1311
=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])>

Split the value of the Automake::Variable C<$var> on space, and
traverse its components recursively.

If C<$cond_filter> is an C<Automake::Condition>, process any
conditions which are true when C<$cond_filter> is true.  Otherwise,
process all conditions.

We distinguish two kinds of items in the content of C<$var>.
Terms that look like C<$(foo)> or C<${foo}> are subvariables
and cause recursion.  Other terms are assumed to be filenames.

Each time a filename is encountered, C<&fun_item> is called with the
following arguments:

  ($var,        -- the Automake::Variable we are currently
                   traversing
   $val,        -- the item (i.e., filename) to process
   $cond,       -- the Condition for the $var definition we are
                   examining (ignoring the recursion context)
   $full_cond)  -- the full Condition, taking into account
                   conditions inherited from parent variables
                   during recursion

If C<inner_expand> is set, variable references occurring in filename
(as in C<$(BASE).ext>) are expanded before the filename is passed to
C<&fun_item>.

If C<skip_ac_subst> is set, Autoconf @substitutions@ will be skipped,
i.e., C<&fun_item> will never be called for them.

C<&fun_item> may return a list of items, they will be passed to
C<&fun_store> later on.  Define C<&fun_item> or @<&fun_store> as
C<undef> when they serve no purpose.

Once all items of a variable have been processed, the result (of the
calls to C<&fun_items>, or of recursive traversals of subvariables)
are passed to C<&fun_collect>.  C<&fun_collect> receives three
arguments:

  ($var,         -- the variable being traversed
   $parent_cond, -- the Condition inherited from parent
                    variables during recursion
   @condlist)    -- a list of [$cond, @results] pairs
                    where each $cond appear only once, and @result
                    are all the results for this condition.

Typically you should do C<$cond->merge ($parent_cond)> to recompute
the C<$full_cond> associated to C<@result>.  C<&fun_collect> may
return a list of items, that will be used as the result of
C<Automake::Variable::traverse_recursively> (the top-level, or its
recursive calls).

=cut
1312
1313# Contains a stack of `from' and `to' parts of variable
1314# substitutions currently in force.
1315my @_substfroms;
1316my @_substtos;
1317sub traverse_recursively ($&&;%)
1318{
1319
0
1
  ++$_traversal;
1320
0
  @_substfroms = ();
1321
0
  @_substtos = ();
1322
0
  my ($var, $fun_item, $fun_collect, %options) = @_;
1323
0
  my $cond_filter = $options{'cond_filter'};
1324
0
  my $inner_expand = $options{'inner_expand'};
1325
0
  my $skip_ac_subst = $options{'skip_ac_subst'};
1326
0
  return $var->_do_recursive_traversal ($var,
1327                                        $fun_item, $fun_collect,
1328                                        $cond_filter, TRUE, $inner_expand,
1329                                        $skip_ac_subst)
1330}
1331
1332# The guts of Automake::Variable::traverse_recursively.
1333sub _do_recursive_traversal ($$&&$$$$)
1334{
1335
0
  my ($var, $parent, $fun_item, $fun_collect, $cond_filter, $parent_cond,
1336      $inner_expand, $skip_ac_subst) = @_;
1337
1338
0
  $var->set_seen;
1339
1340
0
  if ($var->{'scanned'} == $_traversal)
1341    {
1342
0
      err_var $var, "variable `" . $var->name() . "' recursively defined";
1343
0
      return ();
1344    }
1345
0
  $var->{'scanned'} = $_traversal;
1346
1347
0
  my @allresults = ();
1348
0
  my $cond_once = 0;
1349
0
  foreach my $cond ($var->conditions->conds)
1350    {
1351
0
      if (ref $cond_filter)
1352        {
1353          # Ignore conditions that don't match $cond_filter.
1354
0
          next if ! $cond->true_when ($cond_filter);
1355          # If we found out several definitions of $var
1356          # match $cond_filter then we are in trouble.
1357          # Tell the user we don't support this.
1358
0
          $var->check_defined_unconditionally ($parent, $parent_cond)
1359            if $cond_once;
1360
0
          $cond_once = 1;
1361        }
1362
0
      my @result = ();
1363
0
      my $full_cond = $cond->merge ($parent_cond);
1364
1365
0
      my @to_process = $var->value_as_list ($cond, $parent, $parent_cond);
1366
0
      while (@to_process)
1367        {
1368
0
          my $val = shift @to_process;
1369          # If $val is a variable (i.e. ${foo} or $(bar), not a filename),
1370          # handle the sub variable recursively.
1371          # (Backslashes before `}' and `)' within brackets are here to
1372          # please Emacs's indentation.)
1373
0
          if ($val =~ /^\$\{([^\}]*)\}$/ || $val =~ /^\$\(([^\)]*)\)$/)
1374            {
1375
0
              my $subvarname = $1;
1376
1377              # If the user uses a losing variable name, just ignore it.
1378              # This isn't ideal, but people have requested it.
1379
0
              next if ($subvarname =~ /\@.*\@/);
1380
1381              # See if the variable is actually a substitution reference
1382
0
              my ($from, $to);
1383              # This handles substitution references like ${foo:.a=.b}.
1384
0
              if ($subvarname =~ /^([^:]*):([^=]*)=(.*)$/o)
1385                {
1386
0
                  $subvarname = $1;
1387
0
                  $to = $3;
1388
0
                  $from = quotemeta $2;
1389                }
1390
1391
0
              my $subvar = var ($subvarname);
1392              # Don't recurse into undefined variables.
1393
0
              next unless $subvar;
1394
1395
0
              push @_substfroms, $from;
1396
0
              push @_substtos, $to;
1397
1398
0
              my @res = $subvar->_do_recursive_traversal ($parent,
1399                                                          $fun_item,
1400                                                          $fun_collect,
1401                                                          $cond_filter,
1402                                                          $full_cond,
1403                                                          $inner_expand,
1404                                                          $skip_ac_subst);
1405
0
              push (@result, @res);
1406
1407
0
              pop @_substfroms;
1408
0
              pop @_substtos;
1409
1410
0
              next;
1411            }
1412          # Try to expand variable references inside filenames such as
1413          # `$(NAME).txt'. We do not handle `:.foo=.bar'
1414          # substitutions, but it would make little sense to use this
1415          # here anyway.
1416          elsif ($inner_expand
1417                 && ($val =~ /\$\{([^\}]*)\}/ || $val =~ /\$\(([^\)]*)\)/))
1418            {
1419
0
              my $subvarname = $1;
1420
0
              my $subvar = var $subvarname;
1421
0
              if ($subvar)
1422                {
1423                  # Replace the reference by its value, and reschedule
1424                  # for expansion.
1425
0
                  foreach my $c ($subvar->conditions->conds)
1426                    {
1427
0
                      if (ref $cond_filter)
1428                        {
1429                          # Ignore conditions that don't match $cond_filter.
1430
0
                          next if ! $c->true_when ($cond_filter);
1431                          # If we found out several definitions of $var
1432                          # match $cond_filter then we are in trouble.
1433                          # Tell the user we don't support this.
1434
0
                          $subvar->check_defined_unconditionally ($var,
1435                                                                  $full_cond)
1436                            if $cond_once;
1437
0
                          $cond_once = 1;
1438                        }
1439
0
                      my $subval = $subvar->rdef ($c)->value;
1440
0
                      $val =~ s/\$\{$subvarname\}/$subval/g;
1441
0
                      $val =~ s/\$\($subvarname\)/$subval/g;
1442
0
                      unshift @to_process, split (' ', $val);
1443                    }
1444
0
                  next;
1445                }
1446              # We do not know any variable with this name. Fall through
1447              # to filename processing.
1448            }
1449          elsif ($skip_ac_subst && $val =~ /^\@.+\@$/)
1450            {
1451
0
              next;
1452            }
1453
1454
0
          if ($fun_item) # $var is a filename we must process
1455            {
1456
0
              my $substnum=$#_substfroms;
1457
0
              while ($substnum >= 0)
1458                {
1459
0
                  $val =~ s/$_substfroms[$substnum]$/$_substtos[$substnum]/
1460                    if defined $_substfroms[$substnum];
1461
0
                  $substnum -= 1;
1462                }
1463
1464              # Make sure you update the doc of
1465              # Automake::Variable::traverse_recursively
1466              # if you change the prototype of &fun_item.
1467
0
              my @transformed = &$fun_item ($var, $val, $cond, $full_cond);
1468
0
              push (@result, @transformed);
1469            }
1470        }
1471
0
      push (@allresults, [$cond, @result]) if @result;
1472    }
1473
1474  # We only care about _recursive_ variable definitions. The user
1475  # is free to use the same variable several times in the same definition.
1476
0
  $var->{'scanned'} = -1;
1477
1478  return ()
1479
0
    unless $fun_collect;
1480  # Make sure you update the doc of Automake::Variable::traverse_recursively
1481  # if you change the prototype of &fun_collect.
1482
0
  return &$fun_collect ($var, $parent_cond, @allresults);
1483}
1484
1485# _hash_varname ($VAR)
1486# --------------------
1487# Compute the key associated $VAR in %_gen_varname.
1488# See _gen_varname() below.
1489sub _hash_varname ($)
1490{
1491
0
  my ($var) = @_;
1492
0
  my $key = '';
1493
0
  foreach my $cond ($var->conditions->conds)
1494    {
1495
0
      my @values = $var->value_as_list ($cond);
1496
0
      $key .= "($cond)@values";
1497    }
1498
0
  return $key;
1499}
1500
1501# _hash_values (@VALUES)
1502# ----------------------
1503# Hash @VALUES for %_gen_varname. @VALUES should be a list
1504# of pairs: ([$cond, @values], [$cond, @values], ...).
1505# See _gen_varname() below.
1506sub _hash_values (@)
1507{
1508
0
  my $key = '';
1509
0
  foreach my $pair (@_)
1510    {
1511
0
      my ($cond, @values) = @$pair;
1512
0
      $key .= "($cond)@values";
1513    }
1514
0
  return $key;
1515}
1516# ($VARNAME, $GENERATED)
1517# _gen_varname ($BASE, @DEFINITIONS)
1518# ---------------------------------
1519# Return a variable name starting with $BASE, that will be
1520# used to store definitions @DEFINITIONS.
1521# @DEFINITIONS is a list of pair [$COND, @OBJECTS].
1522#
1523# If we already have a $BASE-variable containing @DEFINITIONS, reuse
1524# it and set $GENERATED to 0. Otherwise construct a new name and set
1525# $GENERATED to 1.
1526#
1527# This way, we avoid combinatorial explosion of the generated
1528# variables. Especially, in a Makefile such as:
1529#
1530# | if FOO1
1531# | A1=1
1532# | endif
1533# |
1534# | if FOO2
1535# | A2=2
1536# | endif
1537# |
1538# | ...
1539# |
1540# | if FOON
1541# | AN=N
1542# | endif
1543# |
1544# | B=$(A1) $(A2) ... $(AN)
1545# |
1546# | c_SOURCES=$(B)
1547# | d_SOURCES=$(B)
1548#
1549# The generated c_OBJECTS and d_OBJECTS will share the same variable
1550# definitions.
1551#
1552# This setup can be the case of a testsuite containing lots (>100) of
1553# small C programs, all testing the same set of source files.
1554sub _gen_varname ($@)
1555{
1556
0
  my $base = shift;
1557
0
  my $key = _hash_values @_;
1558
1559
0
  return ($_gen_varname{$base}{$key}, 0)
1560    if exists $_gen_varname{$base}{$key};
1561
1562
0
  my $num = 1 + ($_gen_varname_n{$base} || 0);
1563
0
  $_gen_varname_n{$base} = $num;
1564
0
  my $name = "${base}_${num}";
1565
0
  $_gen_varname{$base}{$key} = $name;
1566
1567
0
  return ($name, 1);
1568}
1569
1570 - 1597
=item C<$resvar = transform_variable_recursively ($var, $resvar, $base, $nodefine, $where, &fun_item, [%options])>

=item C<$resvar = $var-E<gt>transform_variable_recursively ($resvar, $base, $nodefine, $where, &fun_item, [%options])>

Traverse C<$var> recursively, and create a C<$resvar> variable in
which each filename in C<$var> have been transformed using
C<&fun_item>.  (C<$var> may be a variable name in the first syntax.
It must be an C<Automake::Variable> otherwise.)

Helper variables (corresponding to sub-variables of C<$var>) are
created as needed, using C<$base> as prefix.

Arguments are:
  $var       source variable to traverse
  $resvar    resulting variable to define
  $base      prefix to use when naming subvariables of $resvar
  $nodefine  if true, traverse $var but do not define any variable
             (this assumes &fun_item has some useful side-effect)
  $where     context into which variable definitions are done
  &fun_item  a transformation function -- see the documentation
             of &fun_item in Automake::Variable::traverse_recursively.

This returns the string C<"\$($RESVAR)">.

C<%options> is a list of options to pass to
C<Variable::traverse_recursively> (see this method).

=cut
1598
1599sub transform_variable_recursively ($$$$$&;%)
1600{
1601
0
1
  my ($var, $resvar, $base, $nodefine, $where, $fun_item, %options) = @_;
1602
1603
0
  $var = ref $var ? $var : rvar $var;
1604
1605  my $res = $var->traverse_recursively
1606    ($fun_item,
1607     # The code that defines the variable holding the result
1608     # of the recursive transformation of a subvariable.
1609     sub {
1610
0
       my ($subvar, $parent_cond, @allresults) = @_;
1611       # If no definition is required, return anything: the result is
1612       # not expected to be used, only the side effect of $fun_item
1613       # should matter.
1614
0
       return 'report-me' if $nodefine;
1615       # Cache $subvar, so that we reuse it if @allresults is the same.
1616
0
       my $key = _hash_varname $subvar;
1617
0
       $_gen_varname{$base}{$key} = $subvar->name;
1618
1619       # Find a name for the variable, unless this is the top-variable
1620       # for which we want to use $resvar.
1621
0
       my ($varname, $generated) =
1622         ($var != $subvar) ? _gen_varname ($base, @allresults) : ($resvar, 1);
1623
1624       # Define the variable if we are not reusing a previously
1625       # defined variable. At the top-level, we can also avoid redefining
1626       # the variable if it already contains the same values.
1627
0
       if ($generated
1628           && !($varname eq $var->name && $key eq _hash_values @allresults))
1629         {
1630           # If the new variable is the source variable, we assume
1631           # we are trying to override a user variable. Delete
1632           # the old variable first.
1633
0
           variable_delete ($varname) if $varname eq $var->name;
1634           # Define an empty variable in condition TRUE if there is no
1635           # result.
1636
0
           @allresults = ([TRUE, '']) unless @allresults;
1637           # Define the rewritten variable in all conditions not
1638           # already covered by user definitions.
1639
0
           foreach my $pair (@allresults)
1640             {
1641
0
               my ($cond, @result) = @$pair;
1642
0
               my $var = var $varname;
1643
0
               my @conds = ($var
1644                            ? $var->not_always_defined_in_cond ($cond)->conds
1645                            : $cond);
1646
1647
0
               foreach (@conds)
1648                 {
1649
0
                   define ($varname, VAR_AUTOMAKE, '', $_, "@result",
1650                           '', $where, VAR_PRETTY);
1651                 }
1652             }
1653         }
1654
0
       set_seen $varname;
1655
0
       return "\$($varname)";
1656     },
1657
0
     %options);
1658
0
  return $res;
1659}
1660
1661
1662=back
1663
1664 - 1669
=head1 SEE ALSO

L<Automake::VarDef>, L<Automake::Condition>,
L<Automake::DisjConditions>, L<Automake::Location>.

=cut
1670
16711;
1672
1673### Setup "GNU" style for perl-mode and cperl-mode.
1674## Local Variables:
1675## perl-indent-level: 2
1676## perl-continued-statement-offset: 2
1677## perl-continued-brace-offset: 0
1678## perl-brace-offset: 0
1679## perl-brace-imaginary-offset: 0
1680## perl-label-offset: -2
1681## cperl-indent-level: 2
1682## cperl-brace-offset: 0
1683## cperl-continued-brace-offset: 0
1684## cperl-label-offset: -2
1685## cperl-extra-newline-before-brace: t
1686## cperl-merge-trailing-else: nil
1687## cperl-continued-statement-offset: 2
1688## End: