File Coverage

File:/tmp/automake/lib/Automake/Variable.pm
Coverage:92.7%

linestmtbrancondsubpodtimecode
1# Copyright (C) 2003, 2004, 2005, 2006, 2008, 2009, 2010 Free Software
2# Foundation, Inc.
3
4# This program is free software; you can redistribute it and/or modify
5# it under the terms of the GNU General Public License as published by
6# the Free Software Foundation; either version 2, or (at your option)
7# any later version.
8
9# This program is distributed in the hope that it will be useful,
10# but WITHOUT ANY WARRANTY; without even the implied warranty of
11# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12# GNU General Public License for more details.
13
14# You should have received a copy of the GNU General Public License
15# along with this program. If not, see <http://www.gnu.org/licenses/>.
16
17package Automake::Variable;
18
1159
1159
1159
3195
1161
3524
use strict;
19
1159
1159
1159
4164
1136
2936
use Carp;
20
21
1159
1159
1159
4312
1125
2939
use Automake::Channels;
22
1159
1159
1159
5413
1385
3212
use Automake::ChannelDefs;
23
1159
1159
1159
4458
1146
3352
use Automake::Configure_ac;
24
1159
1159
1159
9169
1505
8429
use Automake::Item;
25
1159
1159
1159
8125
1364
7772
use Automake::VarDef;
26
1159
1159
1159
4736
1262
3808
use Automake::Condition qw (TRUE FALSE);
27
1159
1159
1159
4346
1154
3176
use Automake::DisjConditions;
28
1159
1159
1159
4162
1108
6673
use Automake::General 'uniq';
29
1159
1159
1159
9152
2830
7406
use Automake::Wrap 'makefile_wrap';
30
31require Exporter;
32
1159
1159
1159
4670
1203
3056
use vars '@ISA', '@EXPORT', '@EXPORT_OK';
33@ISA = qw/Automake::Item Exporter/;
34@EXPORT = qw (err_var msg_var msg_cond_var reject_var
35              var rvar vardef rvardef
36              variables
37              scan_variable_expansions check_variable_expansions
38              variable_delete
39              variables_dump
40              set_seen
41              require_variables
42              variable_value
43              output_variables
44              transform_variable_recursively);
45
46 - 130
=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
131
132my $_VARIABLE_CHARACTERS = '[.A-Za-z0-9_@]+';
133my $_VARIABLE_PATTERN = '^' . $_VARIABLE_CHARACTERS . "\$";
134my $_VARIABLE_RECURSIVE_PATTERN =
135    '^([.A-Za-z0-9_@]|\$[({]' . $_VARIABLE_CHARACTERS . '[})]?)+' . "\$";
136
137# The order in which variables should be output. (May contain
138# duplicates -- only the first occurrence matters.)
139my @_var_order;
140
141# This keeps track of all variables defined by &_gen_varname.
142# $_gen_varname{$base} is a hash for all variables defined with
143# prefix `$base'. Values stored in this hash are the variable names.
144# Keys have the form "(COND1)VAL1(COND2)VAL2..." where VAL1 and VAL2
145# are the values of the variable for condition COND1 and COND2.
146my %_gen_varname = ();
147# $_gen_varname_n{$base} is the number of variables generated by
148# _gen_varname() for $base. This is not the same as keys
149# %{$_gen_varname{$base}} because %_gen_varname may also contain
150# variables not generated by _gen_varname.
151my %_gen_varname_n = ();
152
153# Declare the macros that define known variables, so we can
154# hint the user if she try to use one of these variables.
155
156# Macros accessible via aclocal.
157my %_am_macro_for_var =
158  (
159   ANSI2KNR => 'AM_C_PROTOTYPES',
160   CCAS => 'AM_PROG_AS',
161   CCASFLAGS => 'AM_PROG_AS',
162   EMACS => 'AM_PATH_LISPDIR',
163   GCJ => 'AM_PROG_GCJ',
164   LEX => 'AM_PROG_LEX',
165   LIBTOOL => 'AC_PROG_LIBTOOL',
166   lispdir => 'AM_PATH_LISPDIR',
167   pkgpyexecdir => 'AM_PATH_PYTHON',
168   pkgpythondir => 'AM_PATH_PYTHON',
169   pyexecdir => 'AM_PATH_PYTHON',
170   PYTHON => 'AM_PATH_PYTHON',
171   pythondir => 'AM_PATH_PYTHON',
172   U => 'AM_C_PROTOTYPES',
173   );
174
175# Macros shipped with Autoconf.
176my %_ac_macro_for_var =
177  (
178   ALLOCA => 'AC_FUNC_ALLOCA',
179   CC => 'AC_PROG_CC',
180   CFLAGS => 'AC_PROG_CC',
181   CXX => 'AC_PROG_CXX',
182   CXXFLAGS => 'AC_PROG_CXX',
183   F77 => 'AC_PROG_F77',
184   F77FLAGS => 'AC_PROG_F77',
185   FC => 'AC_PROG_FC',
186   FCFLAGS => 'AC_PROG_FC',
187   OBJC => 'AC_PROG_OBJC',
188   OBJCFLAGS => 'AC_PROG_OBJC',
189   RANLIB => 'AC_PROG_RANLIB',
190   UPC => 'AM_PROG_UPC',
191   UPCFLAGS => 'AM_PROG_UPC',
192   YACC => 'AC_PROG_YACC',
193   );
194
195# The name of the configure.ac file.
196my $configure_ac;
197
198# Variables that can be overridden without complaint from -Woverride
199my %_silent_variable_override =
200  (AM_MAKEINFOHTMLFLAGS => 1,
201   AR => 1,
202   ARFLAGS => 1,
203   DEJATOOL => 1,
204   JAVAC => 1,
205   JAVAROOT => 1);
206
207# Count of helper variables used to implement conditional '+='.
208my $_appendvar;
209
210# Each call to C<Automake::Variable::traverse_recursively> gets an
211# unique label. This is used to detect recursively defined variables.
212my $_traversal = 0;
213
214
215 - 226
=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
227
228sub err_var ($$;%)
229{
230
39
1
134
  msg_var ('error', @_);
231}
232
233 - 237
=item C<msg_cond_var ($channel, $cond, $var, $message, [%options])>

Messages about conditional variable.

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

Messages about variables.

=cut
251
252sub msg_var ($$$;%)
253{
254
124
1
366
  my ($channel, $var, $msg, %opts) = @_;
255
124
357
  my $v = ref ($var) ? $var : rvar ($var);
256  # Don't know which condition is concerned. Pick any.
257
124
341
  my $cond = $v->conditions->one_cond;
258
124
454
  msg_cond_var $channel, $cond, $v, $msg, %opts;
259}
260
261 - 268
=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
269
270sub reject_var ($$)
271{
272
24477
1
44802
  my ($var, $msg) = @_;
273
24477
37172
  my $v = var ($var);
274
24477
43234
  if ($v)
275    {
276
16
45
      err_var $v, $msg;
277
16
50
      return 1;
278    }
279
24461
44974
  return 0;
280}
281
282=back
283
284 - 298
=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
299
300
1159
1159
1159
5031
1376
4489
use vars '%_hooks';
301sub hook ($$)
302{
303
1159
1
3386
  my ($var, $fun) = @_;
304
1159
4290
  $_hooks{$var} = $fun;
305}
306
307 - 313
=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
314
315
1159
1159
1159
4931
1285
2950
use vars '%_variable_dict', '%_primary_dict';
316sub variables (;$)
317{
318
21348
1
35501
  my ($suffix) = @_;
319
21348
35001
  if ($suffix)
320    {
321
20026
41380
      if (exists $_primary_dict{$suffix})
322        {
323
4762
4762
6318
21541
          return values %{$_primary_dict{$suffix}};
324        }
325      else
326        {
327
15264
46796
          return ();
328        }
329    }
330  else
331    {
332
1322
6998
      return values %_variable_dict;
333    }
334}
335
336 - 341
=item C<Automake::Variable::reset>

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

=cut
342
343sub reset ()
344{
345
1322
1
37087
  %_variable_dict = ();
346
1322
42049
  %_primary_dict = ();
347
1322
2983
  $_appendvar = 0;
348
1322
4019
  @_var_order = ();
349
1322
2503
  %_gen_varname = ();
350
1322
2252
  %_gen_varname_n = ();
351
1322
3130
  $_traversal = 0;
352}
353
354 - 359
=item C<var ($varname)>

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

=cut
360
361sub var ($)
362{
363
832114
1
1106840
  my ($name) = @_;
364
832114
2228020
  return $_variable_dict{$name} if exists $_variable_dict{$name};
365
413030
1177613
  return 0;
366}
367
368 - 374
=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
375
376sub vardef ($$)
377{
378
24026
1
38670
  my ($name, $cond) = @_;
379
24026
36707
  my $var = var $name;
380
24026
95684
  return $var && $var->def ($cond);
381}
382
383# Create the variable if it does not exist.
384# This is used only by other functions in this package.
385sub _cvar ($)
386{
387
195442
277328
  my ($name) = @_;
388
195442
287515
  my $v = var $name;
389
195442
330630
  return $v if $v;
390
180790
425223
  return _new Automake::Variable $name;
391}
392
393 - 402
=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
403
404sub rvar ($)
405{
406
377962
1
555379
  my ($name) = @_;
407
377962
548261
  my $v = var $name;
408
377962
652018
  prog_error ("undefined variable $name\n" . &variables_dump)
409    unless $v;
410
377962
517104
  return $v;
411}
412
413 - 419
=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
420
421sub rvardef ($$)
422{
423
0
1
0
  my ($name, $cond) = @_;
424
0
0
  return rvar ($name)->rdef ($cond);
425}
426
427=back
428
429 - 439
=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
440
441# Create Automake::Variable objects. This is used
442# only in this file. Other users should use
443# the "define" function.
444sub _new ($$)
445{
446
180790
280897
  my ($class, $name) = @_;
447
180790
398893
  my $self = Automake::Item::new ($class, $name);
448
180790
302684
  $self->{'scanned'} = 0;
449
180790
317120
  $self->{'last-append'} = []; # helper variable for last conditional append.
450
180790
314536
  $_variable_dict{$name} = $self;
451
180790
580347
  if ($name =~ /_([[:alnum:]]+)$/)
452    {
453
101467
348077
      $_primary_dict{$1}{$name} = $self;
454    }
455
180790
348283
  return $self;
456}
457
458# _check_ambiguous_condition ($SELF, $COND, $WHERE)
459# -------------------------------------------------
460# Check for an ambiguous conditional. This is called when a variable
461# is being defined conditionally. If we already know about a
462# definition that is true under the same conditions, then we have an
463# ambiguity.
464sub _check_ambiguous_condition ($$$)
465{
466
180993
305654
  my ($self, $cond, $where) = @_;
467
180993
393480
  my $var = $self->name;
468
180993
426697
  my ($message, $ambig_cond) = $self->conditions->ambiguous_p ($var, $cond);
469
470  # We allow silent variables to be overridden silently,
471  # by either silent or non-silent variables.
472
180993
441245
  my $def = $self->def ($ambig_cond);
473
180993
520776
  if ($message && $def->pretty != VAR_SILENT)
474    {
475
20
86
      msg 'syntax', $where, "$message ...", partial => 1;
476
20
100
      msg_var ('syntax', $var, "... `$var' previously defined here");
477
20
77
      verb ($self->dump);
478    }
479}
480
481 - 487
=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
488
489sub check_defined_unconditionally ($;$$)
490{
491
3131
1
7584
  my ($self, $parent, $parent_cond) = @_;
492
493
3131
25541
  if (!$self->conditions->true)
494    {
495
1
3
      if ($parent)
496        {
497
0
0
          msg_cond_var ('unsupported', $parent_cond, $parent,
498                        "automake does not support conditional definition of "
499                        . $self->name . " in $parent");
500        }
501      else
502        {
503
1
3
          msg_var ('unsupported', $self,
504                   "automake does not support " . $self->name
505                   . " being defined conditionally");
506        }
507    }
508}
509
510 - 515
=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
516
517sub output ($@)
518{
519
177648
1
291478
  my ($self, @conds) = @_;
520
521
177648
290501
  @conds = $self->conditions->conds
522    unless @conds;
523
524
177648
202433
  my $res = '';
525
177648
364700
  my $name = $self->name;
526
527
177648
263237
  foreach my $cond (@conds)
528    {
529
177648
376487
      my $def = $self->def ($cond);
530
177648
296538
      prog_error ("unknown condition `" . $cond->human . "' for `"
531                  . $self->name . "'")
532        unless $def;
533
534      next
535
177648
385839
        if $def->pretty == VAR_SILENT;
536
537
170950
379523
      $res .= $def->comment;
538
539
170950
376079
      my $val = $def->raw_value;
540
170950
356037
      my $equals = $def->type eq ':' ? ':=' : '=';
541
170950
381060
      my $str = $cond->subst_string;
542
543
544
170950
362602
      if ($def->pretty == VAR_ASIS)
545        {
546
149194
311470
          my $output_var = "$name $equals $val";
547
149194
165595
427981
415042
          $output_var =~ s/^/$str/meg;
548
149194
398038
          $res .= "$output_var\n";
549        }
550      elsif ($def->pretty == VAR_PRETTY)
551        {
552          # Suppress escaped new lines. &makefile_wrap will
553          # add them back, maybe at other places.
554
21585
31879
          $val =~ s/\\$//mg;
555
21585
92668
          my $wrap = makefile_wrap ("$str$name $equals", "$str\t",
556                                    split (' ', $val));
557
558          # If the last line of the definition is made only of
559          # @substitutions@, append an empty variable to make sure it
560          # cannot be substituted as a blank line (that would confuse
561          # HP-UX Make).
562
21585
50480
          $wrap = makefile_wrap ("$str$name $equals", "$str\t",
563                                 split (' ', $val), '$(am__empty)')
564            if $wrap =~ /\n(\s*@\w+@)+\s*$/;
565
566
21585
48439
          $res .= $wrap;
567        }
568      else # ($def->pretty == VAR_SORTED)
569        {
570          # Suppress escaped new lines. &makefile_wrap will
571          # add them back, maybe at other places.
572
171
1983
          $val =~ s/\\$//mg;
573
171
2848
          $res .= makefile_wrap ("$str$name $equals", "$str\t",
574                                 sort (split (' ' , $val)));
575        }
576    }
577
177648
624791
  return $res;
578}
579
580 - 597
=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
598
599sub value_as_list ($$;$$)
600{
601
8633
1
17524
  my ($self, $cond, $parent, $parent_cond) = @_;
602
8633
7802
  my @result;
603
604  # Get value for given condition
605
8633
7671
  my $onceflag;
606
8633
20773
  foreach my $vcond ($self->conditions->conds)
607    {
608
11230
28620
      if ($vcond->true_when ($cond))
609        {
610          # If there is more than one definitions of $var matching
611          # $cond then we are in trouble: tell the user we need a
612          # paddle. Continue by merging results from all conditions,
613          # although it doesn't make much sense.
614
8633
17162
          $self->check_defined_unconditionally ($parent, $parent_cond)
615            if $onceflag;
616
8633
9437
          $onceflag = 1;
617
618
8633
20972
          my $val = $self->rdef ($vcond)->value;
619
8633
30772
          push @result, split (' ', $val);
620        }
621    }
622
8633
23611
  return @result;
623}
624
625 - 643
=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
644
645sub value_as_list_recursive ($;%)
646{
647
2196
1
6861
  my ($var, %options) = @_;
648
649  return $var->traverse_recursively
650    (# Construct [$location, $value] pairs if requested.
651     sub {
652
3450
7522
       my ($var, $val, $cond, $full_cond) = @_;
653
3450
13211
       return [$var->rdef ($cond)->location, $val] if $options{'location'};
654
681
1559
       return $val;
655     },
656     # Collect results.
657     sub {
658
2332
5228
       my ($var, $parent_cond, @allresults) = @_;
659
2332
2317
2317
4699
4483
13752
       return map { my ($cond, @vals) = @$_; @vals } @allresults;
660     },
661
2196
27603
     %options);
662}
663
664
665 - 670
=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
671
672sub has_conditional_contents ($)
673{
674
1772
1
3565
  my ($self) = @_;
675
676  # Traverse the variable recursively until we
677  # find a variable defined conditionally.
678  # Use `die' to abort the traversal, and pass it `$full_cond'
679  # to we can find easily whether the `eval' block aborted
680  # because we found a condition, or for some other error.
681  eval
682
1772
3479
    {
683      $self->traverse_recursively
684        (sub
685         {
686
2351
5370
           my ($subvar, $val, $cond, $full_cond) = @_;
687
2351
5842
           die $full_cond if ! $full_cond->true;
688
2301
4501
           return ();
689         },
690
1772
1750
14821
5170
         sub { return (); });
691    };
692
1772
8923
  if ($@)
693    {
694
50
613
      return 1 if ref ($@) && $@->isa ("Automake::Condition");
695      # Propagate other errors.
696
0
0
      die;
697    }
698
1722
6657
  return 0;
699}
700
701
702 - 707
=item C<$string = $var-E<gt>dump>

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

=cut
708
709sub dump ($)
710{
711
37
1
81
  my ($self) = @_;
712
713
37
112
  my $text = $self->name . ": \n {\n";
714
37
113
  foreach my $vcond ($self->conditions->conds)
715    {
716
37
142
      $text .= " " . $vcond->human . " => " . $self->rdef ($vcond)->dump;
717    }
718
37
64
  $text .= " }\n";
719
37
140
  return $text;
720}
721
722
723=back
724
725 - 735
=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
736
737sub scan_variable_expansions ($)
738{
739
198857
1
256959
  my ($text) = @_;
740
198857
234482
  my @result = ();
741
742  # Strip comments.
743
198857
252126
  $text =~ s/#.*$//;
744
745  # Record each use of ${stuff} or $(stuff) that does not follow a $.
746
198857
563243
  while ($text =~ /(?<!\$)\$(?:\{([^\}]*)\}|\(([^\)]*)\))/g)
747    {
748
77702
422907
      my $var = $1 || $2;
749      # The occurrence may look like $(string1[:subst1=[subst2]]) but
750      # we want only `string1'.
751
77702
103831
      $var =~ s/:[^:=]*=[^=]*$//;
752
77702
278579
      push @result, $var;
753    }
754
755
198857
522811
  return @result;
756}
757
758 - 764
=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
765
766sub check_variable_expansions ($$)
767{
768
198857
1
324244
  my ($text, $where) = @_;
769  # Catch expansion of variables whose name does not conform to POSIX.
770
198857
313542
  foreach my $var (scan_variable_expansions ($text))
771    {
772
77702
309148
      if ($var !~ /$_VARIABLE_PATTERN/o)
773        {
774          # If the variable name contains a space, it's likely
775          # to be a GNU make extension (such as $(addsuffix ...)).
776          # Mention this in the diagnostic.
777
363
469
          my $gnuext = "";
778
363
774
          $gnuext = "\n(probably a GNU make extension)" if $var =~ / /;
779          # Accept recursive variable expansions if so desired
780          # (we hope they are rather portable in practice).
781
363
2237
          if ($var =~ /$_VARIABLE_RECURSIVE_PATTERN/o)
782            {
783
332
1165
              msg ('portability-recursive', $where,
784                   "$var: non-POSIX recursive variable expansion$gnuext");
785            }
786          else
787            {
788
31
116
              msg ('portability', $where, "$var: non-POSIX variable name$gnuext");
789            }
790        }
791    }
792}
793
794
795
796 - 829
=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
830
831sub define ($$$$$$$$)
832{
833
195442
1
467045
  my ($var, $owner, $type, $cond, $value, $comment, $where, $pretty) = @_;
834
835
195442
364486
  prog_error "$cond is not a reference"
836    unless ref $cond;
837
838
195442
344563
  prog_error "$where is not a reference"
839    unless ref $where;
840
841
195442
1449129
  prog_error "pretty argument missing"
842    unless defined $pretty && ($pretty == VAR_ASIS
843                               || $pretty == VAR_PRETTY
844                               || $pretty == VAR_SILENT
845                               || $pretty == VAR_SORTED);
846
847
195442
716290
  error $where, "bad characters in variable name `$var'"
848    if $var !~ /$_VARIABLE_PATTERN/o;
849
850  # `:='-style assignments are not acknowledged by POSIX. Moreover it
851  # has multiple meanings. In GNU make or BSD make it means "assign
852  # with immediate expansion", while in OSF make it is used for
853  # conditional assignments.
854
195442
353146
  msg ('portability', $where, "`:='-style assignments are not portable")
855    if $type eq ':';
856
857
195442
334828
  check_variable_expansions ($value, $where);
858
859  # If there's a comment, make sure it is \n-terminated.
860
195442
332006
  if ($comment)
861    {
862
361
571
      chomp $comment;
863
361
540
      $comment .= "\n";
864    }
865  else
866    {
867
195081
243265
      $comment = '';
868    }
869
870
195442
310262
  my $self = _cvar $var;
871
872
195442
503570
  my $def = $self->def ($cond);
873
195442
324061
  my $new_var = $def ? 0 : 1;
874
875  # Additional checks for Automake definitions.
876
195442
676673
  if ($owner == VAR_AUTOMAKE && ! $new_var)
877    {
878      # An Automake variable must be consistently defined with the same
879      # sign by Automake.
880
13157
43212
      if ($def->type ne $type && $def->owner == VAR_AUTOMAKE)
881        {
882
0
0
          error ($def->location,
883                 "Automake variable `$var' was set with `"
884                 . $def->type . "=' here ...", partial => 1);
885
0
0
          error ($where, "... and is now set with `$type=' here.");
886
0
0
          prog_error ("Automake variable assignments should be consistently\n"
887                      . "defined with the same sign");
888        }
889
890      # If Automake tries to override a value specified by the user,
891      # just don't let it do.
892
13157
45015
      if ($def->owner != VAR_AUTOMAKE)
893        {
894
17
69
          if (! exists $_silent_variable_override{$var})
895            {
896
9
30
              my $condmsg = ($cond == TRUE
897                             ? '' : (" in condition `" . $cond->human . "'"));
898
9
58
              msg_cond_var ('override', $cond, $var,
899                            "user variable `$var' defined here$condmsg ...",
900                            partial => 1);
901
9
48
              msg ('override', $where,
902                   "... overrides Automake variable `$var' defined here");
903            }
904
17
91
          verb ("refusing to override the user definition of:\n"
905                . $self->dump ."with `" . $cond->human . "' => `$value'");
906
17
56
          return;
907        }
908    }
909
910  # Differentiate assignment types.
911
912  # 1. append (+=) to a variable defined for current condition
913
195425
787525
  if ($type eq '+' && ! $new_var)
914    {
915
14300
44959
      $def->append ($value, $comment);
916
14300
28201
      $self->{'last-append'} = [];
917
918      # Only increase owners. A VAR_CONFIGURE variable augmented in a
919      # Makefile.am becomes a VAR_MAKEFILE variable.
920
14300
43175
      $def->set_owner ($owner, $where->clone)
921        if $owner > $def->owner;
922    }
923  # 2. append (+=) to a variable defined for *another* condition
924  elsif ($type eq '+' && ! $self->conditions->false)
925    {
926      # * Generally, $cond is not TRUE. For instance:
927      # FOO = foo
928      # if COND
929      # FOO += bar
930      # endif
931      # In this case, we declare an helper variable conditionally,
932      # and append it to FOO:
933      # FOO = foo $(am__append_1)
934      # @COND_TRUE@am__append_1 = bar
935      # Of course if FOO is defined under several conditions, we add
936      # $(am__append_1) to each definitions.
937      #
938      # * If $cond is TRUE, we don't need the helper variable. E.g., in
939      # if COND1
940      # FOO = foo1
941      # else
942      # FOO = foo2
943      # endif
944      # FOO += bar
945      # we can add bar directly to all definition of FOO, and output
946      # @COND_TRUE@FOO = foo1 bar
947      # @COND_FALSE@FOO = foo2 bar
948
949
110
167
      my $lastappend = [];
950      # Do we need an helper variable?
951
110
239
      if ($cond != TRUE)
952        {
953          # Can we reuse the helper variable created for the previous
954          # append? (We cannot reuse older helper variables because
955          # we must preserve the order of items appended to the
956          # variable.)
957
105
252
          my $condstr = $cond->string;
958
105
211
          my $key = "$var:$condstr";
959
105
105
105
232
          my ($appendvar, $appendvarcond) = @{$self->{'last-append'}};
960
105
479
          if ($appendvar && $condstr eq $appendvarcond)
961            {
962              # Yes, let's simply append to it.
963
3
5
              $var = $appendvar;
964
3
5
              $owner = VAR_AUTOMAKE;
965
3
5
              $self = var ($var);
966
3
20
              $def = $self->rdef ($cond);
967
3
5
              $new_var = 0;
968            }
969          else
970            {
971              # No, create it.
972
102
140
              my $num = ++$_appendvar;
973
102
185
              my $hvar = "am__append_$num";
974
102
212
              $lastappend = [$hvar, $condstr];
975
102
509
              &define ($hvar, VAR_AUTOMAKE, '+',
976                       $cond, $value, $comment, $where, $pretty);
977
978              # Now HVAR is to be added to VAR.
979
102
125
              $comment = '';
980
102
229
              $value = "\$($hvar)";
981            }
982        }
983
984      # Add VALUE to all definitions of SELF.
985
110
275
      foreach my $vcond ($self->conditions->conds)
986        {
987          # We have a bit of error detection to do here.
988          # This:
989          # if COND1
990          # X = Y
991          # endif
992          # X += Z
993          # should be rejected because X is not defined for all conditions
994          # where `+=' applies.
995
121
380
          my $undef_cond = $self->not_always_defined_in_cond ($cond);
996
121
325
          if (! $undef_cond->false)
997            {
998
5
15
              error ($where,
999                     "cannot apply `+=' because `$var' is not defined "
1000                     . "in\nthe following conditions:\n "
1001
5
25
                     . join ("\n ", map { $_->human } $undef_cond->conds)
1002                     . "\neither define `$var' in these conditions,"
1003                     . " or use\n`+=' in the same conditions as"
1004                     . " the definitions.");
1005            }
1006          else
1007            {
1008
116
270
              &define ($var, $owner, '+', $vcond, $value, $comment,
1009                       $where, $pretty);
1010            }
1011        }
1012
110
224
      $self->{'last-append'} = $lastappend;
1013    }
1014  # 3. first assignment (=, :=, or +=)
1015  else
1016    {
1017      # There must be no previous value unless the user is redefining
1018      # an Automake variable or an AC_SUBST variable for an existing
1019      # condition.
1020
181015
624042
      _check_ambiguous_condition ($self, $cond, $where)
1021        unless (!$new_var
1022                && (($def->owner == VAR_AUTOMAKE && $owner != VAR_AUTOMAKE)
1023                    || $def->owner == VAR_CONFIGURE));
1024
1025      # Never decrease an owner.
1026
181015
426469
      $owner = $def->owner
1027        if ! $new_var && $owner < $def->owner;
1028
1029      # Assignments to a macro set its location. We don't adjust
1030      # locations for `+='. Ideally I suppose we would associate
1031      # line numbers with random bits of text.
1032
181015
503003
      $def = new Automake::VarDef ($var, $value, $comment, $where->clone,
1033                                   $type, $owner, $pretty);
1034
181015
461921
      $self->set ($cond, $def);
1035
181015
283494
      push @_var_order, $var;
1036    }
1037
1038  # Call any defined hook. This helps to update some internal state
1039  # *while* parsing the file. For instance the handling of SUFFIXES
1040  # requires this (see var_SUFFIXES_trigger).
1041
195425
11
722644
52
  &{$_hooks{$var}}($type, $value) if exists $_hooks{$var};
1042}
1043
1044 - 1049
=item C<variable_delete ($varname, [@conds])>

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

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

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

=cut
1078
1079sub variables_dump ()
1080{
1081
0
1
0
  my $text = "all variables:\n{\n";
1082
0
0
0
0
  foreach my $var (sort { $a->name cmp $b->name } variables)
1083    {
1084
0
0
      $text .= $var->dump;
1085    }
1086
0
0
  $text .= "}\n";
1087
0
0
  return $text;
1088}
1089
1090
1091 - 1101
=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
1102
1103sub set_seen ($)
1104{
1105
25487
1
44658
  my ($self) = @_;
1106
25487
57103
  $self = ref $self ? $self : var $self;
1107
1108
25487
75569
  return 0 unless $self;
1109
1110
8851
22812
  for my $c ($self->conditions->conds)
1111    {
1112
9133
23244
      $self->rdef ($c)->set_seen;
1113    }
1114
1115
8851
15568
  return $self;
1116}
1117
1118
1119 - 1127
=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
1128
1129sub require_variables ($$$@)
1130{
1131
1873
1
5322
  my ($where, $reason, $cond, @vars) = @_;
1132
1873
2599
  my $res = 0;
1133
1873
5517
  $reason .= ' but ' unless $reason eq '';
1134
1135
1873
6396
  $configure_ac = find_configure_ac
1136    unless defined $configure_ac;
1137
1138 VARIABLE:
1139
1873
4857
  foreach my $var (@vars)
1140    {
1141      # Nothing to do if the variable exists.
1142      next VARIABLE
1143
1897
3789
        if vardef ($var, $cond);
1144
1145
58
204
      my $text = "$reason`$var' is undefined\n";
1146
58
113
      my $v = var $var;
1147
58
273
      if ($v)
1148        {
1149
12
94
          my $undef_cond = $v->not_always_defined_in_cond ($cond);
1150          next VARIABLE
1151
12
40
            if $undef_cond->false;
1152
2
11
          $text .= ("in the following conditions:\n "
1153
2
7
                    . join ("\n ", map { $_->human } $undef_cond->conds)
1154                    . "\n");
1155        }
1156
1157
48
60
      ++$res;
1158
1159
48
261
      if (exists $_am_macro_for_var{$var})
1160        {
1161
25
59
          my $mac = $_am_macro_for_var{$var};
1162
25
133
          $text .= " The usual way to define `$var' is to add "
1163            . "`$mac'\n to `$configure_ac' and run `aclocal' and "
1164            . "`autoconf' again.";
1165          # aclocal will not warn about undefined macros unless it
1166          # starts with AM_.
1167
25
146
          $text .= "\n If `$mac' is in `$configure_ac', make sure\n"
1168            . " its definition is in aclocal's search path."
1169            unless $mac =~ /^AM_/;
1170        }
1171      elsif (exists $_ac_macro_for_var{$var})
1172        {
1173
18
109
          $text .= " The usual way to define `$var' is to add "
1174            . "`$_ac_macro_for_var{$var}'\n to `$configure_ac' and "
1175            . "run `autoconf' again.";
1176        }
1177
1178
48
237
      error $where, $text, uniq_scope => US_GLOBAL;
1179    }
1180
1873
5079
  return $res;
1181}
1182
1183 - 1189
=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
1190
1191sub requires_variables ($$@)
1192{
1193
1157
1
3157
  my ($var, $reason, @args) = @_;
1194
1157
1537
  my $res = 0;
1195
1157
3108
  for my $cond ($var->conditions->conds)
1196    {
1197
1159
3309
      $res += require_variables ($var->rdef ($cond)->location, $reason,
1198                                 $cond, @args);
1199    }
1200
1157
4729
  return $res;
1201}
1202
1203
1204 - 1211
=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
1212
1213sub variable_value ($)
1214{
1215
3876
1
10003
    my ($var) = @_;
1216
3876
16787
    my $v = ref ($var) ? $var : var ($var);
1217
3876
15560
    return () unless $v;
1218
3131
51949
    $v->check_defined_unconditionally;
1219
3131
9828
    my $d = $v->def (TRUE);
1220
3131
15144
    return $d ? $d->value : "";
1221}
1222
1223 - 1227
=item C<$str = output_variables>

Format definitions for all variables.

=cut
1228
1229sub output_variables ()
1230{
1231
1319
1
2956
  my $res = '';
1232  # We output variables it in the same order in which they were
1233  # defined (skipping duplicates).
1234
1319
11231
  my @vars = uniq @_var_order;
1235
1236  # Output all the Automake variables. If the user changed one,
1237  # then it is now marked as VAR_CONFIGURE or VAR_MAKEFILE.
1238
1319
11204
  foreach my $var (@vars)
1239    {
1240
177479
282972
      my $v = rvar $var;
1241
177479
439162
      foreach my $cond ($v->conditions->conds)
1242        {
1243
177648
407465
          $res .= $v->output ($cond)
1244            if $v->rdef ($cond)->owner == VAR_AUTOMAKE;
1245        }
1246    }
1247
1248  # Now dump the user variables that were defined.
1249
1319
3617
  foreach my $var (@vars)
1250    {
1251
177479
286021
      my $v = rvar $var;
1252
177479
438918
      foreach my $cond ($v->conditions->conds)
1253        {
1254
177648
408478
          $res .= $v->output ($cond)
1255            if $v->rdef ($cond)->owner != VAR_AUTOMAKE;
1256        }
1257    }
1258
1319
28126
  return $res;
1259}
1260
1261 - 1315
=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
1316
1317# Contains a stack of `from' and `to' parts of variable
1318# substitutions currently in force.
1319my @_substfroms;
1320my @_substtos;
1321sub traverse_recursively ($&&;%)
1322{
1323
5992
1
7398
  ++$_traversal;
1324
5992
11736
  @_substfroms = ();
1325
5992
7717
  @_substtos = ();
1326
5992
14544
  my ($var, $fun_item, $fun_collect, %options) = @_;
1327
5992
9195
  my $cond_filter = $options{'cond_filter'};
1328
5992
8379
  my $inner_expand = $options{'inner_expand'};
1329
5992
7877
  my $skip_ac_subst = $options{'skip_ac_subst'};
1330
5992
17016
  return $var->_do_recursive_traversal ($var,
1331                                        $fun_item, $fun_collect,
1332                                        $cond_filter, TRUE, $inner_expand,
1333                                        $skip_ac_subst)
1334}
1335
1336# The guts of Automake::Variable::traverse_recursively.
1337sub _do_recursive_traversal ($$&&$$$$)
1338{
1339
6481
15699
  my ($var, $parent, $fun_item, $fun_collect, $cond_filter, $parent_cond,
1340      $inner_expand, $skip_ac_subst) = @_;
1341
1342
6481
13066
  $var->set_seen;
1343
1344
6481
17384
  if ($var->{'scanned'} == $_traversal)
1345    {
1346
10
26
      err_var $var, "variable `" . $var->name() . "' recursively defined";
1347
10
30
      return ();
1348    }
1349
6471
9425
  $var->{'scanned'} = $_traversal;
1350
1351
6471
8582
  my @allresults = ();
1352
6471
7336
  my $cond_once = 0;
1353
6471
16291
  foreach my $cond ($var->conditions->conds)
1354    {
1355
6621
14078
      if (ref $cond_filter)
1356        {
1357          # Ignore conditions that don't match $cond_filter.
1358
129
398
          next if ! $cond->true_when ($cond_filter);
1359          # If we found out several definitions of $var
1360          # match $cond_filter then we are in trouble.
1361          # Tell the user we don't support this.
1362
128
370
          $var->check_defined_unconditionally ($parent, $parent_cond)
1363            if $cond_once;
1364
128
206
          $cond_once = 1;
1365        }
1366
6620
8706
      my @result = ();
1367
6620
17532
      my $full_cond = $cond->merge ($parent_cond);
1368
1369
6620
20322
      my @to_process = $var->value_as_list ($cond, $parent, $parent_cond);
1370
6620
15552
      while (@to_process)
1371        {
1372
9128
12670
          my $val = shift @to_process;
1373          # If $val is a variable (i.e. ${foo} or $(bar), not a filename),
1374          # handle the sub variable recursively.
1375          # (Backslashes before `}' and `)' within brackets are here to
1376          # please Emacs's indentation.)
1377
9128
81793
          if ($val =~ /^\$\{([^\}]*)\}$/ || $val =~ /^\$\(([^\)]*)\)$/)
1378            {
1379
495
1067
              my $subvarname = $1;
1380
1381              # If the user uses a losing variable name, just ignore it.
1382              # This isn't ideal, but people have requested it.
1383
495
1168
              next if ($subvarname =~ /\@.*\@/);
1384
1385              # See if the variable is actually a substitution reference
1386
495
655
              my ($from, $to);
1387              # This handles substitution references like ${foo:.a=.b}.
1388
495
1329
              if ($subvarname =~ /^([^:]*):([^=]*)=(.*)$/o)
1389                {
1390
66
98
                  $subvarname = $1;
1391
66
84
                  $to = $3;
1392
66
116
                  $from = quotemeta $2;
1393                }
1394
1395
495
910
              my $subvar = var ($subvarname);
1396              # Don't recurse into undefined variables.
1397
495
1020
              next unless $subvar;
1398
1399
489
711
              push @_substfroms, $from;
1400
489
639
              push @_substtos, $to;
1401
1402
489
2435
              my @res = $subvar->_do_recursive_traversal ($parent,
1403                                                          $fun_item,
1404                                                          $fun_collect,
1405                                                          $cond_filter,
1406                                                          $full_cond,
1407                                                          $inner_expand,
1408                                                          $skip_ac_subst);
1409
455
721
              push (@result, @res);
1410
1411
455
540
              pop @_substfroms;
1412
455
481
              pop @_substtos;
1413
1414
455
1170
              next;
1415            }
1416          # Try to expand variable references inside filenames such as
1417          # `$(NAME).txt'. We do not handle `:.foo=.bar'
1418          # substitutions, but it would make little sense to use this
1419          # here anyway.
1420          elsif ($inner_expand
1421                 && ($val =~ /\$\{([^\}]*)\}/ || $val =~ /\$\(([^\)]*)\)/))
1422            {
1423
4
8
              my $subvarname = $1;
1424
4
7
              my $subvar = var $subvarname;
1425
4
9
              if ($subvar)
1426                {
1427                  # Replace the reference by its value, and reschedule
1428                  # for expansion.
1429
4
10
                  foreach my $c ($subvar->conditions->conds)
1430                    {
1431
4
7
                      if (ref $cond_filter)
1432                        {
1433                          # Ignore conditions that don't match $cond_filter.
1434
0
0
                          next if ! $c->true_when ($cond_filter);
1435                          # If we found out several definitions of $var
1436                          # match $cond_filter then we are in trouble.
1437                          # Tell the user we don't support this.
1438
0
0
                          $subvar->check_defined_unconditionally ($var,
1439                                                                  $full_cond)
1440                            if $cond_once;
1441
0
0
                          $cond_once = 1;
1442                        }
1443
4
11
                      my $subval = $subvar->rdef ($c)->value;
1444
4
34
                      $val =~ s/\$\{$subvarname\}/$subval/g;
1445
4
27
                      $val =~ s/\$\($subvarname\)/$subval/g;
1446
4
15
                      unshift @to_process, split (' ', $val);
1447                    }
1448
4
11
                  next;
1449                }
1450              # We do not know any variable with this name. Fall through
1451              # to filename processing.
1452            }
1453          elsif ($skip_ac_subst && $val =~ /^\@.+\@$/)
1454            {
1455
4
11
              next;
1456            }
1457
1458
8625
16646
          if ($fun_item) # $var is a filename we must process
1459            {
1460
8625
16218
              my $substnum=$#_substfroms;
1461
8625
22708
              while ($substnum >= 0)
1462                {
1463
716
2324
                  $val =~ s/$_substfroms[$substnum]$/$_substtos[$substnum]/
1464                    if defined $_substfroms[$substnum];
1465
716
1907
                  $substnum -= 1;
1466                }
1467
1468              # Make sure you update the doc of
1469              # Automake::Variable::traverse_recursively
1470              # if you change the prototype of &fun_item.
1471
8625
19920
              my @transformed = &$fun_item ($var, $val, $cond, $full_cond);
1472
8575
25521
              push (@result, @transformed);
1473            }
1474        }
1475
6536
24697
      push (@allresults, [$cond, @result]) if @result;
1476    }
1477
1478  # We only care about _recursive_ variable definitions. The user
1479  # is free to use the same variable several times in the same definition.
1480
6387
12320
  $var->{'scanned'} = -1;
1481
1482  return ()
1483
6387
12431
    unless $fun_collect;
1484  # Make sure you update the doc of Automake::Variable::traverse_recursively
1485  # if you change the prototype of &fun_collect.
1486
6203
12801
  return &$fun_collect ($var, $parent_cond, @allresults);
1487}
1488
1489# _hash_varname ($VAR)
1490# --------------------
1491# Compute the key associated $VAR in %_gen_varname.
1492# See _gen_varname() below.
1493sub _hash_varname ($)
1494{
1495
1934
3396
  my ($var) = @_;
1496
1934
2913
  my $key = '';
1497
1934
5382
  foreach my $cond ($var->conditions->conds)
1498    {
1499
2013
4463
      my @values = $var->value_as_list ($cond);
1500
2013
8763
      $key .= "($cond)@values";
1501    }
1502
1934
4111
  return $key;
1503}
1504
1505# _hash_values (@VALUES)
1506# ----------------------
1507# Hash @VALUES for %_gen_varname. @VALUES should be a list
1508# of pairs: ([$cond, @values], [$cond, @values], ...).
1509# See _gen_varname() below.
1510sub _hash_values (@)
1511{
1512
945
1755
  my $key = '';
1513
945
2081
  foreach my $pair (@_)
1514    {
1515
936
2254
      my ($cond, @values) = @$pair;
1516
936
4536
      $key .= "($cond)@values";
1517    }
1518
945
5501
  return $key;
1519}
1520# ($VARNAME, $GENERATED)
1521# _gen_varname ($BASE, @DEFINITIONS)
1522# ----------------------------------
1523# Return a variable name starting with $BASE, that will be
1524# used to store definitions @DEFINITIONS.
1525# @DEFINITIONS is a list of pair [$COND, @OBJECTS].
1526#
1527# If we already have a $BASE-variable containing @DEFINITIONS, reuse
1528# it and set $GENERATED to 0. Otherwise construct a new name and set
1529# $GENERATED to 1.
1530#
1531# This way, we avoid combinatorial explosion of the generated
1532# variables. Especially, in a Makefile such as:
1533#
1534# | if FOO1
1535# | A1=1
1536# | endif
1537# |
1538# | if FOO2
1539# | A2=2
1540# | endif
1541# |
1542# | ...
1543# |
1544# | if FOON
1545# | AN=N
1546# | endif
1547# |
1548# | B=$(A1) $(A2) ... $(AN)
1549# |
1550# | c_SOURCES=$(B)
1551# | d_SOURCES=$(B)
1552#
1553# The generated c_OBJECTS and d_OBJECTS will share the same variable
1554# definitions.
1555#
1556# This setup can be the case of a testsuite containing lots (>100) of
1557# small C programs, all testing the same set of source files.
1558sub _gen_varname ($@)
1559{
1560
245
434
  my $base = shift;
1561
245
552
  my $key = _hash_values @_;
1562
1563
245
1137
  return ($_gen_varname{$base}{$key}, 0)
1564    if exists $_gen_varname{$base}{$key};
1565
1566
141
701
  my $num = 1 + ($_gen_varname_n{$base} || 0);
1567
141
238
  $_gen_varname_n{$base} = $num;
1568
141
305
  my $name = "${base}_${num}";
1569
141
346
  $_gen_varname{$base}{$key} = $name;
1570
1571
141
334
  return ($name, 1);
1572}
1573
1574 - 1601
=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
1602
1603sub transform_variable_recursively ($$$$$&;%)
1604{
1605
1763
1
6401
  my ($var, $resvar, $base, $nodefine, $where, $fun_item, %options) = @_;
1606
1607
1763
5317
  $var = ref $var ? $var : rvar $var;
1608
1609  my $res = $var->traverse_recursively
1610    ($fun_item,
1611     # The code that defines the variable holding the result
1612     # of the recursive transformation of a subvariable.
1613     sub {
1614
2031
4821
       my ($subvar, $parent_cond, @allresults) = @_;
1615       # If no definition is required, return anything: the result is
1616       # not expected to be used, only the side effect of $fun_item
1617       # should matter.
1618
2031
4496
       return 'report-me' if $nodefine;
1619       # Cache $subvar, so that we reuse it if @allresults is the same.
1620
1934
4928
       my $key = _hash_varname $subvar;
1621
1934
5364
       $_gen_varname{$base}{$key} = $subvar->name;
1622
1623       # Find a name for the variable, unless this is the top-variable
1624       # for which we want to use $resvar.
1625
1934
7654
       my ($varname, $generated) =
1626         ($var != $subvar) ? _gen_varname ($base, @allresults) : ($resvar, 1);
1627
1628       # Define the variable if we are not reusing a previously
1629       # defined variable. At the top-level, we can also avoid redefining
1630       # the variable if it already contains the same values.
1631
1934
9765
       if ($generated
1632           && !($varname eq $var->name && $key eq _hash_values @allresults))
1633         {
1634           # If the new variable is the source variable, we assume
1635           # we are trying to override a user variable. Delete
1636           # the old variable first.
1637
1762
4708
           variable_delete ($varname) if $varname eq $var->name;
1638           # Define an empty variable in condition TRUE if there is no
1639           # result.
1640
1762
4719
           @allresults = ([TRUE, '']) unless @allresults;
1641           # Define the rewritten variable in all conditions not
1642           # already covered by user definitions.
1643
1762
3378
           foreach my $pair (@allresults)
1644             {
1645
1828
4185
               my ($cond, @result) = @$pair;
1646
1828
3410
               my $var = var $varname;
1647
1828
5212
               my @conds = ($var
1648                            ? $var->not_always_defined_in_cond ($cond)->conds
1649                            : $cond);
1650
1651
1828
3694
               foreach (@conds)
1652                 {
1653
1818
6729
                   define ($varname, VAR_AUTOMAKE, '', $_, "@result",
1654                           '', $where, VAR_PRETTY);
1655                 }
1656             }
1657         }
1658
1934
4303
       set_seen $varname;
1659
1934
9266
       return "\$($varname)";
1660     },
1661
1763
20251
     %options);
1662
1763
19081
  return $res;
1663}
1664
1665
1666=back
1667
1668 - 1673
=head1 SEE ALSO

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

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