1 # Copyright (C) 2003, 2004, 2005, 2006, 2008, 2009, 2010 Free Software
4 # This program is free software; you can redistribute it and/or modify
5 # it under the terms of the GNU General Public License as published by
6 # the Free Software Foundation; either version 2, or (at your option)
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
14 # You should have received a copy of the GNU General Public License
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
17 package Automake::Variable;
21 use Automake::Channels;
22 use Automake::ChannelDefs;
23 use Automake::Configure_ac;
26 use Automake::Condition qw (TRUE FALSE);
27 use Automake::DisjConditions;
28 use Automake::General 'uniq';
29 use Automake::Wrap 'makefile_wrap';
32 use vars '@ISA', '@EXPORT', '@EXPORT_OK';
33 @ISA = qw/Automake::Item Exporter/;
34 @EXPORT = qw (err_var msg_var msg_cond_var reject_var
35 var rvar vardef rvardef
37 scan_variable_expansions check_variable_expansions
44 transform_variable_recursively);
48 Automake::Variable - support for variable definitions
52 use Automake::Variable;
55 # Defining a variable.
56 Automake::Variable::define($varname, $owner, $type,
57 $cond, $value, $comment,
60 # Looking up a variable.
61 my $var = var $varname;
67 # Looking up a variable that is assumed to exist.
68 my $var = rvar $varname;
70 # The list of conditions where $var has been defined.
71 # ($var->conditions is an Automake::DisjConditions,
72 # $var->conditions->conds is a list of Automake::Condition.)
73 my @conds = $var->conditions->conds
75 # Access to the definition in Condition $cond.
76 # $def is an Automake::VarDef.
77 my $def = $var->def ($cond);
83 # When the conditional definition is assumed to exist, use
84 my $def = $var->rdef ($cond);
89 This package provides support for Makefile variable definitions.
91 An C<Automake::Variable> is a variable name associated to possibly
92 many conditional definitions. These definitions are instances
93 of C<Automake::VarDef>.
95 Therefore obtaining the value of a variable under a given
96 condition involves two lookups. One to look up the variable,
97 and one to look up the conditional definition:
102 my $def = $var->def ($cond);
111 When it is known that the variable and the definition
112 being looked up exist, the above can be simplified to
114 return var ($name)->def ($cond)->value; # Do not write this.
116 but is better written
118 return rvar ($name)->rdef ($cond)->value;
122 return rvardef ($name, $cond)->value;
124 The I<r> variants of the C<var>, C<def>, and C<vardef> methods add an
125 extra test to ensure that the lookup succeeded, and will diagnose
126 failures as internal errors (with a message which is much more
127 informative than Perl's warning about calling a method on a
132 my $_VARIABLE_CHARACTERS = '[.A-Za-z0-9_@]+';
133 my $_VARIABLE_PATTERN = '^' . $_VARIABLE_CHARACTERS . "\$";
134 my $_VARIABLE_RECURSIVE_PATTERN =
135 '^([.A-Za-z0-9_@]|\$[({]' . $_VARIABLE_CHARACTERS . '[})]?)+' . "\$";
137 # The order in which variables should be output. (May contain
138 # duplicates -- only the first occurrence matters.)
141 # This keeps track of all variables defined by &_gen_varname.
142 # $_gen_varname{$base} is a hash for all variables defined with
143 # prefix `$base'. Values stored in this hash are the variable names.
144 # Keys have the form "(COND1)VAL1(COND2)VAL2..." where VAL1 and VAL2
145 # are the values of the variable for condition COND1 and COND2.
146 my %_gen_varname = ();
147 # $_gen_varname_n{$base} is the number of variables generated by
148 # _gen_varname() for $base. This is not the same as keys
149 # %{$_gen_varname{$base}} because %_gen_varname may also contain
150 # variables not generated by _gen_varname.
151 my %_gen_varname_n = ();
153 # Declare the macros that define known variables, so we can
154 # hint the user if she try to use one of these variables.
156 # Macros accessible via aclocal.
157 my %_am_macro_for_var =
159 ANSI2KNR => 'AM_C_PROTOTYPES',
160 CCAS => 'AM_PROG_AS',
161 CCASFLAGS => 'AM_PROG_AS',
162 EMACS => 'AM_PATH_LISPDIR',
163 GCJ => 'AM_PROG_GCJ',
164 LEX => 'AM_PROG_LEX',
165 LIBTOOL => 'AC_PROG_LIBTOOL',
166 lispdir => 'AM_PATH_LISPDIR',
167 pkgpyexecdir => 'AM_PATH_PYTHON',
168 pkgpythondir => 'AM_PATH_PYTHON',
169 pyexecdir => 'AM_PATH_PYTHON',
170 PYTHON => 'AM_PATH_PYTHON',
171 pythondir => 'AM_PATH_PYTHON',
172 U => 'AM_C_PROTOTYPES',
175 # Macros shipped with Autoconf.
176 my %_ac_macro_for_var =
178 ALLOCA => 'AC_FUNC_ALLOCA',
180 CFLAGS => 'AC_PROG_CC',
181 CXX => 'AC_PROG_CXX',
182 CXXFLAGS => 'AC_PROG_CXX',
183 F77 => 'AC_PROG_F77',
184 F77FLAGS => 'AC_PROG_F77',
186 FCFLAGS => 'AC_PROG_FC',
187 OBJC => 'AC_PROG_OBJC',
188 OBJCFLAGS => 'AC_PROG_OBJC',
189 RANLIB => 'AC_PROG_RANLIB',
190 UPC => 'AM_PROG_UPC',
191 UPCFLAGS => 'AM_PROG_UPC',
192 YACC => 'AC_PROG_YACC',
195 # The name of the configure.ac file.
198 # Variables that can be overridden without complaint from -Woverride
199 my %_silent_variable_override =
200 (AM_MAKEINFOHTMLFLAGS => 1,
207 # Count of helper variables used to implement conditional '+='.
210 # Each call to C<Automake::Variable::traverse_recursively> gets an
211 # unique label. This is used to detect recursively defined variables.
215 =head2 Error reporting functions
217 In these functions, C<$var> can be either a variable name, or
218 an instance of C<Automake::Variable>.
222 =item C<err_var ($var, $message, [%options])>
224 Uncategorized errors about variables.
230 msg_var ('error', @_);
233 =item C<msg_cond_var ($channel, $cond, $var, $message, [%options])>
235 Messages about conditional variable.
239 sub msg_cond_var ($$$$;%)
241 my ($channel, $cond, $var, $msg, %opts) = @_;
242 my $v = ref ($var) ? $var : rvar ($var);
243 msg $channel, $v->rdef ($cond)->location, $msg, %opts;
246 =item C<msg_var ($channel, $var, $message, [%options])>
248 Messages about variables.
254 my ($channel, $var, $msg, %opts) = @_;
255 my $v = ref ($var) ? $var : rvar ($var);
256 # Don't know which condition is concerned. Pick any.
257 my $cond = $v->conditions->one_cond;
258 msg_cond_var $channel, $cond, $v, $msg, %opts;
261 =item C<$bool = reject_var ($varname, $error_msg)>
263 Bail out with C<$error_msg> if a variable with name C<$varname> has
266 Return true iff C<$varname> is defined.
272 my ($var, $msg) = @_;
284 =head2 Administrative functions
288 =item C<Automake::Variable::hook ($varname, $fun)>
290 Declare a function to be called whenever a variable
291 named C<$varname> is defined or redefined.
293 C<$fun> should take two arguments: C<$type> and C<$value>.
294 When type is C<''> or <':'>, C<$value> is the value being
295 assigned to C<$varname>. When C<$type> is C<'+'>, C<$value>
296 is the value being appended to C<$varname>.
303 my ($var, $fun) = @_;
304 $_hooks{$var} = $fun;
307 =item C<variables ([$suffix])>
309 Returns the list of all L<Automake::Variable> instances. (I.e., all
310 variables defined so far.) If C<$suffix> is supplied, return only
311 the L<Automake::Variable> instances that ends with C<_$suffix>.
315 use vars '%_variable_dict', '%_primary_dict';
321 if (exists $_primary_dict{$suffix})
323 return values %{$_primary_dict{$suffix}};
332 return values %_variable_dict;
336 =item C<Automake::Variable::reset>
338 The I<forget all> function. Clears all know variables and reset some
345 %_variable_dict = ();
350 %_gen_varname_n = ();
354 =item C<var ($varname)>
356 Return the C<Automake::Variable> object for the variable
357 named C<$varname> if defined. Return 0 otherwise.
364 return $_variable_dict{$name} if exists $_variable_dict{$name};
368 =item C<vardef ($varname, $cond)>
370 Return the C<Automake::VarDef> object for the variable named
371 C<$varname> if defined in condition C<$cond>. Return false
372 if the condition or the variable does not exist.
378 my ($name, $cond) = @_;
380 return $var && $var->def ($cond);
383 # Create the variable if it does not exist.
384 # This is used only by other functions in this package.
390 return _new Automake::Variable $name;
393 =item C<rvar ($varname)>
395 Return the C<Automake::Variable> object for the variable named
396 C<$varname>. Abort with an internal error if the variable was not
399 The I<r> in front of C<var> stands for I<required>. One
400 should call C<rvar> to assert the variable's existence.
408 prog_error ("undefined variable $name\n" . &variables_dump)
413 =item C<rvardef ($varname, $cond)>
415 Return the C<Automake::VarDef> object for the variable named
416 C<$varname> if defined in condition C<$cond>. Abort with an internal
417 error if the condition or the variable does not exist.
423 my ($name, $cond) = @_;
424 return rvar ($name)->rdef ($cond);
431 C<Automake::Variable> is a subclass of C<Automake::Item>. See
432 that package for inherited methods.
434 Here are the methods specific to the C<Automake::Variable> instances.
435 Use the C<define> function, described latter, to create such objects.
441 # Create Automake::Variable objects. This is used
442 # only in this file. Other users should use
443 # the "define" function.
446 my ($class, $name) = @_;
447 my $self = Automake::Item::new ($class, $name);
448 $self->{'scanned'} = 0;
449 $self->{'last-append'} = []; # helper variable for last conditional append.
450 $_variable_dict{$name} = $self;
451 if ($name =~ /_([[:alnum:]]+)$/)
453 $_primary_dict{$1}{$name} = $self;
458 # _check_ambiguous_condition ($SELF, $COND, $WHERE)
459 # -------------------------------------------------
460 # Check for an ambiguous conditional. This is called when a variable
461 # is being defined conditionally. If we already know about a
462 # definition that is true under the same conditions, then we have an
464 sub _check_ambiguous_condition ($$$)
466 my ($self, $cond, $where) = @_;
467 my $var = $self->name;
468 my ($message, $ambig_cond) = $self->conditions->ambiguous_p ($var, $cond);
470 # We allow silent variables to be overridden silently,
471 # by either silent or non-silent variables.
472 my $def = $self->def ($ambig_cond);
473 if ($message && $def->pretty != VAR_SILENT)
475 msg 'syntax', $where, "$message ...", partial => 1;
476 msg_var ('syntax', $var, "... `$var' previously defined here");
481 =item C<$bool = $var-E<gt>check_defined_unconditionally ([$parent, $parent_cond])>
483 Warn if the variable is conditionally defined. C<$parent> is the name
484 of the parent variable, and C<$parent_cond> the condition of the parent
485 definition. These two variables are used to display diagnostics.
489 sub check_defined_unconditionally ($;$$)
491 my ($self, $parent, $parent_cond) = @_;
493 if (!$self->conditions->true)
497 msg_cond_var ('unsupported', $parent_cond, $parent,
498 "automake does not support conditional definition of "
499 . $self->name . " in $parent");
503 msg_var ('unsupported', $self,
504 "automake does not support " . $self->name
505 . " being defined conditionally");
510 =item C<$str = $var-E<gt>output ([@conds])>
512 Format all the definitions of C<$var> if C<@cond> is not specified,
513 else only that corresponding to C<@cond>.
519 my ($self, @conds) = @_;
521 @conds = $self->conditions->conds
525 my $name = $self->name;
527 foreach my $cond (@conds)
529 my $def = $self->def ($cond);
530 prog_error ("unknown condition `" . $cond->human . "' for `"
535 if $def->pretty == VAR_SILENT;
537 $res .= $def->comment;
539 my $val = $def->raw_value;
540 my $equals = $def->type eq ':' ? ':=' : '=';
541 my $str = $cond->subst_string;
544 if ($def->pretty == VAR_ASIS)
546 my $output_var = "$name $equals $val";
547 $output_var =~ s/^/$str/meg;
548 $res .= "$output_var\n";
550 elsif ($def->pretty == VAR_PRETTY)
552 # Suppress escaped new lines. &makefile_wrap will
553 # add them back, maybe at other places.
555 my $wrap = makefile_wrap ("$str$name $equals", "$str\t",
558 # If the last line of the definition is made only of
559 # @substitutions@, append an empty variable to make sure it
560 # cannot be substituted as a blank line (that would confuse
562 $wrap = makefile_wrap ("$str$name $equals", "$str\t",
563 split (' ', $val), '$(am__empty)')
564 if $wrap =~ /\n(\s*@\w+@)+\s*$/;
568 else # ($def->pretty == VAR_SORTED)
570 # Suppress escaped new lines. &makefile_wrap will
571 # add them back, maybe at other places.
573 $res .= makefile_wrap ("$str$name $equals", "$str\t",
574 sort (split (' ' , $val)));
580 =item C<@values = $var-E<gt>value_as_list ($cond, [$parent, $parent_cond])>
582 Get the value of C<$var> as a list, given a specified condition,
583 without recursing through any subvariables.
585 C<$cond> is the condition of interest. C<$var> does not need
586 to be defined for condition C<$cond> exactly, but it needs
587 to be defined for at most one condition implied by C<$cond>.
589 C<$parent> and C<$parent_cond> designate the name and the condition
590 of the parent variable, i.e., the variable in which C<$var> is
591 being expanded. These are used in diagnostics.
593 For example, if C<A> is defined as "C<foo $(B) bar>" in condition
594 C<TRUE>, calling C<rvar ('A')->value_as_list (TRUE)> will return
595 C<("foo", "$(B)", "bar")>.
599 sub value_as_list ($$;$$)
601 my ($self, $cond, $parent, $parent_cond) = @_;
604 # Get value for given condition
606 foreach my $vcond ($self->conditions->conds)
608 if ($vcond->true_when ($cond))
610 # If there is more than one definitions of $var matching
611 # $cond then we are in trouble: tell the user we need a
612 # paddle. Continue by merging results from all conditions,
613 # although it doesn't make much sense.
614 $self->check_defined_unconditionally ($parent, $parent_cond)
618 my $val = $self->rdef ($vcond)->value;
619 push @result, split (' ', $val);
625 =item C<@values = $var-E<gt>value_as_list_recursive ([%options])>
627 Return the contents of C<$var> as a list, split on whitespace. This
628 will recursively follow C<$(...)> and C<${...}> inclusions. It
629 preserves C<@...@> substitutions.
631 C<%options> is a list of option for C<Variable::traverse_recursively>
632 (see this method). The most useful is C<cond_filter>:
634 $var->value_as_list_recursive (cond_filter => $cond)
636 will return the contents of C<$var> and any subvariable in all
637 conditions implied by C<$cond>.
639 C<%options> can also carry options specific to C<value_as_list_recursive>.
640 Presently, the only such option is C<location =E<gt> 1> which instructs
641 C<value_as_list_recursive> to return a list of C<[$location, @values]> pairs.
645 sub value_as_list_recursive ($;%)
647 my ($var, %options) = @_;
649 return $var->traverse_recursively
650 (# Construct [$location, $value] pairs if requested.
652 my ($var, $val, $cond, $full_cond) = @_;
653 return [$var->rdef ($cond)->location, $val] if $options{'location'};
658 my ($var, $parent_cond, @allresults) = @_;
659 return map { my ($cond, @vals) = @$_; @vals } @allresults;
665 =item C<$bool = $var-E<gt>has_conditional_contents>
667 Return 1 if C<$var> or one of its subvariable was conditionally
668 defined. Return 0 otherwise.
672 sub has_conditional_contents ($)
676 # Traverse the variable recursively until we
677 # find a variable defined conditionally.
678 # Use `die' to abort the traversal, and pass it `$full_cond'
679 # to we can find easily whether the `eval' block aborted
680 # because we found a condition, or for some other error.
683 $self->traverse_recursively
686 my ($subvar, $val, $cond, $full_cond) = @_;
687 die $full_cond if ! $full_cond->true;
694 return 1 if ref ($@) && $@->isa ("Automake::Condition");
695 # Propagate other errors.
702 =item C<$string = $var-E<gt>dump>
704 Return a string describing all we know about C<$var>.
713 my $text = $self->name . ": \n {\n";
714 foreach my $vcond ($self->conditions->conds)
716 $text .= " " . $vcond->human . " => " . $self->rdef ($vcond)->dump;
725 =head2 Utility functions
729 =item C<@list = scan_variable_expansions ($text)>
731 Return the list of variable names expanded in C<$text>. Note that
732 unlike some other functions, C<$text> is not split on spaces before we
733 check for subvariables.
737 sub scan_variable_expansions ($)
745 # Record each use of ${stuff} or $(stuff) that does not follow a $.
746 while ($text =~ /(?<!\$)\$(?:\{([^\}]*)\}|\(([^\)]*)\))/g)
749 # The occurrence may look like $(string1[:subst1=[subst2]]) but
750 # we want only `string1'.
751 $var =~ s/:[^:=]*=[^=]*$//;
758 =item C<check_variable_expansions ($text, $where)>
760 Check variable expansions in C<$text> and warn about any name that
761 does not conform to POSIX. C<$where> is the location of C<$text>
762 for the error message.
766 sub check_variable_expansions ($$)
768 my ($text, $where) = @_;
769 # Catch expansion of variables whose name does not conform to POSIX.
770 foreach my $var (scan_variable_expansions ($text))
772 if ($var !~ /$_VARIABLE_PATTERN/o)
774 # If the variable name contains a space, it's likely
775 # to be a GNU make extension (such as $(addsuffix ...)).
776 # Mention this in the diagnostic.
778 $gnuext = "\n(probably a GNU make extension)" if $var =~ / /;
779 # Accept recursive variable expansions if so desired
780 # (we hope they are rather portable in practice).
781 if ($var =~ /$_VARIABLE_RECURSIVE_PATTERN/o)
783 msg ('portability-recursive', $where,
784 "$var: non-POSIX recursive variable expansion$gnuext");
788 msg ('portability', $where, "$var: non-POSIX variable name$gnuext");
796 =item C<Automake::Variable::define($varname, $owner, $type, $cond, $value, $comment, $where, $pretty)>
798 Define or append to a new variable.
800 C<$varname>: the name of the variable being defined.
802 C<$owner>: owner of the variable (one of C<VAR_MAKEFILE>,
803 C<VAR_CONFIGURE>, or C<VAR_AUTOMAKE>, defined by L<Automake::VarDef>).
804 Variables can be overridden, provided the new owner is not weaker
805 (C<VAR_AUTOMAKE> < C<VAR_CONFIGURE> < C<VAR_MAKEFILE>).
807 C<$type>: the type of the assignment (C<''> for C<FOO = bar>,
808 C<':'> for C<FOO := bar>, and C<'+'> for C<'FOO += bar'>).
810 C<$cond>: the C<Condition> in which C<$var> is being defined.
812 C<$value>: the value assigned to C<$var> in condition C<$cond>.
814 C<$comment>: any comment (C<'# bla.'>) associated with the assignment.
815 Comments from C<+=> assignments stack with comments from the last C<=>
818 C<$where>: the C<Location> of the assignment.
820 C<$pretty>: whether C<$value> should be pretty printed (one of
821 C<VAR_ASIS>, C<VAR_PRETTY>, C<VAR_SILENT>, or C<VAR_SORTED>, defined
822 by by L<Automake::VarDef>). C<$pretty> applies only to real
823 assignments. I.e., it does not apply to a C<+=> assignment (except
824 when part of it is being done as a conditional C<=> assignment).
826 This function will all run any hook registered with the C<hook>
831 sub define ($$$$$$$$)
833 my ($var, $owner, $type, $cond, $value, $comment, $where, $pretty) = @_;
835 prog_error "$cond is not a reference"
838 prog_error "$where is not a reference"
841 prog_error "pretty argument missing"
842 unless defined $pretty && ($pretty == VAR_ASIS
843 || $pretty == VAR_PRETTY
844 || $pretty == VAR_SILENT
845 || $pretty == VAR_SORTED);
847 error $where, "bad characters in variable name `$var'"
848 if $var !~ /$_VARIABLE_PATTERN/o;
850 # `:='-style assignments are not acknowledged by POSIX. Moreover it
851 # has multiple meanings. In GNU make or BSD make it means "assign
852 # with immediate expansion", while in OSF make it is used for
853 # conditional assignments.
854 msg ('portability', $where, "`:='-style assignments are not portable")
857 check_variable_expansions ($value, $where);
859 # If there's a comment, make sure it is \n-terminated.
870 my $self = _cvar $var;
872 my $def = $self->def ($cond);
873 my $new_var = $def ? 0 : 1;
875 # Additional checks for Automake definitions.
876 if ($owner == VAR_AUTOMAKE && ! $new_var)
878 # An Automake variable must be consistently defined with the same
880 if ($def->type ne $type && $def->owner == VAR_AUTOMAKE)
882 error ($def->location,
883 "Automake variable `$var' was set with `"
884 . $def->type . "=' here ...", partial => 1);
885 error ($where, "... and is now set with `$type=' here.");
886 prog_error ("Automake variable assignments should be consistently\n"
887 . "defined with the same sign");
890 # If Automake tries to override a value specified by the user,
891 # just don't let it do.
892 if ($def->owner != VAR_AUTOMAKE)
894 if (! exists $_silent_variable_override{$var})
896 my $condmsg = ($cond == TRUE
897 ? '' : (" in condition `" . $cond->human . "'"));
898 msg_cond_var ('override', $cond, $var,
899 "user variable `$var' defined here$condmsg ...",
901 msg ('override', $where,
902 "... overrides Automake variable `$var' defined here");
904 verb ("refusing to override the user definition of:\n"
905 . $self->dump ."with `" . $cond->human . "' => `$value'");
910 # Differentiate assignment types.
912 # 1. append (+=) to a variable defined for current condition
913 if ($type eq '+' && ! $new_var)
915 $def->append ($value, $comment);
916 $self->{'last-append'} = [];
918 # Only increase owners. A VAR_CONFIGURE variable augmented in a
919 # Makefile.am becomes a VAR_MAKEFILE variable.
920 $def->set_owner ($owner, $where->clone)
921 if $owner > $def->owner;
923 # 2. append (+=) to a variable defined for *another* condition
924 elsif ($type eq '+' && ! $self->conditions->false)
926 # * Generally, $cond is not TRUE. For instance:
931 # In this case, we declare an helper variable conditionally,
932 # and append it to FOO:
933 # FOO = foo $(am__append_1)
934 # @COND_TRUE@am__append_1 = bar
935 # Of course if FOO is defined under several conditions, we add
936 # $(am__append_1) to each definitions.
938 # * If $cond is TRUE, we don't need the helper variable. E.g., in
945 # we can add bar directly to all definition of FOO, and output
946 # @COND_TRUE@FOO = foo1 bar
947 # @COND_FALSE@FOO = foo2 bar
950 # Do we need an helper variable?
953 # Can we reuse the helper variable created for the previous
954 # append? (We cannot reuse older helper variables because
955 # we must preserve the order of items appended to the
957 my $condstr = $cond->string;
958 my $key = "$var:$condstr";
959 my ($appendvar, $appendvarcond) = @{$self->{'last-append'}};
960 if ($appendvar && $condstr eq $appendvarcond)
962 # Yes, let's simply append to it.
964 $owner = VAR_AUTOMAKE;
966 $def = $self->rdef ($cond);
972 my $num = ++$_appendvar;
973 my $hvar = "am__append_$num";
974 $lastappend = [$hvar, $condstr];
975 &define ($hvar, VAR_AUTOMAKE, '+',
976 $cond, $value, $comment, $where, $pretty);
978 # Now HVAR is to be added to VAR.
980 $value = "\$($hvar)";
984 # Add VALUE to all definitions of SELF.
985 foreach my $vcond ($self->conditions->conds)
987 # We have a bit of error detection to do here.
993 # should be rejected because X is not defined for all conditions
994 # where `+=' applies.
995 my $undef_cond = $self->not_always_defined_in_cond ($cond);
996 if (! $undef_cond->false)
999 "cannot apply `+=' because `$var' is not defined "
1000 . "in\nthe following conditions:\n "
1001 . join ("\n ", map { $_->human } $undef_cond->conds)
1002 . "\neither define `$var' in these conditions,"
1003 . " or use\n`+=' in the same conditions as"
1004 . " the definitions.");
1008 &define ($var, $owner, '+', $vcond, $value, $comment,
1012 $self->{'last-append'} = $lastappend;
1014 # 3. first assignment (=, :=, or +=)
1017 # There must be no previous value unless the user is redefining
1018 # an Automake variable or an AC_SUBST variable for an existing
1020 _check_ambiguous_condition ($self, $cond, $where)
1022 && (($def->owner == VAR_AUTOMAKE && $owner != VAR_AUTOMAKE)
1023 || $def->owner == VAR_CONFIGURE));
1025 # Never decrease an owner.
1026 $owner = $def->owner
1027 if ! $new_var && $owner < $def->owner;
1029 # Assignments to a macro set its location. We don't adjust
1030 # locations for `+='. Ideally I suppose we would associate
1031 # line numbers with random bits of text.
1032 $def = new Automake::VarDef ($var, $value, $comment, $where->clone,
1033 $type, $owner, $pretty);
1034 $self->set ($cond, $def);
1035 push @_var_order, $var;
1038 # Call any defined hook. This helps to update some internal state
1039 # *while* parsing the file. For instance the handling of SUFFIXES
1040 # requires this (see var_SUFFIXES_trigger).
1041 &{$_hooks{$var}}($type, $value) if exists $_hooks{$var};
1044 =item C<variable_delete ($varname, [@conds])>
1046 Forget about C<$varname> under the conditions C<@conds>, or completely
1047 if C<@conds> is empty.
1051 sub variable_delete ($@)
1053 my ($var, @conds) = @_;
1057 delete $_variable_dict{$var};
1061 for my $cond (@conds)
1063 delete $_variable_dict{$var}{'defs'}{$cond};
1066 if ($var =~ /_([[:alnum:]]+)$/)
1068 delete $_primary_dict{$1}{$var};
1072 =item C<$str = variables_dump>
1074 Return a string describing all we know about all variables.
1079 sub variables_dump ()
1081 my $text = "all variables:\n{\n";
1082 foreach my $var (sort { $a->name cmp $b->name } variables)
1084 $text .= $var->dump;
1091 =item C<$var = set_seen ($varname)>
1093 =item C<$var = $var-E<gt>set_seen>
1095 Mark all definitions of this variable as examined, if the variable
1096 exists. See L<Automake::VarDef::set_seen>.
1098 Return the C<Variable> object if the variable exists, or 0
1099 otherwise (i.e., as the C<var> function).
1106 $self = ref $self ? $self : var $self;
1108 return 0 unless $self;
1110 for my $c ($self->conditions->conds)
1112 $self->rdef ($c)->set_seen;
1119 =item C<$count = require_variables ($where, $reason, $cond, @variables)>
1121 Make sure that each supplied variable is defined in C<$cond>.
1122 Otherwise, issue a warning showing C<$reason> (C<$reason> should be
1123 the reason why these variables are required, for instance C<'option foo
1124 used'>). If we know which macro can define this variable, hint the
1125 user. Return the number of undefined variables.
1129 sub require_variables ($$$@)
1131 my ($where, $reason, $cond, @vars) = @_;
1133 $reason .= ' but ' unless $reason eq '';
1135 $configure_ac = find_configure_ac
1136 unless defined $configure_ac;
1139 foreach my $var (@vars)
1141 # Nothing to do if the variable exists.
1143 if vardef ($var, $cond);
1145 my $text = "$reason`$var' is undefined\n";
1149 my $undef_cond = $v->not_always_defined_in_cond ($cond);
1151 if $undef_cond->false;
1152 $text .= ("in the following conditions:\n "
1153 . join ("\n ", map { $_->human } $undef_cond->conds)
1159 if (exists $_am_macro_for_var{$var})
1161 my $mac = $_am_macro_for_var{$var};
1162 $text .= " The usual way to define `$var' is to add "
1163 . "`$mac'\n to `$configure_ac' and run `aclocal' and "
1164 . "`autoconf' again.";
1165 # aclocal will not warn about undefined macros unless it
1167 $text .= "\n If `$mac' is in `$configure_ac', make sure\n"
1168 . " its definition is in aclocal's search path."
1169 unless $mac =~ /^AM_/;
1171 elsif (exists $_ac_macro_for_var{$var})
1173 $text .= " The usual way to define `$var' is to add "
1174 . "`$_ac_macro_for_var{$var}'\n to `$configure_ac' and "
1175 . "run `autoconf' again.";
1178 error $where, $text, uniq_scope => US_GLOBAL;
1183 =item C<$count = $var->requires_variables ($reason, @variables)>
1185 Same as C<require_variables>, but a method of Automake::Variable.
1186 C<@variables> should be defined in the same conditions as C<$var> is
1191 sub requires_variables ($$@)
1193 my ($var, $reason, @args) = @_;
1195 for my $cond ($var->conditions->conds)
1197 $res += require_variables ($var->rdef ($cond)->location, $reason,
1204 =item C<variable_value ($var)>
1206 Get the C<TRUE> value of a variable, warn if the variable is
1207 conditionally defined. C<$var> can be either a variable name
1208 or a C<Automake::Variable> instance (this allows calls such
1209 as C<$var-E<gt>variable_value>).
1213 sub variable_value ($)
1216 my $v = ref ($var) ? $var : var ($var);
1217 return () unless $v;
1218 $v->check_defined_unconditionally;
1219 my $d = $v->def (TRUE);
1220 return $d ? $d->value : "";
1223 =item C<$str = output_variables>
1225 Format definitions for all variables.
1229 sub output_variables ()
1232 # We output variables it in the same order in which they were
1233 # defined (skipping duplicates).
1234 my @vars = uniq @_var_order;
1236 # Output all the Automake variables. If the user changed one,
1237 # then it is now marked as VAR_CONFIGURE or VAR_MAKEFILE.
1238 foreach my $var (@vars)
1241 foreach my $cond ($v->conditions->conds)
1243 $res .= $v->output ($cond)
1244 if $v->rdef ($cond)->owner == VAR_AUTOMAKE;
1248 # Now dump the user variables that were defined.
1249 foreach my $var (@vars)
1252 foreach my $cond ($v->conditions->conds)
1254 $res .= $v->output ($cond)
1255 if $v->rdef ($cond)->owner != VAR_AUTOMAKE;
1261 =item C<$var-E<gt>traverse_recursively (&fun_item, &fun_collect, [cond_filter =E<gt> $cond_filter], [inner_expand =E<gt> 1], [skip_ac_subst =E<gt> 1])>
1263 Split the value of the Automake::Variable C<$var> on space, and
1264 traverse its components recursively.
1266 If C<$cond_filter> is an C<Automake::Condition>, process any
1267 conditions which are true when C<$cond_filter> is true. Otherwise,
1268 process all conditions.
1270 We distinguish two kinds of items in the content of C<$var>.
1271 Terms that look like C<$(foo)> or C<${foo}> are subvariables
1272 and cause recursion. Other terms are assumed to be filenames.
1274 Each time a filename is encountered, C<&fun_item> is called with the
1275 following arguments:
1277 ($var, -- the Automake::Variable we are currently
1279 $val, -- the item (i.e., filename) to process
1280 $cond, -- the Condition for the $var definition we are
1281 examining (ignoring the recursion context)
1282 $full_cond) -- the full Condition, taking into account
1283 conditions inherited from parent variables
1286 If C<inner_expand> is set, variable references occurring in filename
1287 (as in C<$(BASE).ext>) are expanded before the filename is passed to
1290 If C<skip_ac_subst> is set, Autoconf @substitutions@ will be skipped,
1291 i.e., C<&fun_item> will never be called for them.
1293 C<&fun_item> may return a list of items, they will be passed to
1294 C<&fun_store> later on. Define C<&fun_item> or @<&fun_store> as
1295 C<undef> when they serve no purpose.
1297 Once all items of a variable have been processed, the result (of the
1298 calls to C<&fun_items>, or of recursive traversals of subvariables)
1299 are passed to C<&fun_collect>. C<&fun_collect> receives three
1302 ($var, -- the variable being traversed
1303 $parent_cond, -- the Condition inherited from parent
1304 variables during recursion
1305 @condlist) -- a list of [$cond, @results] pairs
1306 where each $cond appear only once, and @result
1307 are all the results for this condition.
1309 Typically you should do C<$cond->merge ($parent_cond)> to recompute
1310 the C<$full_cond> associated to C<@result>. C<&fun_collect> may
1311 return a list of items, that will be used as the result of
1312 C<Automake::Variable::traverse_recursively> (the top-level, or its
1317 # Contains a stack of `from' and `to' parts of variable
1318 # substitutions currently in force.
1321 sub traverse_recursively ($&&;%)
1326 my ($var, $fun_item, $fun_collect, %options) = @_;
1327 my $cond_filter = $options{'cond_filter'};
1328 my $inner_expand = $options{'inner_expand'};
1329 my $skip_ac_subst = $options{'skip_ac_subst'};
1330 return $var->_do_recursive_traversal ($var,
1331 $fun_item, $fun_collect,
1332 $cond_filter, TRUE, $inner_expand,
1336 # The guts of Automake::Variable::traverse_recursively.
1337 sub _do_recursive_traversal ($$&&$$$$)
1339 my ($var, $parent, $fun_item, $fun_collect, $cond_filter, $parent_cond,
1340 $inner_expand, $skip_ac_subst) = @_;
1344 if ($var->{'scanned'} == $_traversal)
1346 err_var $var, "variable `" . $var->name() . "' recursively defined";
1349 $var->{'scanned'} = $_traversal;
1351 my @allresults = ();
1353 foreach my $cond ($var->conditions->conds)
1355 if (ref $cond_filter)
1357 # Ignore conditions that don't match $cond_filter.
1358 next if ! $cond->true_when ($cond_filter);
1359 # If we found out several definitions of $var
1360 # match $cond_filter then we are in trouble.
1361 # Tell the user we don't support this.
1362 $var->check_defined_unconditionally ($parent, $parent_cond)
1367 my $full_cond = $cond->merge ($parent_cond);
1369 my @to_process = $var->value_as_list ($cond, $parent, $parent_cond);
1372 my $val = shift @to_process;
1373 # If $val is a variable (i.e. ${foo} or $(bar), not a filename),
1374 # handle the sub variable recursively.
1375 # (Backslashes before `}' and `)' within brackets are here to
1376 # please Emacs's indentation.)
1377 if ($val =~ /^\$\{([^\}]*)\}$/ || $val =~ /^\$\(([^\)]*)\)$/)
1379 my $subvarname = $1;
1381 # If the user uses a losing variable name, just ignore it.
1382 # This isn't ideal, but people have requested it.
1383 next if ($subvarname =~ /\@.*\@/);
1385 # See if the variable is actually a substitution reference
1387 # This handles substitution references like ${foo:.a=.b}.
1388 if ($subvarname =~ /^([^:]*):([^=]*)=(.*)$/o)
1392 $from = quotemeta $2;
1395 my $subvar = var ($subvarname);
1396 # Don't recurse into undefined variables.
1397 next unless $subvar;
1399 push @_substfroms, $from;
1400 push @_substtos, $to;
1402 my @res = $subvar->_do_recursive_traversal ($parent,
1409 push (@result, @res);
1416 # Try to expand variable references inside filenames such as
1417 # `$(NAME).txt'. We do not handle `:.foo=.bar'
1418 # substitutions, but it would make little sense to use this
1420 elsif ($inner_expand
1421 && ($val =~ /\$\{([^\}]*)\}/ || $val =~ /\$\(([^\)]*)\)/))
1423 my $subvarname = $1;
1424 my $subvar = var $subvarname;
1427 # Replace the reference by its value, and reschedule
1429 foreach my $c ($subvar->conditions->conds)
1431 if (ref $cond_filter)
1433 # Ignore conditions that don't match $cond_filter.
1434 next if ! $c->true_when ($cond_filter);
1435 # If we found out several definitions of $var
1436 # match $cond_filter then we are in trouble.
1437 # Tell the user we don't support this.
1438 $subvar->check_defined_unconditionally ($var,
1443 my $subval = $subvar->rdef ($c)->value;
1444 $val =~ s/\$\{$subvarname\}/$subval/g;
1445 $val =~ s/\$\($subvarname\)/$subval/g;
1446 unshift @to_process, split (' ', $val);
1450 # We do not know any variable with this name. Fall through
1451 # to filename processing.
1453 elsif ($skip_ac_subst && $val =~ /^\@.+\@$/)
1458 if ($fun_item) # $var is a filename we must process
1460 my $substnum=$#_substfroms;
1461 while ($substnum >= 0)
1463 $val =~ s/$_substfroms[$substnum]$/$_substtos[$substnum]/
1464 if defined $_substfroms[$substnum];
1468 # Make sure you update the doc of
1469 # Automake::Variable::traverse_recursively
1470 # if you change the prototype of &fun_item.
1471 my @transformed = &$fun_item ($var, $val, $cond, $full_cond);
1472 push (@result, @transformed);
1475 push (@allresults, [$cond, @result]) if @result;
1478 # We only care about _recursive_ variable definitions. The user
1479 # is free to use the same variable several times in the same definition.
1480 $var->{'scanned'} = -1;
1483 unless $fun_collect;
1484 # Make sure you update the doc of Automake::Variable::traverse_recursively
1485 # if you change the prototype of &fun_collect.
1486 return &$fun_collect ($var, $parent_cond, @allresults);
1489 # _hash_varname ($VAR)
1490 # --------------------
1491 # Compute the key associated $VAR in %_gen_varname.
1492 # See _gen_varname() below.
1493 sub _hash_varname ($)
1497 foreach my $cond ($var->conditions->conds)
1499 my @values = $var->value_as_list ($cond);
1500 $key .= "($cond)@values";
1505 # _hash_values (@VALUES)
1506 # ----------------------
1507 # Hash @VALUES for %_gen_varname. @VALUES should be a list
1508 # of pairs: ([$cond, @values], [$cond, @values], ...).
1509 # See _gen_varname() below.
1510 sub _hash_values (@)
1513 foreach my $pair (@_)
1515 my ($cond, @values) = @$pair;
1516 $key .= "($cond)@values";
1520 # ($VARNAME, $GENERATED)
1521 # _gen_varname ($BASE, @DEFINITIONS)
1522 # ----------------------------------
1523 # Return a variable name starting with $BASE, that will be
1524 # used to store definitions @DEFINITIONS.
1525 # @DEFINITIONS is a list of pair [$COND, @OBJECTS].
1527 # If we already have a $BASE-variable containing @DEFINITIONS, reuse
1528 # it and set $GENERATED to 0. Otherwise construct a new name and set
1531 # This way, we avoid combinatorial explosion of the generated
1532 # variables. Especially, in a Makefile such as:
1548 # | B=$(A1) $(A2) ... $(AN)
1553 # The generated c_OBJECTS and d_OBJECTS will share the same variable
1556 # This setup can be the case of a testsuite containing lots (>100) of
1557 # small C programs, all testing the same set of source files.
1558 sub _gen_varname ($@)
1561 my $key = _hash_values @_;
1563 return ($_gen_varname{$base}{$key}, 0)
1564 if exists $_gen_varname{$base}{$key};
1566 my $num = 1 + ($_gen_varname_n{$base} || 0);
1567 $_gen_varname_n{$base} = $num;
1568 my $name = "${base}_${num}";
1569 $_gen_varname{$base}{$key} = $name;
1574 =item C<$resvar = transform_variable_recursively ($var, $resvar, $base, $nodefine, $where, &fun_item, [%options])>
1576 =item C<$resvar = $var-E<gt>transform_variable_recursively ($resvar, $base, $nodefine, $where, &fun_item, [%options])>
1578 Traverse C<$var> recursively, and create a C<$resvar> variable in
1579 which each filename in C<$var> have been transformed using
1580 C<&fun_item>. (C<$var> may be a variable name in the first syntax.
1581 It must be an C<Automake::Variable> otherwise.)
1583 Helper variables (corresponding to sub-variables of C<$var>) are
1584 created as needed, using C<$base> as prefix.
1587 $var source variable to traverse
1588 $resvar resulting variable to define
1589 $base prefix to use when naming subvariables of $resvar
1590 $nodefine if true, traverse $var but do not define any variable
1591 (this assumes &fun_item has some useful side-effect)
1592 $where context into which variable definitions are done
1593 &fun_item a transformation function -- see the documentation
1594 of &fun_item in Automake::Variable::traverse_recursively.
1596 This returns the string C<"\$($RESVAR)">.
1598 C<%options> is a list of options to pass to
1599 C<Variable::traverse_recursively> (see this method).
1603 sub transform_variable_recursively ($$$$$&;%)
1605 my ($var, $resvar, $base, $nodefine, $where, $fun_item, %options) = @_;
1607 $var = ref $var ? $var : rvar $var;
1609 my $res = $var->traverse_recursively
1611 # The code that defines the variable holding the result
1612 # of the recursive transformation of a subvariable.
1614 my ($subvar, $parent_cond, @allresults) = @_;
1615 # If no definition is required, return anything: the result is
1616 # not expected to be used, only the side effect of $fun_item
1618 return 'report-me' if $nodefine;
1619 # Cache $subvar, so that we reuse it if @allresults is the same.
1620 my $key = _hash_varname $subvar;
1621 $_gen_varname{$base}{$key} = $subvar->name;
1623 # Find a name for the variable, unless this is the top-variable
1624 # for which we want to use $resvar.
1625 my ($varname, $generated) =
1626 ($var != $subvar) ? _gen_varname ($base, @allresults) : ($resvar, 1);
1628 # Define the variable if we are not reusing a previously
1629 # defined variable. At the top-level, we can also avoid redefining
1630 # the variable if it already contains the same values.
1632 && !($varname eq $var->name && $key eq _hash_values @allresults))
1634 # If the new variable is the source variable, we assume
1635 # we are trying to override a user variable. Delete
1636 # the old variable first.
1637 variable_delete ($varname) if $varname eq $var->name;
1638 # Define an empty variable in condition TRUE if there is no
1640 @allresults = ([TRUE, '']) unless @allresults;
1641 # Define the rewritten variable in all conditions not
1642 # already covered by user definitions.
1643 foreach my $pair (@allresults)
1645 my ($cond, @result) = @$pair;
1646 my $var = var $varname;
1648 ? $var->not_always_defined_in_cond ($cond)->conds
1653 define ($varname, VAR_AUTOMAKE, '', $_, "@result",
1654 '', $where, VAR_PRETTY);
1659 return "\$($varname)";
1670 L<Automake::VarDef>, L<Automake::Condition>,
1671 L<Automake::DisjConditions>, L<Automake::Location>.
1677 ### Setup "GNU" style for perl-mode and cperl-mode.
1679 ## perl-indent-level: 2
1680 ## perl-continued-statement-offset: 2
1681 ## perl-continued-brace-offset: 0
1682 ## perl-brace-offset: 0
1683 ## perl-brace-imaginary-offset: 0
1684 ## perl-label-offset: -2
1685 ## cperl-indent-level: 2
1686 ## cperl-brace-offset: 0
1687 ## cperl-continued-brace-offset: 0
1688 ## cperl-label-offset: -2
1689 ## cperl-extra-newline-before-brace: t
1690 ## cperl-merge-trailing-else: nil
1691 ## cperl-continued-statement-offset: 2