* automake.in (lang_yacc_target_hook): Use Automake::Rule::define
[automake.git] / lib / Automake / Variable.pm
blob797d2ca94bf3af73f825df02f0c7076c62175f41
1 # Copyright (C) 2003, 2004 Free Software Foundation, Inc.
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.
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.
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.
18 package Automake::Variable;
19 use strict;
20 use Carp;
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';
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);
47 =head1 NAME
49 Automake::Variable - support for variable definitions
51 =head1 SYNOPSIS
53 use Automake::Variable;
54 use Automake::VarDef;
56 # Defining a variable.
57 Automake::Variable::define($varname, $owner, $type,
58 $cond, $value, $comment,
59 $where, $pretty)
61 # Looking up a variable.
62 my $var = var $varname;
63 if ($var)
65 ...
68 # Looking up a variable that is assumed to exist.
69 my $var = rvar $varname;
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
76 # Accessing to the definition in Condition $cond.
77 # $def is an Automake::VarDef.
78 my $def = $var->def ($cond);
79 if ($def)
81 ...
84 # When the conditional definition is assumed to exist, use
85 my $def = $var->rdef ($cond);
88 =head1 DESCRIPTION
90 This package provides support for Makefile variable definitions.
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>.
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:
100 my $var = var $name;
101 if ($var)
103 my $def = $var->def ($cond);
104 if ($def)
106 return $def->value;
112 When it is known that the variable and the definition
113 being looked up exist, the above can be simplified to
115 return var ($name)->def ($cond)->value; # Do not write this.
117 but is better written
119 return rvar ($name)->rdef ($cond)->value;
121 or even
123 return rvardef ($name, $cond)->value;
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).
131 =cut
133 my $_VARIABLE_PATTERN = '^[.A-Za-z0-9_@]+' . "\$";
135 # The order in which variables should be output. (May contain
136 # duplicates -- only the first occurrence matters.)
137 my @_var_order;
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 = ();
146 # Declare the macros that define known variables, so we can
147 # hint the user if she try to use one of these variables.
149 # Macros accessible via aclocal.
150 my %_am_macro_for_var =
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',
168 # Macros shipped with Autoconf.
169 my %_ac_macro_for_var =
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',
182 # The name of the configure.ac file.
183 my $configure_ac = find_configure_ac;
185 # Variables that can be overriden without complaint from -Woverride
186 my %_silent_variable_override =
187 (AM_MAKEINFOHTMLFLAGS => 1,
188 AR => 1,
189 ARFLAGS => 1,
190 DEJATOOL => 1,
191 JAVAC => 1);
193 # This hash records helper variables used to implement conditional '+='.
194 # Keys have the form "VAR:CONDITIONS". The value associated to a key is
195 # the named of the helper variable used to append to VAR in CONDITIONS.
196 my %_appendvar = ();
198 # Each call to C<Automake::Variable::traverse_recursively> gets an
199 # unique label. This is used to detect recursively defined variables.
200 my $_traversal = 0;
203 =head2 Error reporting functions
205 In these functions, C<$var> can be either a variable name, or
206 an instance of C<Automake::Variable>.
208 =over 4
210 =item C<err_var ($var, $message, [%options])>
212 Uncategorized errors about variables.
214 =cut
216 sub err_var ($$;%)
218 msg_var ('error', @_);
221 =item C<msg_cond_var ($channel, $cond, $var, $message, [%options])>
223 Messages about conditional variable.
225 =cut
227 sub msg_cond_var ($$$$;%)
229 my ($channel, $cond, $var, $msg, %opts) = @_;
230 my $v = ref ($var) ? $var : rvar ($var);
231 msg $channel, $v->rdef ($cond)->location, $msg, %opts;
234 =item C<msg_var ($channel, $var, $message, [%options])>
236 Messages about variables.
238 =cut
240 sub msg_var ($$$;%)
242 my ($channel, $var, $msg, %opts) = @_;
243 my $v = ref ($var) ? $var : rvar ($var);
244 # Don't know which condition is concerned. Pick any.
245 my $cond = $v->conditions->one_cond;
246 msg_cond_var $channel, $cond, $v, $msg, %opts;
249 =item C<$bool = reject_var ($varname, $error_msg)>
251 Bail out with C<$error_msg> if a variable with name C<$varname> has
252 been defined.
254 Return true iff C<$varname> is defined.
256 =cut
258 sub reject_var ($$)
260 my ($var, $msg) = @_;
261 my $v = var ($var);
262 if ($v)
264 err_var $v, $msg;
265 return 1;
267 return 0;
270 =back
272 =head2 Administrative functions
274 =over 4
276 =item C<Automake::Variable::hook ($varname, $fun)>
278 Declare a function to be called whenever a variable
279 named C<$varname> is defined or redefined.
281 C<$fun> should take two arguments: C<$type> and C<$value>.
282 When type is C<''> or <':'>, C<$value> is the value being
283 assigned to C<$varname>. When C<$type> is C<'+'>, C<$value>
284 is the value being appended to C<$varname>.
286 =cut
288 use vars '%_hooks';
289 sub hook ($$)
291 my ($var, $fun) = @_;
292 $_hooks{$var} = $fun;
295 =item C<variables>
297 Returns the list of all L<Automake::Variable> instances. (I.e., all
298 variables defined so far.)
300 =cut
302 use vars '%_variable_dict';
303 sub variables ()
305 return values %_variable_dict;
308 =item C<Automake::Variable::reset>
310 The I<forget all> function. Clears all know variables and reset some
311 other internal data.
313 =cut
315 sub reset ()
317 %_variable_dict = ();
318 %_appendvar = ();
319 @_var_order = ();
320 %_gen_varname = ();
321 $_traversal = 0;
324 =item C<var ($varname)>
326 Return the C<Automake::Variable> object for the variable
327 named C<$varname> if defined. Return 0 otherwise.
329 =cut
331 sub var ($)
333 my ($name) = @_;
334 return $_variable_dict{$name} if exists $_variable_dict{$name};
335 return 0;
338 =item C<vardef ($varname, $cond)>
340 Return the C<Automake::VarDef> object for the variable named
341 C<$varname> if defined in condition C<$cond>. Return false
342 if the condition or the variable does not exist.
344 =cut
346 sub vardef ($$)
348 my ($name, $cond) = @_;
349 my $var = var $name;
350 return $var && $var->def ($cond);
353 # Create the variable if it does not exist.
354 # This is used only by other functions in this package.
355 sub _cvar ($)
357 my ($name) = @_;
358 my $v = var $name;
359 return $v if $v;
360 return _new Automake::Variable $name;
363 =item C<rvar ($varname)>
365 Return the C<Automake::Variable> object for the variable named
366 C<$varname>. Abort with an internal error if the variable was not
367 defined.
369 The I<r> in front of C<var> stands for I<required>. One
370 should call C<rvar> to assert the variable's existence.
372 =cut
374 sub rvar ($)
376 my ($name) = @_;
377 my $v = var $name;
378 prog_error ("undefined variable $name\n" . &variables_dump)
379 unless $v;
380 return $v;
383 =item C<rvardef ($varname, $cond)>
385 Return the C<Automake::VarDef> object for the variable named
386 C<$varname> if defined in condition C<$cond>. Abort with an internal
387 error if the condition or the variable does not exist.
389 =cut
391 sub rvardef ($$)
393 my ($name, $cond) = @_;
394 return rvar ($name)->rdef ($cond);
397 =back
399 =head2 Methods
401 C<Automake::Variable> is a subclass of C<Automake::Item>. See
402 that package for inherited methods.
404 Here are the methods specific to the C<Automake::Variable> instances.
405 Use the C<define> function, described latter, to create such objects.
407 =over 4
409 =cut
411 # Create Automake::Variable objects. This is used
412 # only in this file. Other users should use
413 # the "define" function.
414 sub _new ($$)
416 my ($class, $name) = @_;
417 my $self = Automake::Item::new ($class, $name);
418 $self->{'scanned'} = 0;
419 $_variable_dict{$name} = $self;
420 return $self;
423 # _check_ambiguous_condition ($SELF, $COND, $WHERE)
424 # -------------------------------------------------
425 # Check for an ambiguous conditional. This is called when a variable
426 # is being defined conditionally. If we already know about a
427 # definition that is true under the same conditions, then we have an
428 # ambiguity.
429 sub _check_ambiguous_condition ($$$)
431 my ($self, $cond, $where) = @_;
432 my $var = $self->name;
433 my ($message, $ambig_cond) = $self->conditions->ambiguous_p ($var, $cond);
435 # We allow silent variables to be overridden silently.
436 my $def = $self->def ($cond);
437 if ($message && !($def && $def->pretty == VAR_SILENT))
439 msg 'syntax', $where, "$message ...", partial => 1;
440 msg_var ('syntax', $var, "... `$var' previously defined here");
441 verb ($self->dump);
445 =item C<$bool = $var-E<gt>check_defined_unconditionally ([$parent, $parent_cond])>
447 Warn if the variable is conditionally defined. C<$parent> is the name
448 of the parent variable, and C<$parent_cond> the condition of the parent
449 definition. These two variables are used to display diagnostics.
451 =cut
453 sub check_defined_unconditionally ($;$$)
455 my ($self, $parent, $parent_cond) = @_;
457 if (!$self->conditions->true)
459 if ($parent)
461 msg_cond_var ('unsupported', $parent_cond, $parent,
462 "automake does not support conditional definition of "
463 . $self->name . " in $parent");
465 else
467 msg_var ('unsupported', $self,
468 "automake does not support " . $self->name
469 . " being defined conditionally");
474 =item C<$str = $var-E<gt>output ([@conds])>
476 Format all the definitions of C<$var> if C<@cond> is not specified,
477 else only that corresponding to C<@cond>.
479 =cut
481 sub output ($@)
483 my ($self, @conds) = @_;
485 @conds = $self->conditions->conds
486 unless @conds;
488 my $res = '';
489 my $name = $self->name;
491 foreach my $cond (@conds)
493 my $def = $self->def ($cond);
494 prog_error ("unknown condition `" . $cond->human . "' for `"
495 . $self->name . "'")
496 unless $def;
498 next
499 if $def->pretty == VAR_SILENT;
501 $res .= $def->comment;
503 my $val = $def->raw_value;
504 my $equals = $def->type eq ':' ? ':=' : '=';
505 my $str = $cond->subst_string;
508 if ($def->pretty == VAR_ASIS)
510 my $output_var = "$name $equals $val";
511 $output_var =~ s/^/$str/meg;
512 $res .= "$output_var\n";
514 elsif ($def->pretty == VAR_PRETTY)
516 # Suppress escaped new lines. &makefile_wrap will
517 # add them back, maybe at other places.
518 $val =~ s/\\$//mg;
519 my $wrap = makefile_wrap ("$str$name $equals", "$str\t",
520 split (' ', $val));
522 # If the last line of the definition is made only of
523 # @substitutions@, append an empty variable to make sure it
524 # cannot be substituted as a blank line (that would confuse
525 # HP-UX Make).
526 $wrap = makefile_wrap ("$str$name $equals", "$str\t",
527 split (' ', $val), '$(am__empty)')
528 if $wrap =~ /\n(\s*@\w+@)+\s*$/;
530 $res .= $wrap;
532 else # ($def->pretty == VAR_SORTED)
534 # Suppress escaped new lines. &makefile_wrap will
535 # add them back, maybe at other places.
536 $val =~ s/\\$//mg;
537 $res .= makefile_wrap ("$str$name $equals", "$str\t",
538 sort (split (' ' , $val)));
541 return $res;
544 =item C<@values = $var-E<gt>value_as_list ($cond, [$parent, $parent_cond])>
546 Get the value of C<$var> as a list, given a specified condition,
547 without recursing through any subvariables.
549 C<$cond> is the condition of interest. C<$var> does not need
550 to be defined for condition C<$cond> exactly, but it needs
551 to be defined for at most one condition implied by C<$cond>.
553 C<$parent> and C<$parent_cond> designate the name and the condition
554 of the parent variable, i.e., the variable in which C<$var> is
555 being expanded. These are used in diagnostics.
557 For example, if C<A> is defined as "C<foo $(B) bar>" in condition
558 C<TRUE>, calling C<rvar ('A')->value_as_list (TRUE)> will return
559 C<("foo", "$(B)", "bar")>.
561 =cut
563 sub value_as_list ($$;$$)
565 my ($self, $cond, $parent, $parent_cond) = @_;
566 my @result;
568 # Get value for given condition
569 my $onceflag;
570 foreach my $vcond ($self->conditions->conds)
572 if ($vcond->true_when ($cond))
574 # If there is more than one definitions of $var matching
575 # $cond then we are in trouble: tell the user we need a
576 # paddle. Continue by merging results from all conditions,
577 # although it doesn't make much sense.
578 $self->check_defined_unconditionally ($parent, $parent_cond)
579 if $onceflag;
580 $onceflag = 1;
582 my $val = $self->rdef ($vcond)->value;
583 push @result, split (' ', $val);
586 return @result;
589 =item C<@values = $var-E<gt>value_as_list_recursive ([%options])>
591 Return the contents of C<$var> as a list, split on whitespace. This
592 will recursively follow C<$(...)> and C<${...}> inclusions. It
593 preserves C<@...@> substitutions.
595 C<%options> is a list of option for C<Variable::traverse_recursively>
596 (see this method). The most useful is C<cond_filter>:
598 $var->value_as_list_recursive (cond_filter => $cond)
600 will return the contents of C<$var> and any subvariable in all
601 conditions implied by C<$cond>.
603 C<%options> can also carry options specific to C<value_as_list_recursive>.
604 Presently, the only such option is C<location =E<gt> 1> which instructs
605 C<value_as_list_recursive> to return a list of C<[$location, @values]> pairs.
607 =cut
609 sub value_as_list_recursive ($;%)
611 my ($var, %options) = @_;
613 return $var->traverse_recursively
614 (# Construct [$location, $value] pairs if requested.
615 sub {
616 my ($var, $val, $cond, $full_cond) = @_;
617 return [$var->rdef ($cond)->location, $val] if $options{'location'};
618 return $val;
620 # Collect results.
621 sub {
622 my ($var, $parent_cond, @allresults) = @_;
623 return map { my ($cond, @vals) = @$_; @vals } @allresults;
625 %options);
629 =item C<$bool = $var-E<gt>has_conditional_contents>
631 Return 1 if C<$var> or one of its subvariable was conditionally
632 defined. Return 0 otherwise.
634 =cut
636 sub has_conditional_contents ($)
638 my ($self) = @_;
640 # Traverse the variable recursively until we
641 # find a variable defined conditionally.
642 # Use `die' to abort the traversal, and pass it `$full_cond'
643 # to we can find easily whether the `eval' block aborted
644 # because we found a condition, or for some other error.
645 eval
647 $self->traverse_recursively
648 (sub
650 my ($subvar, $val, $cond, $full_cond) = @_;
651 die $full_cond if ! $full_cond->true;
652 return ();
654 sub { return (); });
656 if ($@)
658 return 1 if ref ($@) && $@->isa ("Automake::Condition");
659 # Propagate other errors.
660 die;
662 return 0;
666 =item C<$string = $var-E<gt>dump>
668 Return a string describing all we know about C<$var>.
669 For debugging.
671 =cut
673 sub dump ($)
675 my ($self) = @_;
677 my $text = $self->name . ": \n {\n";
678 foreach my $vcond ($self->conditions->conds)
680 $text .= " " . $vcond->human . " => " . $self->rdef ($vcond)->dump;
682 $text .= " }\n";
683 return $text;
687 =back
689 =head2 Utility functions
691 =over 4
693 =item C<@list = scan_variable_expansions ($text)>
695 Return the list of variable names expanded in C<$text>. Note that
696 unlike some other functions, C<$text> is not split on spaces before we
697 check for subvariables.
699 =cut
701 sub scan_variable_expansions ($)
703 my ($text) = @_;
704 my @result = ();
706 # Strip comments.
707 $text =~ s/#.*$//;
709 # Record each use of ${stuff} or $(stuff) that does not follow a $.
710 while ($text =~ /(?<!\$)\$(?:\{([^\}]*)\}|\(([^\)]*)\))/g)
712 my $var = $1 || $2;
713 # The occurence may look like $(string1[:subst1=[subst2]]) but
714 # we want only `string1'.
715 $var =~ s/:[^:=]*=[^=]*$//;
716 push @result, $var;
719 return @result;
722 =item C<check_variable_expansions ($text, $where)>
724 Check variable expansions in C<$text> and warn about any name that
725 does not conform to POSIX. C<$where> is the location of C<$text>
726 for the error message.
728 =cut
730 sub check_variable_expansions ($$)
732 my ($text, $where) = @_;
733 # Catch expansion of variables whose name does not conform to POSIX.
734 foreach my $var (scan_variable_expansions ($text))
736 if ($var !~ /$_VARIABLE_PATTERN/o)
738 # If the variable name contains a space, it's likely
739 # to be a GNU make extension (such as $(addsuffix ...)).
740 # Mention this in the diagnostic.
741 my $gnuext = "";
742 $gnuext = "\n(probably a GNU make extension)" if $var =~ / /;
743 msg ('portability', $where,
744 "$var: non-POSIX variable name$gnuext");
751 =item C<Automake::Variable::define($varname, $owner, $type, $cond, $value, $comment, $where, $pretty)>
753 Define or append to a new variable.
755 C<$varname>: the name of the variable being defined.
757 C<$owner>: owner of the variable (one of C<VAR_MAKEFILE>,
758 C<VAR_CONFIGURE>, or C<VAR_AUTOMAKE>, defined by L<Automake::VarDef>).
759 Variables can be overriden, provided the new owner is not weaker
760 (C<VAR_AUTOMAKE> < C<VAR_CONFIGURE> < C<VAR_MAKEFILE>).
762 C<$type>: the type of the assignment (C<''> for C<FOO = bar>,
763 C<':'> for C<FOO := bar>, and C<'+'> for C<'FOO += bar'>).
765 C<$cond>: the C<Condition> in which C<$var> is being defined.
767 C<$value>: the value assigned to C<$var> in condition C<$cond>.
769 C<$comment>: any comment (C<'# bla.'>) associated with the assignment.
770 Comments from C<+=> assignments stack with comments from the last C<=>
771 assignment.
773 C<$where>: the C<Location> of the assignment.
775 C<$pretty>: whether C<$value> should be pretty printed (one of
776 C<VAR_ASIS>, C<VAR_PRETTY>, C<VAR_SILENT>, or C<VAR_SORTED>, defined
777 by by L<Automake::VarDef>). C<$pretty> applies only to real
778 assignments. I.e., it does not apply to a C<+=> assignment (except
779 when part of it is being done as a conditional C<=> assignment).
781 This function will all run any hook registered with the C<hook>
782 function.
784 =cut
786 sub define ($$$$$$$$)
788 my ($var, $owner, $type, $cond, $value, $comment, $where, $pretty) = @_;
790 prog_error "$cond is not a reference"
791 unless ref $where;
793 prog_error "$where is not a reference"
794 unless ref $where;
796 prog_error "pretty argument missing"
797 unless defined $pretty && ($pretty == VAR_ASIS
798 || $pretty == VAR_PRETTY
799 || $pretty == VAR_SILENT
800 || $pretty == VAR_SORTED);
802 error $where, "bad characters in variable name `$var'"
803 if $var !~ /$_VARIABLE_PATTERN/o;
805 # `:='-style assignments are not acknowledged by POSIX. Moreover it
806 # has multiple meanings. In GNU make or BSD make it means "assign
807 # with immediate expansion", while in OSF make it is used for
808 # conditional assignments.
809 msg ('portability', $where, "`:='-style assignments are not portable")
810 if $type eq ':';
812 check_variable_expansions ($value, $where);
814 # If there's a comment, make sure it is \n-terminated.
815 if ($comment)
817 chomp $comment;
818 $comment .= "\n";
820 else
822 $comment = '';
825 my $self = _cvar $var;
827 my $def = $self->def ($cond);
828 my $new_var = $def ? 0 : 1;
830 # Additional checks for Automake definitions.
831 if ($owner == VAR_AUTOMAKE && ! $new_var)
833 # An Automake variable must be consistently defined with the same
834 # sign by Automake.
835 if ($def->type ne $type && $def->owner == VAR_AUTOMAKE)
837 error ($def->location,
838 "Automake variable `$var' was set with `"
839 . $def->type . "=' here...", partial => 1);
840 error ($where, "... and is now set with `$type=' here.");
841 prog_error ("Automake variable assignments should be consistently\n"
842 . "defined with the same sign.");
845 # If Automake tries to override a value specified by the user,
846 # just don't let it do.
847 if ($def->owner != VAR_AUTOMAKE)
849 if (! exists $_silent_variable_override{$var})
851 my $condmsg = ($cond == TRUE
852 ? '' : (" in condition `" . $cond->human . "'"));
853 msg_cond_var ('override', $cond, $var,
854 "user variable `$var' defined here$condmsg...",
855 partial => 1);
856 msg ('override', $where,
857 "... overrides Automake variable `$var' defined here");
859 verb ("refusing to override the user definition of:\n"
860 . $self->dump ."with `" . $cond->human . "' => `$value'");
861 return;
865 # Differentiate assignment types.
867 # 1. append (+=) to a variable defined for current condition
868 if ($type eq '+' && ! $new_var)
870 $def->append ($value, $comment);
872 # Only increase owners. A VAR_CONFIGURE variable augmented in a
873 # Makefile.am becomes a VAR_MAKEFILE variable.
874 $def->set_owner ($owner, $where->clone)
875 if $owner > $def->owner;
877 # 2. append (+=) to a variable defined for *another* condition
878 elsif ($type eq '+' && ! $self->conditions->false)
880 # * Generally, $cond is not TRUE. For instance:
881 # FOO = foo
882 # if COND
883 # FOO += bar
884 # endif
885 # In this case, we declare an helper variable conditionally,
886 # and append it to FOO:
887 # FOO = foo $(am__append_1)
888 # @COND_TRUE@am__append_1 = bar
889 # Of course if FOO is defined under several conditions, we add
890 # $(am__append_1) to each definitions.
892 # * If $cond is TRUE, we don't need the helper variable. E.g., in
893 # if COND1
894 # FOO = foo1
895 # else
896 # FOO = foo2
897 # endif
898 # FOO += bar
899 # we can add bar directly to all definition of FOO, and output
900 # @COND_TRUE@FOO = foo1 bar
901 # @COND_FALSE@FOO = foo2 bar
903 # Do we need an helper variable?
904 if ($cond != TRUE)
906 # Does the helper variable already exists?
907 my $key = "$var:" . $cond->string;
908 if (exists $_appendvar{$key})
910 # Yes, let's simply append to it.
911 $var = $_appendvar{$key};
912 $owner = VAR_AUTOMAKE;
913 $self = var ($var);
914 $def = $self->rdef ($cond);
915 $new_var = 0;
917 else
919 # No, create it.
920 my $num = 1 + keys (%_appendvar);
921 my $hvar = "am__append_$num";
922 $_appendvar{$key} = $hvar;
923 &define ($hvar, VAR_AUTOMAKE, '+',
924 $cond, $value, $comment, $where, $pretty);
925 # Now HVAR is to be added to VAR.
926 $comment = '';
927 $value = "\$($hvar)";
931 # Add VALUE to all definitions of SELF.
932 foreach my $vcond ($self->conditions->conds)
934 # We have a bit of error detection to do here.
935 # This:
936 # if COND1
937 # X = Y
938 # endif
939 # X += Z
940 # should be rejected because X is not defined for all conditions
941 # where `+=' applies.
942 my $undef_cond = $self->not_always_defined_in_cond ($cond);
943 if (! $undef_cond->false)
945 error ($where,
946 "Cannot apply `+=' because `$var' is not defined "
947 . "in\nthe following conditions:\n "
948 . join ("\n ", map { $_->human } $undef_cond->conds)
949 . "\nEither define `$var' in these conditions,"
950 . " or use\n`+=' in the same conditions as"
951 . " the definitions.");
953 else
955 &define ($var, $owner, '+', $vcond, $value, $comment,
956 $where, $pretty);
960 # 3. first assignment (=, :=, or +=)
961 else
963 # There must be no previous value unless the user is redefining
964 # an Automake variable or an AC_SUBST variable for an existing
965 # condition.
966 _check_ambiguous_condition ($self, $cond, $where)
967 unless (!$new_var
968 && (($def->owner == VAR_AUTOMAKE && $owner != VAR_AUTOMAKE)
969 || $def->owner == VAR_CONFIGURE));
971 # Never decrease an owner.
972 $owner = $def->owner
973 if ! $new_var && $owner < $def->owner;
975 # Assignments to a macro set its location. We don't adjust
976 # locations for `+='. Ideally I suppose we would associate
977 # line numbers with random bits of text.
978 $def = new Automake::VarDef ($var, $value, $comment, $where->clone,
979 $type, $owner, $pretty);
980 $self->set ($cond, $def);
981 push @_var_order, $var;
984 # Call any defined hook. This helps to update some internal state
985 # *while* parsing the file. For instance the handling of SUFFIXES
986 # requires this (see var_SUFFIXES_trigger).
987 &{$_hooks{$var}}($type, $value) if exists $_hooks{$var};
990 =item C<variable_delete ($varname, [@conds])>
992 Forget about C<$varname> under the conditions C<@conds>, or completely
993 if C<@conds> is empty.
995 =cut
997 sub variable_delete ($@)
999 my ($var, @conds) = @_;
1001 if (!@conds)
1003 delete $_variable_dict{$var};
1005 else
1007 for my $cond (@conds)
1009 delete $_variable_dict{$var}{'defs'}{$cond};
1014 =item C<$str = variables_dump>
1016 Return a string describing all we know about all variables.
1017 For debugging.
1019 =cut
1021 sub variables_dump ()
1023 my $text = "All variables:\n{\n";
1024 foreach my $var (sort { $a->name cmp $b->name } variables)
1026 $text .= $var->dump;
1028 $text .= "}\n";
1029 return $text;
1033 =item C<$var = set_seen ($varname)>
1035 =item C<$var = $var-E<gt>set_seen>
1037 Mark all definitions of this variable as examined, if the variable
1038 exists. See L<Automake::VarDef::set_seen>.
1040 Return the C<Variable> object if the variable exists, or 0
1041 otherwise (i.e., as the C<var> function).
1043 =cut
1045 sub set_seen ($)
1047 my ($self) = @_;
1048 $self = ref $self ? $self : var $self;
1050 return 0 unless $self;
1052 for my $c ($self->conditions->conds)
1054 $self->rdef ($c)->set_seen;
1057 return $self;
1061 =item C<$count = require_variables ($where, $reason, $cond, @variables)>
1063 Make sure that each supplied variable is defined in C<$cond>.
1064 Otherwise, issue a warning showing C<$reason> (C<$reason> should be
1065 the reason why these variable are required, for instance C<'option foo
1066 used'>). If we know which macro can define this variable, hint the
1067 user. Return the number of undefined variables.
1069 =cut
1071 sub require_variables ($$$@)
1073 my ($where, $reason, $cond, @vars) = @_;
1074 my $res = 0;
1075 $reason .= ' but ' unless $reason eq '';
1077 VARIABLE:
1078 foreach my $var (@vars)
1080 # Nothing to do if the variable exists.
1081 next VARIABLE
1082 if vardef ($var, $cond);
1084 my $text = "$reason`$var' is undefined\n";
1085 my $v = var $var;
1086 if ($v)
1088 my $undef_cond = $v->not_always_defined_in_cond ($cond);
1089 next VARIABLE
1090 if $undef_cond->false;
1091 $text .= ("in the following conditions:\n "
1092 . join ("\n ", map { $_->human } $undef_cond->conds));
1095 ++$res;
1097 if (exists $_am_macro_for_var{$var})
1099 $text .= "\nThe usual way to define `$var' is to add "
1100 . "`$_am_macro_for_var{$var}'\nto `$configure_ac' and "
1101 . "run `aclocal' and `autoconf' again.";
1103 elsif (exists $_ac_macro_for_var{$var})
1105 $text .= "\nThe usual way to define `$var' is to add "
1106 . "`$_ac_macro_for_var{$var}'\nto `$configure_ac' and "
1107 . "run `autoconf' again.";
1110 error $where, $text, uniq_scope => US_GLOBAL;
1112 return $res;
1115 =item C<$count = $var->requires_variables ($reason, @variables)>
1117 Same as C<require_variables>, but a method of Automake::Variable.
1118 C<@variables> should be defined in the same conditions as C<$var> is
1119 defined.
1121 =cut
1123 sub requires_variables ($$@)
1125 my ($var, $reason, @args) = @_;
1126 my $res = 0;
1127 for my $cond ($var->conditions->conds)
1129 $res += require_variables ($var->rdef ($cond)->location, $reason,
1130 $cond, @args);
1132 return $res;
1136 =item C<variable_value ($var)>
1138 Get the C<TRUE> value of a variable, warn if the variable is
1139 conditionally defined. C<$var> can be either a variable name
1140 or a C<Automake::Variable> instance (this allows to calls sucha
1141 as C<$var-E<gt>variable_value>).
1143 =cut
1145 sub variable_value ($)
1147 my ($var) = @_;
1148 my $v = ref ($var) ? $var : var ($var);
1149 return () unless $v;
1150 $v->check_defined_unconditionally;
1151 return $v->rdef (TRUE)->value;
1154 =item C<$str = output_variables>
1156 Format definitions for all variables.
1158 =cut
1160 sub output_variables ()
1162 my $res = '';
1163 # We output variables it in the same order in which they were
1164 # defined (skipping duplicates).
1165 my @vars = uniq @_var_order;
1167 # Output all the Automake variables. If the user changed one,
1168 # then it is now marked as VAR_CONFIGURE or VAR_MAKEFILE.
1169 foreach my $var (@vars)
1171 my $v = rvar $var;
1172 foreach my $cond ($v->conditions->conds)
1174 $res .= $v->output ($cond)
1175 if $v->rdef ($cond)->owner == VAR_AUTOMAKE;
1179 # Now dump the user variables that were defined.
1180 foreach my $var (@vars)
1182 my $v = rvar $var;
1183 foreach my $cond ($v->conditions->conds)
1185 $res .= $v->output ($cond)
1186 if $v->rdef ($cond)->owner != VAR_AUTOMAKE;
1189 return $res;
1192 =item C<$var-E<gt>traverse_recursively (&fun_item, &fun_collect, [cond_filter =E<gt> $cond_filter], [inner_expand =E<gt> 1])>
1194 Split the value of the Automake::Variable C<$var> on space, and
1195 traverse its components recursively.
1197 If C<$cond_filter> is an C<Automake::Condition>, process any
1198 conditions which are true when C<$cond_filter> is true. Otherwise,
1199 process all conditions.
1201 We distinguish two kinds of items in the content of C<$var>.
1202 Terms that look like C<$(foo)> or C<${foo}> are subvariables
1203 and cause recursion. Other terms are assumed to be filenames.
1205 Each time a filename is encountered, C<&fun_item> is called with the
1206 following arguments:
1208 ($var, -- the Automake::Variable we are currently
1209 traversing
1210 $val, -- the item (i.e., filename) to process
1211 $cond, -- the Condition for the $var definition we are
1212 examinating (ignoring the recursion context)
1213 $full_cond) -- the full Condition, taking into account
1214 conditions inherited from parent variables
1215 during recursion
1217 If C<inner_expand> is set, variable references occuring in filename
1218 (as in C<$(BASE).ext>) are expansed before the filename is passed to
1219 C<&fun_item>.
1221 C<&fun_item> may return a list of items, they will be passed to
1222 C<&fun_store> later on. Define C<&fun_item> as C<undef> when it serve
1223 no purpose, this will speed things up.
1225 Once all items of a variable have been processed, the result (of the
1226 calls to C<&fun_items>, or of recursive traversals of subvariables)
1227 are passed to C<&fun_collect>. C<&fun_collect> receives three
1228 arguments:
1230 ($var, -- the variable being traversed
1231 $parent_cond, -- the Condition inherited from parent
1232 variables during recursion
1233 @condlist) -- a list of [$cond, @results] pairs
1234 where each $cond appear only once, and @result
1235 are all the results for this condition.
1237 Typically you should do C<$cond->merge ($parent_cond)> to recompute
1238 the C<$full_cond> associated to C<@result>. C<&fun_collect> may
1239 return a list of items, that will be used as the result of
1240 C<Automake::Variable::traverse_recursively> (the top-level, or its
1241 recursive calls).
1243 =cut
1245 # Contains a stack of `from' and `to' parts of variable
1246 # substitutions currently in force.
1247 my @_substfroms;
1248 my @_substtos;
1249 sub traverse_recursively ($&&;%)
1251 ++$_traversal;
1252 @_substfroms = ();
1253 @_substtos = ();
1254 my ($var, $fun_item, $fun_collect, %options) = @_;
1255 my $cond_filter = $options{'cond_filter'};
1256 my $inner_expand = $options{'inner_expand'};
1257 return $var->_do_recursive_traversal ($var,
1258 $fun_item, $fun_collect,
1259 $cond_filter, TRUE, $inner_expand)
1262 # The guts of Automake::Variable::traverse_recursively.
1263 sub _do_recursive_traversal ($$&&$$$)
1265 my ($var, $parent, $fun_item, $fun_collect, $cond_filter, $parent_cond,
1266 $inner_expand) = @_;
1268 $var->set_seen;
1270 if ($var->{'scanned'} == $_traversal)
1272 err_var $var, "variable `" . $var->name() . "' recursively defined";
1273 return ();
1275 $var->{'scanned'} = $_traversal;
1277 my @allresults = ();
1278 my $cond_once = 0;
1279 foreach my $cond ($var->conditions->conds)
1281 if (ref $cond_filter)
1283 # Ignore conditions that don't match $cond_filter.
1284 next if ! $cond->true_when ($cond_filter);
1285 # If we found out several definitions of $var
1286 # match $cond_filter then we are in trouble.
1287 # Tell the user we don't support this.
1288 $var->check_defined_unconditionally ($parent, $parent_cond)
1289 if $cond_once;
1290 $cond_once = 1;
1292 my @result = ();
1293 my $full_cond = $cond->merge ($parent_cond);
1295 my @to_process = $var->value_as_list ($cond, $parent, $parent_cond);
1296 while (@to_process)
1298 my $val = shift @to_process;
1299 # If $val is a variable (i.e. ${foo} or $(bar), not a filename),
1300 # handle the sub variable recursively.
1301 # (Backslashes before `}' and `)' within brackets are here to
1302 # please Emacs's indentation.)
1303 if ($val =~ /^\$\{([^\}]*)\}$/ || $val =~ /^\$\(([^\)]*)\)$/)
1305 my $subvarname = $1;
1307 # If the user uses a losing variable name, just ignore it.
1308 # This isn't ideal, but people have requested it.
1309 next if ($subvarname =~ /\@.*\@/);
1311 # See if the variable is actually a substitution reference
1312 my ($from, $to);
1313 # This handles substitution references like ${foo:.a=.b}.
1314 if ($subvarname =~ /^([^:]*):([^=]*)=(.*)$/o)
1316 $subvarname = $1;
1317 $to = $3;
1318 $from = quotemeta $2;
1321 my $subvar = var ($subvarname);
1322 # Don't recurse into undefined variables.
1323 next unless $subvar;
1325 push @_substfroms, $from;
1326 push @_substtos, $to;
1328 my @res = $subvar->_do_recursive_traversal ($parent,
1329 $fun_item,
1330 $fun_collect,
1331 $cond_filter,
1332 $full_cond,
1333 $inner_expand);
1334 push (@result, @res);
1336 pop @_substfroms;
1337 pop @_substtos;
1339 next;
1341 # Try to expand variable references inside filenames such as
1342 # `$(NAME).txt'. We do not handle `:.foo=.bar'
1343 # substitutions, but it would make little sense to use this
1344 # here anyway.
1345 elsif ($inner_expand
1346 && ($val =~ /\$\{([^\}]*)\}/ || $val =~ /\$\(([^\)]*)\)/))
1348 my $subvarname = $1;
1349 my $subvar = var $subvarname;
1350 if ($subvar)
1352 # Replace the reference by its value, and reschedule
1353 # for expansion.
1354 foreach my $c ($subvar->conditions->conds)
1356 if (ref $cond_filter)
1358 # Ignore conditions that don't match $cond_filter.
1359 next if ! $c->true_when ($cond_filter);
1360 # If we found out several definitions of $var
1361 # match $cond_filter then we are in trouble.
1362 # Tell the user we don't support this.
1363 $subvar->check_defined_unconditionally ($var,
1364 $full_cond)
1365 if $cond_once;
1366 $cond_once = 1;
1368 my $subval = $subvar->rdef ($c)->value;
1369 $val =~ s/\$\{$subvarname\}/$subval/g;
1370 $val =~ s/\$\($subvarname\)/$subval/g;
1371 unshift @to_process, split (' ', $val);
1373 next;
1375 # We do not know any variable with this name. Fall through
1376 # to filename processing.
1379 if ($fun_item) # $var is a filename we must process
1381 my $substnum=$#_substfroms;
1382 while ($substnum >= 0)
1384 $val =~ s/$_substfroms[$substnum]$/$_substtos[$substnum]/
1385 if defined $_substfroms[$substnum];
1386 $substnum -= 1;
1389 # Make sure you update the doc of
1390 # Automake::Variable::traverse_recursively
1391 # if you change the prototype of &fun_item.
1392 my @transformed = &$fun_item ($var, $val, $cond, $full_cond);
1393 push (@result, @transformed);
1396 push (@allresults, [$cond, @result]) if @result;
1399 # We only care about _recursive_ variable definitions. The user
1400 # is free to use the same variable several times in the same definition.
1401 $var->{'scanned'} = -1;
1403 # Make sure you update the doc of Automake::Variable::traverse_recursively
1404 # if you change the prototype of &fun_collect.
1405 return &$fun_collect ($var, $parent_cond, @allresults);
1408 # $VARNAME
1409 # _gen_varname ($BASE, @DEFINITIONS)
1410 # ---------------------------------
1411 # Return a variable name starting with $BASE, that will be
1412 # used to store definitions @DEFINITIONS.
1413 # @DEFINITIONS is a list of pair [$COND, @OBJECTS].
1415 # If we already have a $BASE-variable containing @DEFINITIONS, reuse it.
1416 # This way, we avoid combinatorial explosion of the generated
1417 # variables. Especially, in a Makefile such as:
1419 # | if FOO1
1420 # | A1=1
1421 # | endif
1423 # | if FOO2
1424 # | A2=2
1425 # | endif
1427 # | ...
1429 # | if FOON
1430 # | AN=N
1431 # | endif
1433 # | B=$(A1) $(A2) ... $(AN)
1435 # | c_SOURCES=$(B)
1436 # | d_SOURCES=$(B)
1438 # The generated c_OBJECTS and d_OBJECTS will share the same variable
1439 # definitions.
1441 # This setup can be the case of a testsuite containing lots (>100) of
1442 # small C programs, all testing the same set of source files.
1443 sub _gen_varname ($@)
1445 my $base = shift;
1446 my $key = '';
1447 foreach my $pair (@_)
1449 my ($cond, @values) = @$pair;
1450 $key .= "($cond)@values";
1453 return $_gen_varname{$base}{$key} if exists $_gen_varname{$base}{$key};
1455 my $num = 1 + keys (%{$_gen_varname{$base}});
1456 my $name = "${base}_${num}";
1457 $_gen_varname{$base}{$key} = $name;
1458 return $name;
1461 =item C<$resvar = transform_variable_recursively ($var, $resvar, $base, $nodefine, $where, &fun_item, [%options])>
1463 =item C<$resvar = $var-E<gt>transform_variable_recursively ($resvar, $base, $nodefine, $where, &fun_item, [%options])>
1465 Traverse C<$var> recursively, and create a C<$resvar> variable in
1466 which each filename in C<$var> have been transformed using
1467 C<&fun_item>. (C<$var> may be a variable name in the first syntax.
1468 It must be an C<Automake::Variable> otherwise.)
1470 Helper variables (corresponding to sub-variables of C<$var>) are
1471 created as needed, using C<$base> as prefix.
1473 Arguments are:
1474 $var source variable to traverse
1475 $resvar resulting variable to define
1476 $base prefix to use when naming subvariables of $resvar
1477 $nodefine if true, traverse $var but do not define any variable
1478 (this assumes &fun_item has some useful side-effect)
1479 $where context into which variable definitions are done
1480 &fun_item a transformation function -- see the documentation
1481 of &fun_item in Automake::Variable::traverse_recursively.
1483 This returns the string C<"\$($RESVAR)">.
1485 C<%options> is a list of options to pass to
1486 C<Variable::traverse_recursively> (see this method).
1488 =cut
1490 sub transform_variable_recursively ($$$$$&;%)
1492 my ($var, $resvar, $base, $nodefine, $where, $fun_item, %options) = @_;
1494 $var = ref $var ? $var : rvar $var;
1496 my $res = $var->traverse_recursively
1497 ($fun_item,
1498 # The code that define the variable holding the result
1499 # of the recursive transformation of a subvariable.
1500 sub {
1501 my ($subvar, $parent_cond, @allresults) = @_;
1502 # Find a name for the variable, unless this is the top-variable
1503 # for which we want to use $resvar.
1504 my $varname =
1505 ($var != $subvar) ? _gen_varname ($base, @allresults) : $resvar;
1506 # Define the variable if required.
1507 unless ($nodefine)
1509 # If the new variable is the source variable, we assume
1510 # we are trying to override a user variable. Delete
1511 # the old variable first.
1512 variable_delete ($varname) if $varname eq $var->name;
1513 # Define an empty variable in condition TRUE if there is no
1514 # result.
1515 @allresults = ([TRUE, '']) unless @allresults;
1516 # Define the rewritten variable in all conditions not
1517 # already covered by user definitions.
1518 foreach my $pair (@allresults)
1520 my ($cond, @result) = @$pair;
1521 my $var = var $varname;
1522 my @conds = ($var
1523 ? $var->not_always_defined_in_cond ($cond)->conds
1524 : $cond);
1526 foreach (@conds)
1528 define ($varname, VAR_AUTOMAKE, '', $_, "@result",
1529 '', $where, VAR_PRETTY);
1532 set_seen $varname;
1534 return "\$($varname)";
1536 %options);
1537 return $res;
1541 =back
1543 =head1 SEE ALSO
1545 L<Automake::VarDef>, L<Automake::Condition>,
1546 L<Automake::DisjConditions>, L<Automake::Location>.
1548 =cut
1552 ### Setup "GNU" style for perl-mode and cperl-mode.
1553 ## Local Variables:
1554 ## perl-indent-level: 2
1555 ## perl-continued-statement-offset: 2
1556 ## perl-continued-brace-offset: 0
1557 ## perl-brace-offset: 0
1558 ## perl-brace-imaginary-offset: 0
1559 ## perl-label-offset: -2
1560 ## cperl-indent-level: 2
1561 ## cperl-brace-offset: 0
1562 ## cperl-continued-brace-offset: 0
1563 ## cperl-label-offset: -2
1564 ## cperl-extra-newline-before-brace: t
1565 ## cperl-merge-trailing-else: nil
1566 ## cperl-continued-statement-offset: 2
1567 ## End: