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